DeepSeekService.php 724 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068
  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-v4-flash'); // 默认使用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. '3D真人风格' => [
  754. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  755. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  756. ],
  757. ];
  758. if($art_style) {
  759. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  760. }
  761. return $arr;
  762. $arr = [
  763. '唯美真人风格' => [
  764. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  765. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  766. 2. 色彩色调
  767. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  768. 3. 画质精度
  769. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  770. 4. 画面观感
  771. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  772. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  773. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  774. ],
  775. '真人古风风格' => [
  776. 'aliases' => ['真人古风风格', '真人古风'],
  777. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  778. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  779. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  780. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  781. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  782. ],
  783. '日系动漫风格' => [
  784. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  785. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  786. 正向提示词(中文)
  787. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  788. 必须遵守规则
  789. • 全程保持日系动漫风格,不混入其他画风
  790. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  791. • 画面适配所选画面比例,构图居中,主体突出
  792. • 线条干净、色彩统一,不杂乱、不突兀
  793. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  794. ],
  795. '国漫风格' => [
  796. 'aliases' => ['国漫风格', '国漫'],
  797. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  798. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  799. 必须遵守规则
  800. • 严格保持国漫画风,不串风格、不混画风
  801. • 角色形象统一,不随意改变五官、身材、服饰
  802. • 画面构图稳定,适合漫剧叙事展示
  803. • 色调统一,不出现脏色、杂色
  804. 禁止/避免词汇
  805. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  806. ],
  807. 'Q版卡通风格' => [
  808. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  809. 'prompt' => "风格说明
  810. 头大身小,造型可爱圆润,简约干净
  811. 正向提示词(中文)
  812. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  813. 必须遵守规则
  814. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  815. • 角色造型统一,表情可爱,不诡异
  816. • 画面简洁清爽,无多余复杂元素
  817. • 色彩明亮柔和,不刺眼
  818. 禁止/避免词汇
  819. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  820. ],
  821. '简约扁平风格' => [
  822. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  823. 'prompt' => "风格说明
  824. 色块简洁、无复杂渐变,现代极简风
  825. 正向提示词(中文)
  826. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  827. 必须遵守规则
  828. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  829. • 构图简洁,主体突出,无多余装饰
  830. • 色彩统一、干净,不杂乱
  831. 禁止/避免词汇
  832. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  833. ],
  834. '武侠风格' => [
  835. 'aliases' => ['武侠风格', '武侠'],
  836. 'prompt' => "风格说明
  837. 江湖气息,线条硬朗,动作感强
  838. 正向提示词(中文)
  839. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  840. 必须遵守规则
  841. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  842. • 角色形象、服饰、身材比例统一
  843. • 画面动作自然,不扭曲、不畸形
  844. 禁止/避免词汇
  845. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  846. ],
  847. '古风仙侠风格' => [
  848. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  849. 'prompt' => "风格说明
  850. 飘逸汉服、云雾仙气、唯美空灵
  851. 正向提示词(中文)
  852. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  853. 必须遵守规则
  854. • 保持古风仙侠统一画风,不混入现代、科幻元素
  855. • 角色服饰、发型、形象前后一致
  856. • 场景仙气飘逸,色调清雅统一
  857. • 画面唯美柔和,不阴暗、不诡异
  858. 禁止/避免词汇
  859. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  860. ],
  861. '新中式水墨风格' => [
  862. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  863. 'prompt' => "风格说明
  864. 淡墨渲染,毛笔笔触,留白意境
  865. 正向提示词(中文)
  866. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  867. 必须遵守规则
  868. • 严格保持水墨质感,不混入厚涂、写实、卡通
  869. • 色调淡雅统一,不浓艳杂乱
  870. • 画面干净有意境,不堆砌元素
  871. 禁止/避免词汇
  872. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  873. ],
  874. '写实插画风格' => [
  875. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  876. 'prompt' => "风格说明
  877. 接近真人比例,光影真实,质感细腻
  878. 正向提示词(中文)
  879. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  880. 必须遵守规则
  881. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  882. • 角色五官、身材、服饰高度统一
  883. • 画面清晰、光影自然、不扭曲
  884. 禁止/避免词汇
  885. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  886. ],
  887. '3D卡通风格' => [
  888. 'aliases' => ['3D卡通风格', '3D卡通'],
  889. 'prompt' => "风格说明
  890. 3D建模质感,柔和渲染,圆润可爱
  891. 正向提示词(中文)
  892. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  893. 必须遵守规则
  894. • 保持3D卡通统一质感,不出现2D杂乱线条
  895. • 角色模型、比例、形象前后一致
  896. • 画面干净,不模糊、不穿模
  897. 禁止/避免词汇
  898. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  899. ],
  900. '条漫风格' => [
  901. 'aliases' => ['条漫风格', '条漫'],
  902. 'prompt' => "风格说明
  903. 纵向分镜,上下滑动阅读,轻量化
  904. 正向提示词(中文)
  905. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  906. 必须遵守规则
  907. • 保持条漫纵向阅读逻辑,构图简洁
  908. • 画风统一,不混写实、3D、水墨
  909. • 画面干净,不杂乱
  910. 禁止/避免词汇
  911. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  912. ],
  913. '赛博朋克风格' => [
  914. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  915. 'prompt' => "风格说明
  916. 霓虹灯光、未来都市、暗色调、科技机械
  917. 正向提示词(中文)
  918. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  919. 必须遵守规则
  920. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  921. • 色调以暗调+霓虹为主,色彩统一
  922. • 画面科技感强,不杂乱
  923. 禁止/避免词汇
  924. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  925. ],
  926. '暗黑悬疑风格' => [
  927. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  928. 'prompt' => "风格说明
  929. 低饱和、冷色调、阴影重、神秘压抑
  930. 正向提示词(中文)
  931. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  932. 必须遵守规则
  933. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  934. • 画面氛围压抑神秘,但不低俗、不血腥
  935. • 角色形象统一,不崩坏
  936. 禁止/避免词汇
  937. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  938. ],
  939. '治愈清新风格' => [
  940. 'aliases' => ['治愈清新风格', '治愈清新'],
  941. 'prompt' => "风格说明
  942. 马卡龙色系、柔光、温暖干净
  943. 正向提示词(中文)
  944. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  945. 必须遵守规则
  946. • 保持治愈清新统一色调,不阴暗、不诡异
  947. • 画面柔和干净,无杂乱元素
  948. • 角色形象柔和可爱,不狰狞
  949. 禁止/避免词汇
  950. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  951. ],
  952. ];
  953. return $arr;
  954. }
  955. public function getArtStylePromptByInput($inputArtStyle): string
  956. {
  957. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  958. if ($normalizedInput === '') {
  959. return '';
  960. }
  961. return $this->getArtStylePromptMappings($normalizedInput);
  962. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  963. // foreach ($mapping['aliases'] as $alias) {
  964. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  965. // if ($normalizedAlias === '') {
  966. // continue;
  967. // }
  968. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  969. // return $mapping['prompt'];
  970. // }
  971. // }
  972. // }
  973. return '';
  974. }
  975. public function getArtStyleShortPromptByInput($inputArtStyle) {
  976. $stylePrefixes = [
  977. '唯美真人风格' => [
  978. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  979. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  980. ],
  981. '真人古风风格' => [
  982. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  983. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  984. ],
  985. '日系动漫风格' => [
  986. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  987. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  988. ],
  989. '国漫风格' => [
  990. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  991. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  992. ],
  993. 'Q版卡通风格' => [
  994. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  995. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  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. '写实插画风格' => [
  1014. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1015. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1016. ],
  1017. '3D卡通风格' => [
  1018. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1019. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  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. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1035. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1036. ]
  1037. ];
  1038. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1039. }
  1040. private function normalizeArtStyleInput($value): string
  1041. {
  1042. $value = trim((string)$value);
  1043. if ($value === '') {
  1044. return '';
  1045. }
  1046. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1047. return mb_strtolower($value, 'UTF-8');
  1048. }
  1049. private function replaceArtStyleSection(string $content, string $artStyle): string
  1050. {
  1051. if ($content === '' || $artStyle === '') {
  1052. return $content;
  1053. }
  1054. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1055. if (!preg_match($pattern, $content)) {
  1056. return $content;
  1057. }
  1058. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1059. }
  1060. /**
  1061. * DeepSeek流式输出处理方法
  1062. *
  1063. * @param array $post_data DeepSeek API请求参数
  1064. * @return \Generator 返回生成器,用于流式输出
  1065. */
  1066. private function deepSeekStreamResponse($post_data) {
  1067. // 设置最大输出tokens
  1068. $post_data['max_tokens'] = 300000;
  1069. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1070. $response = $client->post($this->url, [
  1071. 'json' => $post_data,
  1072. 'headers' => $this->headers,
  1073. 'stream' => true // 启用流式响应
  1074. ]);
  1075. $body = $response->getBody();
  1076. $fullContent = '';
  1077. $fullReasoningContent = '';
  1078. $usage = [];
  1079. $buffer = '';
  1080. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1081. // 逐行读取流式响应
  1082. while (!$body->eof()) {
  1083. $chunk = $body->read(1024); // 每次读取 1KB
  1084. $buffer .= $chunk;
  1085. // 按行分割
  1086. $lines = explode("\n", $buffer);
  1087. // 保留最后一个不完整的行
  1088. $buffer = array_pop($lines);
  1089. foreach ($lines as $line) {
  1090. $line = trim($line);
  1091. // 跳过空行
  1092. if (empty($line)) {
  1093. continue;
  1094. }
  1095. // 检查是否是 SSE 数据行
  1096. if (strpos($line, 'data: ') !== 0) {
  1097. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1098. continue;
  1099. }
  1100. $data = substr($line, 6); // 移除 "data: " 前缀
  1101. if ($data === '[DONE]') {
  1102. dLog('deepseek')->info('收到结束标记');
  1103. break 2; // 跳出两层循环
  1104. }
  1105. try {
  1106. $json = json_decode($data, true);
  1107. if (json_last_error() !== JSON_ERROR_NONE) {
  1108. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1109. continue;
  1110. }
  1111. if (isset($json['choices'][0]['delta'])) {
  1112. $delta = $json['choices'][0]['delta'];
  1113. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1114. if (isset($delta['reasoning_content'])) {
  1115. $fullReasoningContent .= $delta['reasoning_content'];
  1116. yield [
  1117. 'type' => 'reasoning',
  1118. 'content' => $delta['reasoning_content'],
  1119. 'full_reasoning' => $fullReasoningContent
  1120. ];
  1121. }
  1122. // 处理最终回答内容
  1123. if (isset($delta['content'])) {
  1124. $fullContent .= $delta['content'];
  1125. yield [
  1126. 'type' => 'content',
  1127. 'content' => $delta['content'],
  1128. ];
  1129. }
  1130. }
  1131. // 获取使用统计信息
  1132. if (isset($json['usage'])) {
  1133. $usage = $json['usage'];
  1134. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1135. }
  1136. } catch (\Exception $e) {
  1137. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1138. continue;
  1139. }
  1140. }
  1141. }
  1142. dLog('deepseek')->info('流式读取完成', [
  1143. 'content_length' => strlen($fullContent),
  1144. 'reasoning_length' => strlen($fullReasoningContent)
  1145. ]);
  1146. yield [
  1147. 'type' => 'done',
  1148. 'full_content' => $fullContent,
  1149. 'full_reasoning' => $fullReasoningContent,
  1150. 'usage' => $usage
  1151. ];
  1152. }
  1153. /**
  1154. * GPT 重试次数(env 可配置,默认 5 次)
  1155. */
  1156. private function gptRetryTimes()
  1157. {
  1158. return (int)env('GPT_RETRY_TIMES', 5);
  1159. }
  1160. /**
  1161. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1162. */
  1163. private function gptRetryInterval()
  1164. {
  1165. return (int)env('GPT_RETRY_INTERVAL', 10);
  1166. }
  1167. /**
  1168. * 判断 GPT 请求异常是否可重试
  1169. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1170. */
  1171. private function isGptRetryableException(\Exception $e)
  1172. {
  1173. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1174. return false;
  1175. }
  1176. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1177. $status = $e->getResponse()->getStatusCode();
  1178. return $status >= 500 || $status == 429;
  1179. }
  1180. return true;
  1181. }
  1182. /**
  1183. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1184. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1185. */
  1186. private function checkGptServiceAvailable()
  1187. {
  1188. $apiKey = env('GPT_54_API_KEY');
  1189. if (empty($apiKey)) {
  1190. return false;
  1191. }
  1192. try {
  1193. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1194. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1195. 'headers' => [
  1196. 'Authorization' => 'Bearer ' . $apiKey,
  1197. 'Content-Type' => 'application/json'
  1198. ]
  1199. ]);
  1200. $status = $response->getStatusCode();
  1201. return $status < 500 && $status != 429;
  1202. } catch (\Exception $e) {
  1203. return false;
  1204. }
  1205. }
  1206. /**
  1207. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1208. * 全部失败抛出友好错误
  1209. */
  1210. private function ensureGptServiceAvailable()
  1211. {
  1212. $maxRetries = $this->gptRetryTimes();
  1213. $interval = $this->gptRetryInterval();
  1214. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1215. if ($this->checkGptServiceAvailable()) {
  1216. return;
  1217. }
  1218. if ($attempt < $maxRetries) {
  1219. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1220. 'retry' => $attempt + 1,
  1221. 'max_retries' => $maxRetries
  1222. ]);
  1223. sleep($interval);
  1224. }
  1225. }
  1226. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1227. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1228. 'max_retries' => $maxRetries,
  1229. 'interval' => $interval
  1230. ]);
  1231. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1232. }
  1233. /**
  1234. * GPT 流式输出处理方法
  1235. *
  1236. * @param array $post_data GPT API请求参数
  1237. * @return \Generator 返回生成器,用于流式输出
  1238. */
  1239. private function gpt54StreamResponse($post_data) {
  1240. $apiKey = env('GPT_54_API_KEY');
  1241. if (empty($apiKey)) {
  1242. Utils::throwError('20003:GPT API Key未配置');
  1243. }
  1244. // 先探活,服务不可用时自动重试
  1245. $this->ensureGptServiceAvailable();
  1246. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1247. $headers = [
  1248. 'Authorization' => 'Bearer ' . $apiKey,
  1249. 'Content-Type' => 'application/json'
  1250. ];
  1251. // 移除 thinking 参数,GPT-5.4 不支持
  1252. if (isset($post_data['thinking'])) {
  1253. unset($post_data['thinking']);
  1254. }
  1255. if (isset($post_data['reasoning_effort'])) {
  1256. unset($post_data['reasoning_effort']);
  1257. }
  1258. $post_data['max_completion_tokens'] = 100000;
  1259. $maxRetries = $this->gptRetryTimes();
  1260. $interval = $this->gptRetryInterval();
  1261. $attempt = 0;
  1262. while (true) {
  1263. $fullContent = '';
  1264. $usage = [];
  1265. $buffer = '';
  1266. try {
  1267. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1268. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1269. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1270. 'json' => $post_data,
  1271. 'headers' => $headers,
  1272. 'stream' => true // 启用流式响应
  1273. ]);
  1274. $body = $response->getBody();
  1275. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1276. // 逐行读取流式响应
  1277. while (!$body->eof()) {
  1278. $chunk = $body->read(1024); // 每次读取 1KB
  1279. $buffer .= $chunk;
  1280. // 按行分割
  1281. $lines = explode("\n", $buffer);
  1282. // 保留最后一个不完整的行
  1283. $buffer = array_pop($lines);
  1284. foreach ($lines as $line) {
  1285. $line = trim($line);
  1286. // 跳过空行
  1287. if (empty($line)) {
  1288. continue;
  1289. }
  1290. // 检查是否是 SSE 数据行
  1291. if (strpos($line, 'data: ') !== 0) {
  1292. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1293. continue;
  1294. }
  1295. $data = substr($line, 6); // 移除 "data: " 前缀
  1296. if ($data === '[DONE]') {
  1297. dLog('deepseek')->info('收到结束标记');
  1298. break 2; // 跳出 foreach 和流读取循环
  1299. }
  1300. try {
  1301. $json = json_decode($data, true);
  1302. if (json_last_error() !== JSON_ERROR_NONE) {
  1303. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1304. continue;
  1305. }
  1306. if (isset($json['choices'][0]['delta'])) {
  1307. $delta = $json['choices'][0]['delta'];
  1308. // 处理回答内容
  1309. if (isset($delta['content'])) {
  1310. $fullContent .= $delta['content'];
  1311. yield [
  1312. 'type' => 'content',
  1313. 'content' => $delta['content'],
  1314. ];
  1315. }
  1316. }
  1317. // 获取使用统计信息
  1318. if (isset($json['usage'])) {
  1319. $usage = $json['usage'];
  1320. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1321. }
  1322. } catch (\Exception $e) {
  1323. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1324. continue;
  1325. }
  1326. }
  1327. }
  1328. dLog('deepseek')->info('流式读取完成', [
  1329. 'content_length' => strlen($fullContent)
  1330. ]);
  1331. yield [
  1332. 'type' => 'done',
  1333. 'full_content' => $fullContent,
  1334. 'full_reasoning' => '',
  1335. 'usage' => $usage
  1336. ];
  1337. return;
  1338. } catch (\Exception $e) {
  1339. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1340. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1341. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1342. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1343. throw $e;
  1344. }
  1345. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1346. 'retry' => $attempt + 1,
  1347. 'max_retries' => $maxRetries,
  1348. 'error' => $e->getMessage()
  1349. ]);
  1350. sleep($interval);
  1351. $attempt++;
  1352. }
  1353. }
  1354. }
  1355. // 与推理模型对话
  1356. public function chatWithReasoner($data) {
  1357. $content = getProp($data, 'content');
  1358. $model = getProp($data, 'model', 'r1');
  1359. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1360. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1361. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1362. if ($model == 'r1') {
  1363. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1364. $thinkingMode = 'disabled';
  1365. } else {
  1366. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1367. $thinkingMode = 'disabled';
  1368. }
  1369. // 获取可选情感(根据音色可支持情感选)
  1370. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1371. $emotion_list = [];
  1372. foreach ($timbre_emotion as $emotion) {
  1373. $tmp = explode(',', $emotion);
  1374. $emotion_list = array_merge($emotion_list, $tmp);
  1375. }
  1376. $emotion_list = array_unique($emotion_list);
  1377. $emotion_str = implode('、', $emotion_list);
  1378. // // 获取可选情感
  1379. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1380. // $emotion_str = implode('、', $emotion_list);
  1381. // 是否启用情感
  1382. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1383. if ($enable_emotion) {
  1384. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1385. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1386. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1387. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1388. }else {
  1389. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1390. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1391. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1392. }
  1393. $messages = [
  1394. [
  1395. 'role' => 'system',
  1396. 'content' => $sys_content
  1397. ],
  1398. [
  1399. 'role' => 'user',
  1400. 'content' => $content
  1401. ]
  1402. ];
  1403. $post_data = [
  1404. 'model' => $model,
  1405. 'messages' => $messages,
  1406. // 'max_tokens' => 8192,
  1407. 'temperature' => 1,
  1408. 'frequency_penalty' => 0,
  1409. 'presence_penalty' => 0,
  1410. 'thinking' => ['type' => $thinkingMode],
  1411. 'response_format' => [
  1412. 'type' => 'text'
  1413. ],
  1414. 'stream' => false
  1415. ];
  1416. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1417. // 根据模型类型选择调用方法
  1418. $fullContent = '';
  1419. $usage = [];
  1420. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1421. // DeepSeek 官方模型使用 DeepSeek API
  1422. $chatResult = $this->chatOnly($post_data);
  1423. } else if (in_array($model, $this->gpt_text_models)) {
  1424. // GPT-5.4 模型使用 TokenRouter API
  1425. $chatResult = $this->gpt54ChatOnly($post_data);
  1426. } else {
  1427. // 其他模型使用火山引擎API
  1428. $chatResult = $this->volcEngineChatCompletion($post_data);
  1429. }
  1430. if (is_array($chatResult)) {
  1431. $fullContent = $chatResult['fullContent'];
  1432. $usage = $chatResult['usage'];
  1433. }
  1434. // 处理获取到的剧本数据
  1435. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1436. $result = [
  1437. 'origin_content' => $fullContent,
  1438. 'roles' => getProp($script_content, 'roles'),
  1439. 'words' => getProp($script_content, 'words'),
  1440. ];
  1441. return $result;
  1442. }
  1443. public function resetParagraphAudio($data) {
  1444. $bid = getProp($data, 'bid');
  1445. $cid = getProp($data, 'cid');
  1446. $version_id = getProp($data, 'version_id');
  1447. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1448. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1449. 'generate_status' => '待制作',
  1450. 'updated_at' => date('Y-m-d H:i:s')
  1451. ]);
  1452. }
  1453. public function saveParagraphAudio($data) {
  1454. $bid = getProp($data, 'bid');
  1455. $cid = getProp($data, 'cid');
  1456. $version_id = getProp($data, 'version_id');
  1457. $sequence = getProp($data, 'sequence');
  1458. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1459. // 获取所有情感
  1460. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1461. $emotion_list = array_flip($emotion_list);
  1462. // 获取音色支持情感
  1463. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1464. $timbre_emotion = explode(',', $timbre_emotion);
  1465. $emotion = getProp($data, 'emotion');
  1466. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1467. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1468. $list = [
  1469. 'bid' => $bid,
  1470. 'cid' => $cid,
  1471. 'version_id' => $version_id,
  1472. 'sequence' => $sequence,
  1473. 'role' => getProp($data, 'role'),
  1474. 'gender' => getProp($data, 'gender'),
  1475. 'text' => trim(getProp($data, 'text')),
  1476. 'emotion' => $emotion,
  1477. 'emotion_type' => $emotion_type,
  1478. 'voice_type' => getProp($data, 'voice_type'),
  1479. 'voice_name' => getProp($data, 'voice_name'),
  1480. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1481. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1482. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1483. 'pitch' => getProp($data, 'pitch', 0),
  1484. // 'paragraph_audio_url' => '',
  1485. 'generate_status' => '制作中',
  1486. 'error_msg' => '',
  1487. 'updated_at' => date('Y-m-d H:i:s')
  1488. ];
  1489. $continue = false;
  1490. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1491. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1492. $list['generate_status'] = '制作成功';
  1493. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1494. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1495. $continue = true;
  1496. }
  1497. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1498. if ($id) {
  1499. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1500. }else {
  1501. $list['created_at'] = date('Y-m-d H:i:s');
  1502. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1503. $boolen = $id ? true : false;
  1504. }
  1505. // 如果更新成功则加入查询队列
  1506. if ($boolen) {
  1507. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1508. Redis::sadd($redis_key, $id);
  1509. }
  1510. if ($boolen && !$continue) {
  1511. $boolen = false;
  1512. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1513. // 根据ID通过API通知合成音频
  1514. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1515. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1516. $response = $result->getBody()->getContents();
  1517. $response_arr = json_decode($response, true);
  1518. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1519. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1520. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1521. Utils::throwError('20003:通知火山生成段落音频失败');
  1522. }
  1523. $boolen = true;
  1524. }
  1525. return $boolen;
  1526. }
  1527. public function insertAudioEffect($data) {
  1528. $audio_id = getProp($data, 'audio_id');
  1529. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1530. $bid = getProp($chapter_audio, 'bid');
  1531. $version_id = getProp($chapter_audio, 'version_id');
  1532. $cid = getProp($chapter_audio, 'cid');
  1533. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1534. $audio_effect_json = getProp($data, 'audio_effect_json');
  1535. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1536. try {
  1537. DB::beginTransaction();
  1538. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1539. if (!$count) {
  1540. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1541. }else {
  1542. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1543. }
  1544. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1545. 'audio_effect_status' => '添加中',
  1546. 'audio_effect_json' => $audio_effect_json,
  1547. 'updated_at' => date('Y-m-d H:i:s')
  1548. ]);
  1549. if (!$boolen1) {
  1550. DB::rollBack();
  1551. Utils::throwError('20003:更新生成数据失败');
  1552. }
  1553. $id = DB::table('mp_audio_tasks')->insertGetId([
  1554. 'audio_id' => $audio_id,
  1555. 'generate_status' => '执行中',
  1556. 'generate_json' => json_encode([], 256),
  1557. 'bid' => $bid,
  1558. 'book_name' => getProp($chapter_audio, 'book_name'),
  1559. 'version_id' => $version_id,
  1560. 'version_name' => getProp($chapter_audio, 'version_name'),
  1561. 'cid' => $cid,
  1562. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1563. 'task_name' => $task_name,
  1564. 'created_at' => date('Y-m-d H:i:s'),
  1565. 'updated_at' => date('Y-m-d H:i:s')
  1566. ]);
  1567. if (!$id) {
  1568. DB::rollBack();
  1569. Utils::throwError('20003:创建任务失败');
  1570. }
  1571. }catch (\Exception $e) {
  1572. DB::rollBack();
  1573. Utils::throwError('20003:'.$e->getMessage());
  1574. }
  1575. DB::commit();
  1576. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1577. // 根据ID通过API通知合成音频
  1578. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1579. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1580. $response = $result->getBody()->getContents();
  1581. $response_arr = json_decode($response, true);
  1582. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1583. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1584. Log::info('通知火山插入音效失败: '.$error_msg);
  1585. Utils::throwError('20003:通知火山插入音效失败');
  1586. }
  1587. return true;
  1588. }
  1589. public function insertBgm($data) {
  1590. $audio_id = getProp($data, 'audio_id');
  1591. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1592. $bid = getProp($chapter_audio, 'bid');
  1593. $version_id = getProp($chapter_audio, 'version_id');
  1594. $cid = getProp($chapter_audio, 'cid');
  1595. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1596. $bgm_json = getProp($data, 'bgm_json');
  1597. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1598. if (!$bgm_json) {
  1599. $bgm_json = getProp($data, 'audio_effect_json');
  1600. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1601. }
  1602. try {
  1603. DB::beginTransaction();
  1604. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1605. if (!$count) {
  1606. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1607. }else {
  1608. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1609. }
  1610. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1611. 'bgm_status' => '添加中',
  1612. 'bgm_json' => $bgm_json,
  1613. 'updated_at' => date('Y-m-d H:i:s')
  1614. ]);
  1615. if (!$boolen1) {
  1616. DB::rollBack();
  1617. Utils::throwError('20003:更新生成数据失败');
  1618. }
  1619. $id = DB::table('mp_audio_tasks')->insertGetId([
  1620. 'audio_id' => $audio_id,
  1621. 'generate_status' => '执行中',
  1622. 'generate_json' => json_encode([], 256),
  1623. 'bid' => $bid,
  1624. 'book_name' => getProp($chapter_audio, 'book_name'),
  1625. 'version_id' => $version_id,
  1626. 'version_name' => getProp($chapter_audio, 'version_name'),
  1627. 'cid' => $cid,
  1628. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1629. 'task_name' => $task_name,
  1630. 'created_at' => date('Y-m-d H:i:s'),
  1631. 'updated_at' => date('Y-m-d H:i:s')
  1632. ]);
  1633. if (!$id) {
  1634. DB::rollBack();
  1635. Utils::throwError('20003:创建任务失败');
  1636. }
  1637. }catch (\Exception $e) {
  1638. DB::rollBack();
  1639. Utils::throwError('20003:'.$e->getMessage());
  1640. }
  1641. DB::commit();
  1642. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1643. // 根据ID通过API通知合成音频
  1644. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1645. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1646. $response = $result->getBody()->getContents();
  1647. $response_arr = json_decode($response, true);
  1648. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1649. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1650. Log::info('通知火山插入bgm失败: '.$error_msg);
  1651. Utils::throwError('20003:通知火山插入bgm失败');
  1652. }
  1653. return true;
  1654. }
  1655. public function getParagraphAudios($data) {
  1656. $bid = getProp($data, 'bid');
  1657. $cid = getProp($data, 'cid');
  1658. $version_id = getProp($data, 'version_id');
  1659. $sequence = getProp($data, 'sequence');
  1660. // 获取已生成的音频
  1661. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1662. if ($sequence) $query->where('sequence', $sequence);
  1663. $paragraph_audios = $query->orderBy('sequence')->get();
  1664. $result = [];
  1665. foreach($paragraph_audios as $item) {
  1666. $result[] = [
  1667. 'sequence' => getProp($item, 'sequence'),
  1668. 'role' => getProp($item, 'role'),
  1669. 'gender' => getProp($item, 'gender'),
  1670. 'text' => trim(getProp($item, 'text')),
  1671. 'emotion' => getProp($item, 'emotion'),
  1672. 'emotion_type' => getProp($item, 'emotion_type'),
  1673. 'voice_type' => getProp($item, 'voice_type'),
  1674. 'voice_name' => getProp($item, 'voice_name'),
  1675. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1676. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1677. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1678. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1679. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1680. ];
  1681. }
  1682. return $result;
  1683. }
  1684. // 新增合成任务
  1685. public function addGenerateTask($data) {
  1686. $bid = getProp($data, 'bid');
  1687. $cid = getProp($data, 'cid');
  1688. $version_id = getProp($data, 'version_id');
  1689. $generate_json = getProp($data, 'generate_json');
  1690. // 获取已生成的音频
  1691. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1692. $paragraph_list = [];
  1693. foreach($paragraph_audios as $item) {
  1694. $paragraph_list[getProp($item, 'sequence')] = [
  1695. 'role' => getProp($item, 'role'),
  1696. 'gender' => getProp($item, 'gender'),
  1697. 'text' => trim(getProp($item, 'text')),
  1698. 'emotion' => getProp($item, 'emotion'),
  1699. 'emotion_type' => getProp($item, 'emotion_type'),
  1700. 'voice_type' => getProp($item, 'voice_type'),
  1701. 'voice_name' => getProp($item, 'voice_name'),
  1702. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1703. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1704. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1705. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1706. ];
  1707. }
  1708. // 更新角色-音色信息
  1709. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1710. $existed_role_info = json_decode($existed_role_info, true);
  1711. if (!$existed_role_info) $existed_role_info = [];
  1712. // 获取情感信息
  1713. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1714. $emotion_list = array_flip($emotion_list);
  1715. // 获取音色对应情感组
  1716. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1717. $timbre_emotion_list = [];
  1718. foreach($timbre_emotions as $item) {
  1719. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1720. }
  1721. // 构造生成音频的json
  1722. $words = json_decode($generate_json, true);
  1723. // 最终合成前的参数组
  1724. $mp_chapter_paragraph_audios = [];
  1725. $sequence = 1;
  1726. $complete_paragraph_sequences = [];
  1727. foreach($words as &$word) {
  1728. 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:参数格式有误');
  1729. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1730. $role = getProp($word, 'role');
  1731. $word['gender'] = (int)$word['gender'];
  1732. // 判断音色对应情感是否支持,不支持则调整为中性
  1733. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1734. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1735. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1736. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1737. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1738. }else {
  1739. $word['emotion'] = '中性';
  1740. $word['emotion_type'] = 'neutral';
  1741. }
  1742. $existed_role_info[$role] = [
  1743. 'timbre_type' => $word['voice_type'],
  1744. 'timbre_name' => $word['voice_name'],
  1745. 'emotion' => $word['emotion'],
  1746. 'emotion_type' => $word['emotion_type'],
  1747. 'speed_ratio' => $word['speed_ratio'],
  1748. 'loudness_ratio'=> $word['loudness_ratio'],
  1749. 'emotion_scale' => $word['emotion_scale'],
  1750. 'pitch' => $word['pitch']
  1751. ];
  1752. $word['paragraph_audio_url'] = '';
  1753. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1754. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1755. // 如果音频存在并且参数都未改变则使用已生成的音频
  1756. if (getProp($paragraph, 'paragraph_audio_url')) {
  1757. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1758. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1759. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1760. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1761. // {
  1762. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1763. // }
  1764. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1765. }
  1766. $tmp = $word;
  1767. // 组装章节分句音频数据
  1768. // $tmp['sequence'] = getProp($word, 'sequence');
  1769. // $tmp['text'] = getProp($word, 'text');
  1770. // $tmp['emotion'] = getProp($word, 'emotion');
  1771. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1772. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1773. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1774. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1775. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1776. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1777. $tmp['bid'] = $bid;
  1778. $tmp['version_id'] = $version_id;
  1779. $tmp['cid'] = $cid;
  1780. $tmp['sequence'] = $sequence;
  1781. $tmp['created_at'] = date('Y-m-d H:i:s');
  1782. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1783. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1784. $mp_chapter_paragraph_audios[] = $tmp;
  1785. $complete_paragraph_sequences[] = $sequence;
  1786. $sequence++;
  1787. }
  1788. $generate_json = json_encode($words, 256);
  1789. // 判断是否有未生成字幕的段落
  1790. $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();
  1791. if ($no_subtitle_sequences) {
  1792. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1793. }
  1794. try {
  1795. DB::beginTransaction();
  1796. $role_info = json_encode($existed_role_info, 256);
  1797. $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')]);
  1798. if (!$boolen) {
  1799. DB::rollBack();
  1800. Utils::throwError('20003:更新角色信息失败');
  1801. }
  1802. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1803. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1804. if (!$count) {
  1805. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1806. }else {
  1807. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1808. }
  1809. $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')]);
  1810. if (!$boolen1) {
  1811. DB::rollBack();
  1812. Utils::throwError('20003:更新生成数据失败');
  1813. }
  1814. $id = DB::table('mp_audio_tasks')->insertGetId([
  1815. 'audio_id' => getProp($chapter_audio, 'id'),
  1816. 'generate_status' => '执行中',
  1817. 'generate_json' => $generate_json,
  1818. 'bid' => $bid,
  1819. 'book_name' => getProp($chapter_audio, 'book_name'),
  1820. 'version_id' => $version_id,
  1821. 'version_name' => getProp($chapter_audio, 'version_name'),
  1822. 'cid' => $cid,
  1823. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1824. 'task_name' => $task_name,
  1825. 'created_at' => date('Y-m-d H:i:s'),
  1826. 'updated_at' => date('Y-m-d H:i:s')
  1827. ]);
  1828. if (!$id) {
  1829. DB::rollBack();
  1830. Utils::throwError('20003:创建任务失败');
  1831. }
  1832. // 删除不在段落序号范围内的其他数据
  1833. if ($complete_paragraph_sequences) {
  1834. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1835. }
  1836. // // 删除章节分句音频数据并重新插入
  1837. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1838. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1839. // if (!$boolen3) {
  1840. // DB::rollBack();
  1841. // Utils::throwError('20003:更新章节分句音频失败');
  1842. // }
  1843. } catch (\Exception $e) {
  1844. DB::rollBack();
  1845. Utils::throwError('20003:'.$e->getMessage());
  1846. }
  1847. DB::commit();
  1848. // 通知火山生成音频
  1849. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1850. // 根据ID通过API通知合成音频
  1851. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1852. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1853. $response = $result->getBody()->getContents();
  1854. $response_arr = json_decode($response, true);
  1855. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1856. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1857. Log::info('通知火山生成音频失败: '.$error_msg);
  1858. Utils::throwError('20003:通知火山生成音频失败');
  1859. }
  1860. return true;
  1861. }
  1862. public function timbreList($data) {
  1863. $gender = getProp($data, 'gender');
  1864. $timbre_name = getProp($data, 'voice_name');
  1865. $category_id = getProp($data, 'category_id');
  1866. $age_stage = getProp($data, 'age_stage');
  1867. $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');
  1868. if ($gender) {
  1869. $query->where('gender', $gender);
  1870. }
  1871. if ($timbre_name) {
  1872. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1873. }
  1874. if ($category_id) {
  1875. $query->where(function ($query) use ($category_id) {
  1876. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1877. });
  1878. }
  1879. if ($age_stage) {
  1880. $query->where('age_stage', $age_stage);
  1881. }
  1882. $list = $query->get()->map(function ($value) {
  1883. $value = (array)$value;
  1884. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1885. return $value;
  1886. })->toArray();
  1887. return $list;
  1888. }
  1889. // 生成火山临时token
  1890. public function setStsToken() {
  1891. // ************* 配置参数 *************
  1892. $method = 'GET';
  1893. $service = 'sts';
  1894. $host = 'open.volcengineapi.com';
  1895. $region = env('VOLC_REGION');
  1896. $endpoint = 'https://open.volcengineapi.com';
  1897. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1898. $access_key = env('VOLC_AK');
  1899. $secret_key = env('VOLC_SK');
  1900. // 获取缓存中的token,如果没有则请求接口
  1901. $token = Redis::get('volc_sts_token');
  1902. if (!$token) {
  1903. // 查询参数
  1904. $query_parameters = [
  1905. 'Action' => 'AssumeRole',
  1906. 'RoleSessionName' => 'user@zw',
  1907. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1908. 'Version' => '2018-01-01'
  1909. ];
  1910. // 生成URL编码的查询字符串
  1911. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1912. // 获取签名头信息
  1913. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1914. // 构建完整URL
  1915. $request_url = $endpoint . '?' . $request_parameters;
  1916. $client = new Client(['verify' => false]);
  1917. $response = $client->get($request_url, ['headers' => $headers]);
  1918. $response_arr = json_decode($response->getBody()->getContents(), true);
  1919. $result = [
  1920. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1921. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1922. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1923. 'Region' => env('VOLC_REGION'),
  1924. 'Endpoint' => env('VOLC_END_POINT'),
  1925. 'Bucket' => env('VOLC_BUCKET'),
  1926. ];
  1927. // 缓存token
  1928. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1929. return $result;
  1930. } else {
  1931. return json_decode($token, true);
  1932. }
  1933. // $response = $response['Response'];
  1934. // $access_key = $response['Credentials']['AccessKeyId'];
  1935. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1936. // $security_token = $response['Credentials']['SecurityToken'];
  1937. // $expiration = $response['Credentials']['Expiration'];
  1938. // dd($response_arr);
  1939. }
  1940. public function emotionGroups($data) {
  1941. $id = getProp($data, 'group_id');
  1942. $group_name = getProp($data, 'group_name');
  1943. $voice_type = getProp($data, 'voice_type');
  1944. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1945. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1946. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1947. if ($group_name) {
  1948. $query->where('group_name', 'like', "%{$group_name}%");
  1949. }
  1950. if ($id) {
  1951. $query->where('id', $id);
  1952. }
  1953. if ($voice_type) {
  1954. $query->where('voice_type', $voice_type);
  1955. }
  1956. return $query->orderBy('id')->get()->map(function ($value) {
  1957. return (array)$value;
  1958. })->toArray();
  1959. }
  1960. private function sign($key, $msg) {
  1961. return hash_hmac('sha256', $msg, $key, true);
  1962. }
  1963. // 生成签名密钥
  1964. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1965. $kDate = $this->sign($key, $dateStamp);
  1966. $kRegion = $this->sign($kDate, $regionName);
  1967. $kService = $this->sign($kRegion, $serviceName);
  1968. $kSigning = $this->sign($kService, 'request');
  1969. return $kSigning;
  1970. }
  1971. // 获取签名头信息
  1972. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1973. $contenttype = 'application/x-www-form-urlencoded';
  1974. $accept = 'application/json';
  1975. // 获取当前UTC时间
  1976. $t = new DateTime('now', new DateTimeZone('UTC'));
  1977. $xdate = $t->format('Ymd\THis\Z');
  1978. $datestamp = $t->format('Ymd');
  1979. // 1. 拼接规范请求串
  1980. $canonical_uri = '/';
  1981. $canonical_querystring = $request_parameters;
  1982. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1983. $signed_headers = 'content-type;host;x-date';
  1984. // 空请求体的SHA256哈希
  1985. $payload_hash = hash('sha256', '');
  1986. $canonical_request = implode("\n", [
  1987. $method,
  1988. $canonical_uri,
  1989. $canonical_querystring,
  1990. $canonical_headers,
  1991. $signed_headers,
  1992. $payload_hash
  1993. ]);
  1994. // 2. 拼接待签名字符串
  1995. $algorithm = 'HMAC-SHA256';
  1996. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1997. $hashed_canonical_request = hash('sha256', $canonical_request);
  1998. $string_to_sign = implode("\n", [
  1999. $algorithm,
  2000. $xdate,
  2001. $credential_scope,
  2002. $hashed_canonical_request
  2003. ]);
  2004. // 3. 计算签名
  2005. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2006. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2007. // 4. 添加签名到请求头
  2008. $authorization_header = sprintf(
  2009. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2010. $algorithm,
  2011. $access_key,
  2012. $credential_scope,
  2013. $signed_headers,
  2014. $signature
  2015. );
  2016. return [
  2017. 'Accept' => $accept,
  2018. 'Content-Type' => $contenttype,
  2019. 'X-Date' => $xdate,
  2020. 'Authorization' => $authorization_header
  2021. ];
  2022. }
  2023. // 文字合成语音(火山引擎)
  2024. public function tts($data) {
  2025. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2026. $headers = [
  2027. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2028. 'Content-Type' => 'application/json; charset=UTF-8'
  2029. ];
  2030. $post_data = [
  2031. 'app' => [
  2032. 'appid' => env('VOLC_APPID'),
  2033. 'token' => env('VOLC_TOKEN'),
  2034. 'cluster' => 'volcano_tts'
  2035. ],
  2036. 'user' => [
  2037. 'uid' => 'mp_audio'
  2038. ],
  2039. // 'audio' => [
  2040. // 'voice_type' =>
  2041. // ],
  2042. ];
  2043. }
  2044. public function scriptList($data) {
  2045. $uid = Site::getUid();
  2046. $script_id = getProp($data, 'script_id');
  2047. $script_name = getProp($data, 'script_name');
  2048. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2049. if ($script_id) {
  2050. $query->where('id', $script_id);
  2051. }
  2052. if ($script_name) {
  2053. $query->where('script_name', 'like', "%{$script_name}%");
  2054. }
  2055. return $query->orderBy('created_at', 'desc')->paginate(12);
  2056. }
  2057. public function scripts($data) {
  2058. $uid = Site::getUid();
  2059. $script_id = getProp($data, 'script_id');
  2060. $script_name = getProp($data, 'script_name');
  2061. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2062. if ($script_id) {
  2063. $query->where('id', $script_id);
  2064. }
  2065. if ($script_name) {
  2066. $query->where('script_name', 'like', "%{$script_name}%");
  2067. }
  2068. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2069. return (array)$value;
  2070. })->toArray();
  2071. }
  2072. public function scriptInfo($data) {
  2073. $uid = Site::getUid();
  2074. $script_id = getProp($data, 'script_id');
  2075. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2076. // ->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();
  2077. ->selectRaw('id as script_id, script_name')->first();
  2078. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2079. $script = (array)$script;
  2080. // 获取分集组信息
  2081. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2082. ->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')
  2083. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2084. $value = (array)$value;
  2085. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2086. return (array)$value;
  2087. })->toArray();
  2088. $script['group'] = $groups;
  2089. return $script;
  2090. }
  2091. public function createScript($data) {
  2092. $script_name = getProp($data, 'script_name');
  2093. $uid = Site::getUid(); // 获取当前用户ID
  2094. $cpid = Site::getCpid(); // 获取当前公司组ID
  2095. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2096. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2097. $script_name .= '_'.date('YmdHis');
  2098. }
  2099. return DB::table('mp_scripts')->insertGetId([
  2100. 'script_name' => $script_name,
  2101. 'user_id' => $uid,
  2102. 'cpid' => $cpid,
  2103. 'created_at' => date('Y-m-d H:i:s'),
  2104. 'updated_at' => date('Y-m-d H:i:s')
  2105. ]);
  2106. }
  2107. public function editScript($data) {
  2108. $script_id = getProp($data, 'script_id');
  2109. $script_name = getProp($data, 'script_name');
  2110. $uid = Site::getUid(); // 获取当前用户ID
  2111. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2112. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2113. if ($id && (int)$id !== (int)$script_id) {
  2114. $script_name .= '_'.date('YmdHis');
  2115. }
  2116. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2117. 'script_name' => $script_name,
  2118. 'updated_at' => date('Y-m-d H:i:s')
  2119. ]);
  2120. }
  2121. public function delScript($data) {
  2122. $script_id = getProp($data, 'script_id');
  2123. $uid = Site::getUid(); // 获取当前用户ID
  2124. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2125. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2126. 'is_deleted' => 1,
  2127. 'updated_at' => date('Y-m-d H:i:s')
  2128. ]);
  2129. }
  2130. public function createEpisode($data) {
  2131. $script_id = getProp($data, 'script_id');
  2132. $group_name = getProp($data, 'group_name');
  2133. $remark = getProp($data, 'remark');
  2134. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2135. $uid = Site::getUid(); // 获取当前用户ID
  2136. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2137. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2138. $group_name .= '_'.date('YmdHis');
  2139. }
  2140. return DB::table('mp_script_episode_group')->insertGetId([
  2141. 'script_id' => $script_id,
  2142. 'group_name' => $group_name,
  2143. 'user_id' => $uid,
  2144. 'remark' => $remark,
  2145. 'created_at' => date('Y-m-d H:i:s'),
  2146. 'updated_at' => date('Y-m-d H:i:s')
  2147. ]);
  2148. }
  2149. public function editEpisode($data) {
  2150. $group_id = getProp($data, 'group_id');
  2151. $start_episode_number = getProp($data, 'start_episode_number');
  2152. $end_episode_number = getProp($data, 'end_episode_number');
  2153. $group_name = getProp($data, 'group_name');
  2154. $uid = Site::getUid(); // 获取当前用户ID
  2155. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2156. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2157. if ($id && (int)$id !== (int)$group_id) {
  2158. $group_name .= '_'.date('YmdHis');
  2159. }
  2160. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2161. 'group_name' => $group_name,
  2162. 'start_episode_number' => $start_episode_number,
  2163. 'end_episode_number' => $end_episode_number,
  2164. 'updated_at' => date('Y-m-d H:i:s')
  2165. ]);
  2166. }
  2167. public function delEpisode($data) {
  2168. $group_id = getProp($data, 'group_id');
  2169. $uid = Site::getUid(); // 获取当前用户ID
  2170. if (!$group_id) Utils::throwError('20003:请选择分集');
  2171. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2172. 'is_deleted' => 1,
  2173. 'updated_at' => date('Y-m-d H:i:s')
  2174. ]);
  2175. }
  2176. /**
  2177. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2178. *
  2179. * @param array $data 包含以下参数:
  2180. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2181. * - question: 用户问题(可选)
  2182. * - model: 使用的模型(r1 或 v3,默认 v3)
  2183. * @return \Generator 返回生成器,用于流式输出
  2184. */
  2185. public function generateEpisodes($data) {
  2186. $script_id = getProp($data, 'script_id');
  2187. $group_id = getProp($data, 'group_id');
  2188. // $file = getProp($data, 'file');
  2189. $file = '';
  2190. $content = getProp($data, 'content', '');
  2191. // $bid = getProp($data, 'bid', 0);
  2192. $bid = 0;
  2193. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2194. if (!$group) {
  2195. Utils::throwError('20003:剧本分集不存在');
  2196. }
  2197. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2198. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2199. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2200. $prompt = getProp($data, 'prompt');
  2201. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2202. $model = getProp($data, 'model');
  2203. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2204. Utils::throwError('20003:该模型不存在!');
  2205. }
  2206. // 检查是否存在重叠的剧集序号范围
  2207. $exists_groups = DB::table('mp_script_episode_group')
  2208. ->where('script_id', $script_id)
  2209. ->where('id', '<>', $group_id) // 排除当前组
  2210. ->where('is_deleted', 0)
  2211. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2212. // 检查新范围是否与现有范围重叠
  2213. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2214. // 新范围的开始在现有范围内
  2215. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2216. ->where('end_episode_number', '>=', $start_episode_sequence);
  2217. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2218. // 新范围的结束在现有范围内
  2219. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2220. ->where('end_episode_number', '>=', $end_episode_sequence);
  2221. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2222. // 新范围完全包含现有范围
  2223. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2224. ->where('end_episode_number', '<=', $end_episode_sequence);
  2225. });
  2226. })
  2227. ->select('start_episode_number', 'end_episode_number')
  2228. ->get();
  2229. if ($exists_groups->isNotEmpty()) {
  2230. $conflict_ranges = [];
  2231. foreach ($exists_groups as $group) {
  2232. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2233. }
  2234. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2235. }
  2236. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2237. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2238. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2239. if ($model === 'deepseek-chat') {
  2240. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2241. $model = 'deepseek-v4-flash';
  2242. $thinkingMode = 'disabled';
  2243. } elseif ($model === 'deepseek-reasoner') {
  2244. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2245. $model = 'deepseek-v4-flash';
  2246. $thinkingMode = 'enabled';
  2247. }
  2248. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2249. if (!$script) {
  2250. Utils::throwError('20003:剧本不存在');
  2251. }
  2252. $content = getProp($group, 'content');
  2253. if (!$file && !$content && !$bid) {
  2254. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2255. }
  2256. // 提取文件内容
  2257. if ($file) {
  2258. $content = $this->extractFileContent($file);
  2259. if (!$content) {
  2260. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2261. }
  2262. } elseif ($bid) {
  2263. $content = $this->getContentByBid($bid);
  2264. if (!$content) {
  2265. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2266. }
  2267. } elseif ($content) {
  2268. $content = filterContent($content);
  2269. } elseif ($prompt) {
  2270. $content = filterContent($prompt);
  2271. } else {
  2272. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2273. }
  2274. // 构建消息
  2275. $messages = [
  2276. $this->sys_message,
  2277. [
  2278. 'role' => 'user',
  2279. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2280. ]
  2281. ];
  2282. $post_data = [
  2283. 'model' => $model,
  2284. 'messages' => $messages,
  2285. // 'max_tokens' => 8192,
  2286. 'temperature' => 0.7,
  2287. 'frequency_penalty' => 0,
  2288. 'presence_penalty' => 0,
  2289. 'thinking' => ['type' => $thinkingMode],
  2290. 'response_format' => ['type' => 'text'],
  2291. 'stream' => true
  2292. ];
  2293. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2294. // 根据模型类型选择调用方法
  2295. $fullContent = '';
  2296. $fullReasoningContent = '';
  2297. $usage = [];
  2298. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2299. // DeepSeek 官方模型使用 DeepSeek API
  2300. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2301. } else if (in_array($model, $this->gpt_text_models)) {
  2302. // GPT-5.4 模型使用 TokenRouter API
  2303. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2304. } else {
  2305. // 其他模型使用火山引擎API
  2306. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2307. }
  2308. // 处理流式输出
  2309. foreach ($streamGenerator as $chunk) {
  2310. if (isset($chunk['type'])) {
  2311. if ($chunk['type'] === 'done') {
  2312. // 最终结果
  2313. $fullContent = $chunk['full_content'];
  2314. $fullReasoningContent = $chunk['full_reasoning'];
  2315. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2316. } else {
  2317. // 逐块yield数据
  2318. yield $chunk;
  2319. }
  2320. }
  2321. }
  2322. dLog('deepseek')->info('完整内容: '.$fullContent);
  2323. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2324. // 处理完整内容并返回最终结果
  2325. $script_arr = [];
  2326. if ($fullContent) {
  2327. $script_arr = extractScriptContent($fullContent);
  2328. }
  2329. logDB('deepseek', 'info', '解析内容', $script_arr);
  2330. if (!$script_arr['episodes']) {
  2331. Utils::throwError('20003:未生成剧本相关信息');
  2332. // yield [
  2333. // 'type' => 'done',
  2334. // 'script' => $script_arr,
  2335. // 'msg' => '未生成剧本相关信息',
  2336. // 'answer' => $fullContent,
  2337. // 'reasoning' => $fullReasoningContent,
  2338. // 'usage' => $usage
  2339. // ];
  2340. // return ;
  2341. }
  2342. try {
  2343. DB::beginTransaction();
  2344. // // 返回前保存剧本内容
  2345. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2346. // 'content' => $content,
  2347. // 'updated_at' => date('Y-m-d H:i:s')
  2348. // ]);
  2349. // if (!$boolen) {
  2350. // Utils::throwError('20003:保存剧本内容失败');
  2351. // }
  2352. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2353. // 'start_episode_number' => $start_episode_sequence,
  2354. // 'end_episode_number' => $end_episode_sequence,
  2355. // 'updated_at' => date('Y-m-d H:i:s')
  2356. // ]);
  2357. // if (!$boolen1) {
  2358. // Utils::throwError('20003:保存分集失败');
  2359. // }
  2360. $episode_content = '';
  2361. $episodes = [];
  2362. foreach ($script_arr['episodes'] as $item) {
  2363. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2364. // $episodes[] = [
  2365. // 'script_id' => $script_id,
  2366. // 'episode_number' => $item['episode_number'],
  2367. // 'episode_name' => $item['episode_name'],
  2368. // 'episode_content' => $item['episode_content'],
  2369. // 'created_at' => date('Y-m-d H:i:s'),
  2370. // 'updated_at' => date('Y-m-d H:i:s'),
  2371. // ];
  2372. }
  2373. if ($episode_content) {
  2374. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2375. 'episode_content' => $episode_content,
  2376. 'updated_at' => date('Y-m-d H:i:s')
  2377. ]);
  2378. if (!$boolen2) {
  2379. Utils::throwError('20003:保存分集内容失败');
  2380. }
  2381. }else {
  2382. Utils::throwError('20003:分集剧本解析失败');
  2383. }
  2384. }catch (\Exception $e) {
  2385. DB::rollBack();
  2386. Utils::throwError('20003:'.$e->getMessage());
  2387. }
  2388. DB::commit();
  2389. yield [
  2390. 'type' => 'done',
  2391. 'script' => $script_arr,
  2392. 'episode_content' => $episode_content,
  2393. 'answer' => $fullContent,
  2394. 'reasoning' => $fullReasoningContent,
  2395. 'usage' => $usage
  2396. ];
  2397. }
  2398. public function chatWithFileStream($data) {
  2399. $script_id = getProp($data, 'script_id');
  2400. $group_id = getProp($data, 'group_id');
  2401. $file = getProp($data, 'file');
  2402. $content = getProp($data, 'content', '');
  2403. $bid = getProp($data, 'bid', 0);
  2404. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2405. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2406. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2407. $prompt = getProp($data, 'prompt');
  2408. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2409. if (!empty($prompt)) {
  2410. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2411. }
  2412. $question = getProp($data, 'question', $baseQuestion);
  2413. $model = getProp($data, 'model');
  2414. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2415. Utils::throwError('20003:该模型不存在!');
  2416. }
  2417. // 检查是否存在重叠的剧集序号范围
  2418. $exists_groups = DB::table('mp_script_episode_group')
  2419. ->where('script_id', $script_id)
  2420. ->where('id', '<>', $group_id)
  2421. ->where('is_deleted', 0)
  2422. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2423. // 检查新范围是否与现有范围重叠
  2424. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2425. // 新范围的开始在现有范围内
  2426. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2427. ->where('end_episode_number', '>=', $start_episode_sequence);
  2428. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2429. // 新范围的结束在现有范围内
  2430. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2431. ->where('end_episode_number', '>=', $end_episode_sequence);
  2432. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2433. // 新范围完全包含现有范围
  2434. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2435. ->where('end_episode_number', '<=', $end_episode_sequence);
  2436. });
  2437. })
  2438. ->select('start_episode_number', 'end_episode_number')
  2439. ->get();
  2440. if ($exists_groups->isNotEmpty()) {
  2441. $conflict_ranges = [];
  2442. foreach ($exists_groups as $group) {
  2443. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2444. }
  2445. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2446. }
  2447. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2448. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2449. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2450. if ($model === 'deepseek-chat') {
  2451. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2452. $model = 'deepseek-v4-flash';
  2453. $thinkingMode = 'disabled';
  2454. } elseif ($model === 'deepseek-reasoner') {
  2455. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2456. $model = 'deepseek-v4-flash';
  2457. $thinkingMode = 'enabled';
  2458. }
  2459. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2460. if (!$script) {
  2461. Utils::throwError('20003:剧本不存在');
  2462. }
  2463. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2464. if (!$group) {
  2465. Utils::throwError('20003:剧本分集不存在');
  2466. }
  2467. if (!$file && !$content && !$bid) {
  2468. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2469. }
  2470. // 提取文件内容
  2471. if ($file) {
  2472. $content = $this->extractFileContent($file);
  2473. if (!$content) {
  2474. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2475. }
  2476. } elseif ($bid) {
  2477. $content = $this->getContentByBid($bid);
  2478. if (!$content) {
  2479. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2480. }
  2481. } elseif ($content) {
  2482. $content = filterContent($content);
  2483. } elseif ($prompt) {
  2484. $content = filterContent($prompt);
  2485. } else {
  2486. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2487. }
  2488. // 构建消息
  2489. $messages = [
  2490. [
  2491. 'role' => 'system',
  2492. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2493. 强制要求:\n
  2494. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2495. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2496. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2497. 普通要求:\n
  2498. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2499. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2500. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2501. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2502. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2503. 示例如下:\n
  2504. ###剧本名:西昆仑
  2505. ###故事梗概
  2506. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2507. ###剧本亮点
  2508. 亮点1:绝境奇药,生死一线
  2509. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2510. 亮点2:结拜兄妹,化解尴尬
  2511. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2512. 亮点3:纤发夺命,情愫暗涌
  2513. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2514. ###人物关系
  2515. 阿雪与梁萧之间存在兄妹之情。
  2516. ###核心矛盾
  2517. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2518. ###主体列表
  2519. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2520. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2521. 阴阳球:天地异宝,能化生精气,救人于危难。
  2522. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2523. ###美术风格
  2524. 基础画风风格词:厚涂古风
  2525. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2526. ###场景列表
  2527. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2528. [
  2529. 'role' => 'user',
  2530. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2531. ]
  2532. ];
  2533. $post_data = [
  2534. 'model' => $model,
  2535. 'messages' => $messages,
  2536. // 'max_tokens' => 8192,
  2537. 'temperature' => 0.7,
  2538. 'frequency_penalty' => 0,
  2539. 'presence_penalty' => 0,
  2540. 'thinking' => ['type' => $thinkingMode],
  2541. 'response_format' => ['type' => 'text'],
  2542. 'stream' => true
  2543. ];
  2544. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2545. // 根据模型类型选择调用方法
  2546. $fullContent = '';
  2547. $fullReasoningContent = '';
  2548. $usage = [];
  2549. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2550. // DeepSeek 官方模型使用 DeepSeek API
  2551. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2552. } else if (in_array($model, $this->gpt_text_models)) {
  2553. // GPT-5.4 模型使用 TokenRouter API
  2554. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2555. } else {
  2556. // 其他模型使用火山引擎API
  2557. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2558. }
  2559. // 处理流式输出
  2560. foreach ($streamGenerator as $chunk) {
  2561. if (isset($chunk['type'])) {
  2562. if ($chunk['type'] === 'done') {
  2563. // 最终结果
  2564. $fullContent = $chunk['full_content'];
  2565. $fullReasoningContent = $chunk['full_reasoning'];
  2566. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2567. } else {
  2568. // 逐块yield数据
  2569. yield $chunk;
  2570. }
  2571. }
  2572. }
  2573. dLog('deepseek')->info('完整内容: '.$fullContent);
  2574. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2575. // 处理完整内容并返回最终结果
  2576. $script_arr = [];
  2577. if ($fullContent) {
  2578. $script_arr = extractScriptContent($fullContent);
  2579. }
  2580. logDB('deepseek', 'info', '解析内容', $script_arr);
  2581. if (!$script_arr['roles']) {
  2582. Utils::throwError('20003:未生成剧本相关信息');
  2583. // yield [
  2584. // 'type' => 'done',
  2585. // 'script' => $script_arr,
  2586. // 'msg' => '未生成剧本相关信息',
  2587. // 'answer' => $fullContent,
  2588. // 'reasoning' => $fullReasoningContent,
  2589. // 'usage' => $usage
  2590. // ];
  2591. }
  2592. try {
  2593. DB::beginTransaction();
  2594. // // 返回前保存剧本内容
  2595. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2596. // 'content' => $content,
  2597. // 'status' => '解析完成',
  2598. // 'updated_at' => date('Y-m-d H:i:s')
  2599. // ]);
  2600. // if (!$boolen) {
  2601. // Utils::throwError('20003:保存剧本内容失败');
  2602. // }
  2603. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2604. 'start_episode_number' => $start_episode_sequence,
  2605. 'end_episode_number' => $end_episode_sequence,
  2606. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2607. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2608. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2609. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2610. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2611. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2612. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2613. 'status' => '解析完成',
  2614. 'content' => $content,
  2615. 'updated_at' => date('Y-m-d H:i:s')
  2616. ]);
  2617. if (!$boolen1) {
  2618. Utils::throwError('20003:保存分集失败');
  2619. }
  2620. // $episodes = [];
  2621. // foreach ($script_arr['episodes'] as $item) {
  2622. // $episodes[] = [
  2623. // 'script_id' => $script_id,
  2624. // 'episode_number' => $item['episode_number'],
  2625. // 'episode_name' => $item['episode_name'],
  2626. // 'episode_content' => $item['episode_content'],
  2627. // 'created_at' => date('Y-m-d H:i:s'),
  2628. // 'updated_at' => date('Y-m-d H:i:s'),
  2629. // ];
  2630. // }
  2631. // if ($episodes) {
  2632. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2633. // if (!$boolen2) {
  2634. // Utils::throwError('20003:保存分集内容失败');
  2635. // }
  2636. // }else {
  2637. // Utils::throwError('20003:分集剧本解析失败');
  2638. // }
  2639. }catch (\Exception $e) {
  2640. DB::rollBack();
  2641. Utils::throwError('20003:'.$e->getMessage());
  2642. }
  2643. DB::commit();
  2644. yield [
  2645. 'type' => 'done',
  2646. 'script' => $script_arr,
  2647. 'answer' => $fullContent,
  2648. 'reasoning' => $fullReasoningContent,
  2649. 'usage' => $usage
  2650. ];
  2651. }
  2652. /**
  2653. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2654. *
  2655. * @param array $data 包含以下参数:
  2656. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2657. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2658. * - model: 使用的模型(r1 或 v3,默认 v3)
  2659. * @return array
  2660. */
  2661. public function chatWithFile($data) {
  2662. $script_id = getProp($data, 'script_id');
  2663. $file = getProp($data, 'file');
  2664. $content = getProp($data, 'content', '');
  2665. $bid = getProp($data, 'bid', 0);
  2666. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2667. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2668. $prompt = getProp($data, 'prompt');
  2669. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2670. if (!empty($prompt)) {
  2671. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2672. }
  2673. $question = getProp($data, 'question', $baseQuestion);
  2674. // 处理文本模型
  2675. $model = getProp($data, 'model');
  2676. if (!$model) {
  2677. // 用户没有输入,使用默认值
  2678. $model = 'doubao-seed-2-0-mini-260215';
  2679. }
  2680. // 验证模型是否在可用模型表中
  2681. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2682. $model = 'doubao-seed-2-0-mini-260215';
  2683. }
  2684. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2685. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2686. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2687. if ($model === 'deepseek-chat') {
  2688. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2689. $model = 'deepseek-v4-flash';
  2690. $thinkingMode = 'disabled';
  2691. } elseif ($model === 'deepseek-reasoner') {
  2692. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2693. $model = 'deepseek-v4-flash';
  2694. $thinkingMode = 'enabled';
  2695. }
  2696. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2697. if (!$script) {
  2698. Utils::throwError('20003:剧本不存在');
  2699. }
  2700. if (!$file && !$content && !$bid) {
  2701. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2702. }
  2703. // 提取文件内容
  2704. if ($file) {
  2705. $content = $this->extractFileContent($file);
  2706. if (!$content) {
  2707. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2708. }
  2709. } elseif ($bid) {
  2710. $content = $this->getContentByBid($bid);
  2711. if (!$content) {
  2712. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2713. }
  2714. } elseif ($content) {
  2715. $content = filterContent($content);
  2716. } elseif ($prompt) {
  2717. $content = filterContent($prompt);
  2718. } else {
  2719. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2720. }
  2721. // 构建消息
  2722. $messages = [
  2723. $this->sys_message,
  2724. [
  2725. 'role' => 'user',
  2726. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2727. ]
  2728. ];
  2729. $post_data = [
  2730. 'model' => $model,
  2731. 'messages' => $messages,
  2732. // 'max_tokens' => 8192,
  2733. 'temperature' => 0.7,
  2734. 'frequency_penalty' => 0,
  2735. 'presence_penalty' => 0,
  2736. 'thinking' => ['type' => $thinkingMode],
  2737. 'response_format' => ['type' => 'text'],
  2738. 'stream' => false
  2739. ];
  2740. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2741. // 根据模型类型选择调用方法
  2742. $fullContent = '';
  2743. $usage = [];
  2744. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2745. // DeepSeek 官方模型使用 DeepSeek API
  2746. $chatResult = $this->chatOnly($post_data);
  2747. } else if (in_array($model, $this->gpt_text_models)) {
  2748. // GPT-5.4 模型使用 TokenRouter API
  2749. $chatResult = $this->gpt54ChatOnly($post_data);
  2750. } else {
  2751. // 其他模型使用火山引擎API
  2752. $chatResult = $this->volcEngineChatCompletion($post_data);
  2753. }
  2754. if (is_array($chatResult)) {
  2755. $fullContent = $chatResult['fullContent'];
  2756. $usage = $chatResult['usage'];
  2757. }
  2758. $script_arr = [];
  2759. // 处理结果
  2760. if ($fullContent) {
  2761. $script_arr = extractScriptContent($fullContent);
  2762. }
  2763. // 返回前保存剧本内容
  2764. DB::table('mp_scripts')->where('id', $script_id)->update([
  2765. 'content' => $content,
  2766. 'updated_at' => date('Y-m-d H:i:s')
  2767. ]);
  2768. return [
  2769. 'script' => $script_arr,
  2770. 'answer' => $fullContent,
  2771. 'usage' => $usage
  2772. ];
  2773. }
  2774. public function getEpisodeContent($data) {
  2775. $group_id = getProp($data, 'group_id');
  2776. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2777. }
  2778. public function saveEpisodeContent($data) {
  2779. $script_id = getProp($data, 'script_id');
  2780. $group_id = getProp($data, 'group_id');
  2781. $start_episode_sequence = getProp($data, 'start_episode_number');
  2782. $end_episode_sequence = getProp($data, 'end_episode_number');
  2783. // 检查是否存在重叠的剧集序号范围
  2784. $exists_groups = DB::table('mp_script_episode_group')
  2785. ->where('script_id', $script_id)
  2786. ->where('id', '<>', $group_id) // 排除当前组
  2787. ->where('is_deleted', 0)
  2788. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2789. // 检查新范围是否与现有范围重叠
  2790. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2791. // 新范围的开始在现有范围内
  2792. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2793. ->where('end_episode_number', '>=', $start_episode_sequence);
  2794. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2795. // 新范围的结束在现有范围内
  2796. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2797. ->where('end_episode_number', '>=', $end_episode_sequence);
  2798. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2799. // 新范围完全包含现有范围
  2800. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2801. ->where('end_episode_number', '<=', $end_episode_sequence);
  2802. });
  2803. })
  2804. ->select('start_episode_number', 'end_episode_number')
  2805. ->get();
  2806. if ($exists_groups->isNotEmpty()) {
  2807. $conflict_ranges = [];
  2808. foreach ($exists_groups as $group) {
  2809. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2810. }
  2811. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2812. }
  2813. $episode_content = getProp($data, 'episode_content');
  2814. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2815. 'content' => $episode_content,
  2816. 'start_episode_number' => $start_episode_sequence,
  2817. 'end_episode_number' => $end_episode_sequence,
  2818. 'updated_at' => date('Y-m-d H:i:s')
  2819. ]);
  2820. $script_arr =getProp($data, 'script', []);
  2821. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2822. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2823. $script_id = getProp($data, 'script_id');
  2824. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2825. try {
  2826. DB::beginTransaction();
  2827. $update_data = [
  2828. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2829. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2830. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2831. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2832. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2833. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2834. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2835. 'status' => 3,
  2836. 'start_episode_sequence' => $start_episode_sequence,
  2837. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2838. 'episode_num' => count($script_arr['episodes']),
  2839. 'updated_at' => date('Y-m-d H:i:s')
  2840. ];
  2841. // 保存剧本内容
  2842. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2843. if (!$boolen) {
  2844. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2845. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2846. Utils::throwError('20003:剧本内容保存失败');
  2847. }
  2848. // 保存分集内容
  2849. // 删除历史分集内容
  2850. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2851. $episodes = [];
  2852. $sequence = 1;
  2853. foreach ($script_arr['episodes'] as $episode) {
  2854. $segment_number = 1;
  2855. foreach($episode['segments'] as $segment) {
  2856. $episodes[] = [
  2857. 'script_id' => $script_id,
  2858. 'episode_number' => $episode['episode_number'],
  2859. 'title' => $episode['title'],
  2860. // 'content' => $episode['content'],
  2861. 'content' => '',
  2862. 'segment_number' => $segment_number,
  2863. 'segment_content' => $segment['segment_content'],
  2864. 'sequence' => $sequence,
  2865. 'created_at' => date('Y-m-d H:i:s'),
  2866. 'updated_at' => date('Y-m-d H:i:s')
  2867. ];
  2868. $sequence++;
  2869. $segment_number++;
  2870. }
  2871. }
  2872. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2873. if (!$boolen2) {
  2874. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2875. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2876. Utils::throwError('20003:分集内容保存失败');
  2877. }
  2878. } catch (\Exception $e) {
  2879. DB::rollBack();
  2880. Utils::throwError('20003:'.$e->getMessage());
  2881. }
  2882. DB::commit();
  2883. return true;
  2884. }
  2885. public function getBookContent($data) {
  2886. $bid = getProp($data, 'bid');
  2887. $start_sequence = getProp($data, 'start_sequence');
  2888. $end_sequence = getProp($data, 'end_sequence');
  2889. $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])
  2890. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2891. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2892. return $return_content;
  2893. }
  2894. public function exportScript($data) {
  2895. $filename = getProp($data, 'filename');
  2896. $script_id = getProp($data, 'script_id');
  2897. $group_id = getProp($data, 'group_id');
  2898. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2899. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2900. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2901. $script = (array)$script;
  2902. // 获取分集组信息
  2903. if ($group_id) {
  2904. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2905. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2906. ->get()->map(function($value) {
  2907. return (array)$value;
  2908. })->toArray();
  2909. }else {
  2910. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2911. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2912. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2913. return (array)$value;
  2914. })->toArray();
  2915. }
  2916. if (!$groups) Utils::throwError('20003:分集不存在');
  2917. $script['group'] = $groups;
  2918. $export_type = getProp($data, 'export_type', 'txt');
  2919. // 生成文件名
  2920. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2921. // 根据导出类型生成不同格式的文件
  2922. switch ($export_type) {
  2923. case 'txt':
  2924. return $this->exportScriptAsTxt($script, $filename);
  2925. case 'pdf':
  2926. return $this->exportScriptAsPdf($script, $filename);
  2927. default:
  2928. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2929. }
  2930. }
  2931. /**
  2932. * 导出剧本为TXT格式
  2933. */
  2934. private function exportScriptAsTxt($script, $filename) {
  2935. // 构建TXT内容
  2936. $content = $this->buildScriptContent($script);
  2937. // 设置响应头,直接下载
  2938. header('Content-Type: text/plain; charset=utf-8');
  2939. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2940. header('Content-Length: ' . strlen($content));
  2941. // 输出内容并结束
  2942. echo $content;
  2943. exit();
  2944. }
  2945. /**
  2946. * 导出剧本为PDF格式
  2947. */
  2948. private function exportScriptAsPdf($script, $filename) {
  2949. // 使用HTML转PDF的方式来更好地支持中文
  2950. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2951. // 创建PDF实例
  2952. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2953. // 设置文档信息
  2954. $pdf->SetCreator('剧本导出系统');
  2955. $pdf->SetAuthor('系统');
  2956. $pdf->SetTitle($script['script_name']);
  2957. $pdf->SetSubject('剧本导出');
  2958. // 设置边距
  2959. $pdf->SetMargins(15, 15, 15);
  2960. $pdf->SetAutoPageBreak(TRUE, 15);
  2961. // 添加页面
  2962. $pdf->AddPage();
  2963. // 注册并使用 simsun.ttf 字体
  2964. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2965. // 使用HTML内容生成PDF
  2966. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2967. // 直接输出PDF文件供下载
  2968. header('Content-Type: application/pdf');
  2969. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2970. // 直接输出PDF内容
  2971. $pdf->Output($filename . '.pdf', 'D');
  2972. exit();
  2973. }
  2974. /**
  2975. * 构建用于PDF的HTML内容
  2976. */
  2977. private function buildScriptHtmlForPdf($script) {
  2978. $html = '<style>
  2979. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2980. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2981. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2982. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2983. .info { margin-bottom: 8px; }
  2984. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2985. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2986. .segment { margin-bottom: 10px; margin-left: 20px; }
  2987. .episode-content { white-space: pre-wrap; }
  2988. </style>';
  2989. // 标题
  2990. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2991. // 处理分组数据
  2992. if (!empty($script['group']) && is_array($script['group'])) {
  2993. $groups = (array)$script['group'];
  2994. foreach ($groups as $group) {
  2995. $html .= '<div class="group">';
  2996. // 分组标题
  2997. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2998. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2999. // 故事梗概
  3000. if (!empty($group['intro'])) {
  3001. $html .= '<h3>故事梗概</h3>';
  3002. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3003. }
  3004. // 剧本亮点
  3005. if (!empty($group['highlights'])) {
  3006. $html .= '<h3>剧本亮点</h3>';
  3007. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3008. }
  3009. // 人物关系
  3010. if (!empty($group['role_relationship'])) {
  3011. $html .= '<h3>人物关系</h3>';
  3012. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3013. }
  3014. // 核心矛盾
  3015. if (!empty($group['core_contradiction'])) {
  3016. $html .= '<h3>核心矛盾</h3>';
  3017. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3018. }
  3019. // 主体列表
  3020. if (!empty($group['roles']) && is_array($group['roles'])) {
  3021. $html .= '<h3>主体列表</h3>';
  3022. $html .= '<ul>';
  3023. foreach ($group['roles'] as $role) {
  3024. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3025. }
  3026. $html .= '</ul>';
  3027. }
  3028. // 美术风格
  3029. if (!empty($group['art_style'])) {
  3030. $html .= '<h3>美术风格</h3>';
  3031. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3032. }
  3033. // 场景列表
  3034. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3035. $html .= '<h3>场景列表</h3>';
  3036. $html .= '<ul>';
  3037. foreach ($group['scenes'] as $scene) {
  3038. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3039. }
  3040. $html .= '</ul>';
  3041. }
  3042. // 分集剧本
  3043. if (!empty($group['episode_content'])) {
  3044. $html .= '<h3>分集剧本</h3>';
  3045. // 去除零宽字符和其他不可见字符
  3046. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3047. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3048. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3049. }
  3050. $html .= '</div>';
  3051. }
  3052. }
  3053. return $html;
  3054. }
  3055. /**
  3056. * 构建PDF内容
  3057. */
  3058. private function buildPdfContent($pdf, $script) {
  3059. // 标题
  3060. $pdf->SetFont('dejavusans', 'B', 18);
  3061. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3062. $pdf->Ln(5);
  3063. // 基本信息
  3064. $pdf->SetFont('dejavusans', '', 12);
  3065. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3066. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3067. $pdf->Ln(5);
  3068. // 剧本简介
  3069. if (!empty($script['intro'])) {
  3070. $pdf->SetFont('dejavusans', 'B', 14);
  3071. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3072. $pdf->SetFont('dejavusans', '', 12);
  3073. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3074. $pdf->Ln(3);
  3075. }
  3076. // 亮点
  3077. if (!empty($script['highlights'])) {
  3078. $pdf->SetFont('dejavusans', 'B', 14);
  3079. $pdf->Cell(0, 10, '亮点', 0, 1);
  3080. $pdf->SetFont('dejavusans', '', 12);
  3081. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3082. $pdf->Ln(3);
  3083. }
  3084. // 核心矛盾
  3085. if (!empty($script['core_contradiction'])) {
  3086. $pdf->SetFont('dejavusans', 'B', 14);
  3087. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3088. $pdf->SetFont('dejavusans', '', 12);
  3089. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3090. $pdf->Ln(3);
  3091. }
  3092. // 艺术风格
  3093. if (!empty($script['art_style'])) {
  3094. $pdf->SetFont('dejavusans', 'B', 14);
  3095. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3096. $pdf->SetFont('dejavusans', '', 12);
  3097. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3098. $pdf->Ln(3);
  3099. }
  3100. // 备注
  3101. if (!empty($script['remark'])) {
  3102. $pdf->SetFont('dejavusans', 'B', 14);
  3103. $pdf->Cell(0, 10, '备注', 0, 1);
  3104. $pdf->SetFont('dejavusans', '', 12);
  3105. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3106. $pdf->Ln(3);
  3107. }
  3108. // 角色列表
  3109. if (!empty($script['roles']) && is_array($script['roles'])) {
  3110. $pdf->SetFont('dejavusans', 'B', 14);
  3111. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3112. $pdf->SetFont('dejavusans', '', 12);
  3113. foreach ($script['roles'] as $index => $role) {
  3114. if (is_array($role) || is_object($role)) {
  3115. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3116. } else {
  3117. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3118. }
  3119. }
  3120. $pdf->Ln(3);
  3121. }
  3122. // 角色关系
  3123. if (!empty($script['role_relationship'])) {
  3124. $pdf->SetFont('dejavusans', 'B', 14);
  3125. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3126. $pdf->SetFont('dejavusans', '', 12);
  3127. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3128. $pdf->Ln(3);
  3129. }
  3130. // 场景列表
  3131. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3132. $pdf->SetFont('dejavusans', 'B', 14);
  3133. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3134. $pdf->SetFont('dejavusans', '', 12);
  3135. foreach ($script['scenes'] as $index => $scene) {
  3136. if (is_array($scene) || is_object($scene)) {
  3137. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3138. } else {
  3139. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3140. }
  3141. }
  3142. $pdf->Ln(5);
  3143. }
  3144. // 分集内容
  3145. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3146. $pdf->SetFont('dejavusans', 'B', 16);
  3147. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3148. $pdf->Ln(3);
  3149. foreach ($script['episodes'] as $episode) {
  3150. // 检查是否需要新页面
  3151. if ($pdf->GetY() > 250) {
  3152. $pdf->AddPage();
  3153. }
  3154. $pdf->SetFont('dejavusans', 'B', 14);
  3155. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3156. if (!empty($episode['title'])) {
  3157. $episodeTitle .= ':' . $episode['title'];
  3158. }
  3159. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3160. // 处理分段内容
  3161. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3162. $pdf->SetFont('dejavusans', '', 12);
  3163. foreach ($episode['segments'] as $segment) {
  3164. if (!empty($segment['segment_content'])) {
  3165. // 如果有分段编号,显示分段标题
  3166. if (!empty($segment['segment_number'])) {
  3167. $pdf->SetFont('dejavusans', 'B', 12);
  3168. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3169. $pdf->SetFont('dejavusans', '', 12);
  3170. }
  3171. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3172. $pdf->Ln(2);
  3173. }
  3174. }
  3175. }
  3176. $pdf->Ln(5);
  3177. }
  3178. }
  3179. }
  3180. /**
  3181. * 构建剧本文本内容
  3182. */
  3183. private function buildScriptContent($script) {
  3184. $content = '';
  3185. $groups = $script['group'];
  3186. $groups = (array)$groups;
  3187. foreach ($groups as $group) {
  3188. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3189. // 剧本基本信息
  3190. if (!empty($group['intro'])) {
  3191. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3192. }
  3193. if (!empty($group['highlights'])) {
  3194. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3195. }
  3196. if (!empty($group['role_relationship'])) {
  3197. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3198. }
  3199. if (!empty($group['core_contradiction'])) {
  3200. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3201. }
  3202. if (!empty($group['roles']) && is_array($group['roles'])) {
  3203. $content .= "###主体列表\n";
  3204. foreach ($group['roles'] as $role) {
  3205. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3206. }
  3207. $content .= "\n\n";
  3208. }
  3209. if (!empty($group['art_style'])) {
  3210. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3211. }
  3212. // 场景信息
  3213. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3214. $content .= "###场景列表\n";
  3215. foreach ($group['scenes'] as $scene) {
  3216. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3217. }
  3218. $content .= "\n\n";
  3219. }
  3220. // 分集内容
  3221. if (!empty($group['episode_content'])) {
  3222. $content .= "###分集剧本\n";
  3223. $content .= $group['episode_content'];
  3224. // foreach ($script['episodes'] as $episode) {
  3225. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3226. // // if (!empty($episode['episode_name'])) {
  3227. // // $content .= ":" . $episode['episode_name'];
  3228. // // }
  3229. // // $content .= "\n";
  3230. // $content .= $episode['episode_content'] . "\n\n";
  3231. // }
  3232. }
  3233. }
  3234. return $content;
  3235. }
  3236. /**
  3237. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3238. *
  3239. * @param array $data 包含以下参数:
  3240. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3241. * - question: 用户问题(可选)
  3242. * - model: 使用的模型(r1 或 v3,默认 v3)
  3243. * @return \Generator 返回生成器,用于流式输出
  3244. */
  3245. public function addChat($data) {
  3246. $uid = Site::getUid();
  3247. $anime_id = getProp($data, 'anime_id');
  3248. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3249. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3250. if (!$anime) Utils::throwError('20003:对话不存在');
  3251. $file = getProp($data, 'file');
  3252. $content = getProp($data, 'content', '');
  3253. $bid = getProp($data, 'bid', 0);
  3254. $script_id = getProp($data, 'script_id', 0);
  3255. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3256. $prompt = getProp($data, 'prompt');
  3257. $user_anime_name = getProp($anime, 'anime_name');
  3258. // 处理文本模型
  3259. $model = getProp($data, 'model');
  3260. if (!$model) {
  3261. // 用户没有输入,从anime表获取
  3262. $model = getProp($anime, 'model');
  3263. if (!$model) {
  3264. // anime表也没有,使用默认值
  3265. $model = 'doubao-seed-2-0-mini-260215';
  3266. }
  3267. }
  3268. // 验证模型是否在可用模型表中
  3269. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3270. $model = 'doubao-seed-2-0-mini-260215';
  3271. }
  3272. $is_multi = getProp($anime, 'is_multi');
  3273. $is_single = (int)$is_multi !== 1;
  3274. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3275. if ($prompt) {
  3276. $question .= "本次修改要求如下:\n{$prompt}";
  3277. }
  3278. // if (!$file && !$content && !$bid) {
  3279. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3280. // }
  3281. // 提取文件内容
  3282. if ($file) {
  3283. $content = $this->extractFileContent($file);
  3284. if (!$content) {
  3285. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3286. }
  3287. } elseif ($script_id) {
  3288. $content = $this->getContentByScriptId($script_id);
  3289. if (!$content) {
  3290. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3291. }
  3292. } elseif ($bid) {
  3293. $content = $this->getContentByBid($bid);
  3294. if (!$content) {
  3295. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3296. }
  3297. } elseif ($content) {
  3298. $content = filterContent($content);
  3299. } else {
  3300. $content = getProp($anime, 'content');
  3301. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3302. $need_generate_content = true;
  3303. }
  3304. }
  3305. // 美术风格
  3306. $input_art_style = getProp($data, 'art_style');
  3307. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3308. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3309. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3310. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3311. 中年女:邻居阿姨
  3312. 老年男:幽默大爷
  3313. 老年女:婆婆
  3314. 萌娃:奶气萌娃";
  3315. // 判断是否需要生成原文内容
  3316. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3317. // 如果需要生成原文内容,添加额外的要求
  3318. $content_generation_requirement = $need_generate_content
  3319. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3320. : "";
  3321. // 美术风格
  3322. if (!$mappedArtStyle) {
  3323. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3324. }else {
  3325. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3326. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3327. }else {
  3328. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3329. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3330. }
  3331. }
  3332. $systemPrompt = $is_single
  3333. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3334. 强制要求:
  3335. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3336. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3337. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3338. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3339. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3340. 普通要求:
  3341. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3342. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3343. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3344. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3345. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3346. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3347. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3348. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3349. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3350. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3351. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3352. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3353. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3354. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3355. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3356. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3357. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3358. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3359. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3360. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3361. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3362. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3363. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3364. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3365. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3366. 5.{$mappedArtStyle_prompt}\n\n
  3367. 示例如下:\n
  3368. ###剧本名:西昆仑
  3369. ###故事梗概
  3370. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3371. ###剧本亮点
  3372. 亮点1:绝境奇药,生死一线
  3373. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3374. 亮点2:结拜兄妹,化解尴尬
  3375. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3376. 亮点3:纤发夺命,情愫暗涌
  3377. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3378. ###人物关系
  3379. 阿雪与梁萧之间存在兄妹之情。
  3380. ###核心矛盾
  3381. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3382. ###主体列表
  3383. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3384. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3385. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3386. 姿态:站立。}{{甜心小美}}
  3387. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3388. 全景,正面拍摄,青年女性,亚洲人。
  3389. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3390. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3391. 姿态:站立。}{{阳光青年}}
  3392. ###美术风格
  3393. 基础画风风格词:厚涂古风
  3394. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3395. ###场景列表
  3396. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3397. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3398. 无人物。}
  3399. ###分镜剧本
  3400. ##第1幕:徐家老旧厨房 白天 室内
  3401. 分镜1
  3402. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3403. 场景:徐家老旧厨房
  3404. 构图设计:全景,低角度仰视
  3405. 运镜调度:手持拍摄
  3406. 配音角色:旁白
  3407. 出镜角色:许芸-校服装、徐母
  3408. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3409. 画面类型:普通画面
  3410. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3411. 分镜2
  3412. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3413. 场景:徐家老旧厨房
  3414. 构图设计:近景,徐母面部特写
  3415. 运镜调度:固定镜头
  3416. 配音角色:徐母
  3417. 出镜角色:徐母
  3418. 台词内容:问我夜不归宿死哪儿去了。
  3419. 画面类型:对口型
  3420. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3421. ##第2幕:徐家简陋客厅 黄昏 室内
  3422. 分镜3
  3423. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3424. 场景:徐家简陋客厅
  3425. 构图设计:全景,景深虚化
  3426. 运镜调度:固定镜头
  3427. 配音角色:旁白
  3428. 出镜角色:无
  3429. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3430. 画面类型:普通画面
  3431. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3432. 分镜4
  3433. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3434. 场景:徐家简陋客厅
  3435. 构图设计:特写,火车票
  3436. 运镜调度:固定镜头
  3437. 配音角色:旁白
  3438. 出镜角色:无
  3439. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3440. 画面类型:普通画面
  3441. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3442. "
  3443. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3444. 强制要求:\n
  3445. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3446. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3447. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3448. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3449. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3450. 普通要求:\n
  3451. 1.剧本名(必须生成)必须与文档内容高度相关
  3452. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3453. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3454. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3455. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3456. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3457. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3458. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3459. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3460. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3461. 4.{$mappedArtStyle_prompt}\n\n
  3462. 示例如下:\n
  3463. ###剧本名:西昆仑
  3464. ###故事梗概
  3465. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3466. ###剧本亮点
  3467. 亮点1:绝境奇药,生死一线
  3468. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3469. 亮点2:结拜兄妹,化解尴尬
  3470. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3471. 亮点3:纤发夺命,情愫暗涌
  3472. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3473. ###人物关系
  3474. 阿雪与梁萧之间存在兄妹之情。
  3475. ###核心矛盾
  3476. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3477. ###主体列表
  3478. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3479. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3480. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3481. 姿态:站立。}{{甜心小美}}
  3482. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3483. 全景,正面拍摄,青年女性,亚洲人。
  3484. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3485. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3486. 姿态:站立。}{{阳光青年}}
  3487. ###美术风格
  3488. 基础画风风格词:厚涂古风
  3489. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3490. ###场景列表
  3491. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3492. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3493. 无人物。}";
  3494. // 构建消息
  3495. $messages = [
  3496. [
  3497. 'role' => 'system',
  3498. 'content' => $systemPrompt
  3499. ],
  3500. [
  3501. 'role' => 'user',
  3502. 'content' => "以下是文档内容:
  3503. {$content}
  3504. 用户问题:
  3505. {$question}"
  3506. ]
  3507. ];
  3508. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3509. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3510. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3511. if ($model === 'deepseek-chat') {
  3512. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3513. $model = 'deepseek-v4-flash';
  3514. $thinkingMode = 'disabled';
  3515. } elseif ($model === 'deepseek-reasoner') {
  3516. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3517. $model = 'deepseek-v4-flash';
  3518. $thinkingMode = 'enabled';
  3519. }
  3520. $post_data = [
  3521. 'model' => $model,
  3522. 'messages' => $messages,
  3523. // 'max_tokens' => 8192,
  3524. 'temperature' => 0.7,
  3525. 'frequency_penalty' => 0,
  3526. 'presence_penalty' => 0,
  3527. 'response_format' => ['type' => 'text'],
  3528. 'thinking' => ['type'=>$thinkingMode],
  3529. 'stream' => true // 启用流式输出
  3530. ];
  3531. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3532. // 根据模型类型选择调用方法
  3533. $fullContent = '';
  3534. $fullReasoningContent = '';
  3535. $usage = [];
  3536. try {
  3537. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3538. // DeepSeek 官方模型使用 DeepSeek API
  3539. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3540. } else if (in_array($model, $this->gpt_text_models)) {
  3541. // GPT-5.4 模型使用 TokenRouter API
  3542. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3543. } else {
  3544. // 其他模型使用火山引擎API
  3545. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3546. }
  3547. // 验证返回值类型
  3548. if (!is_iterable($streamGenerator)) {
  3549. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3550. dLog('deepseek')->error('addChat流式生成器无效', [
  3551. 'generator_type' => $errorType,
  3552. 'model' => $model,
  3553. 'anime_id' => $anime_id
  3554. ]);
  3555. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3556. 'type' => $errorType,
  3557. 'model' => $model
  3558. ]);
  3559. yield [
  3560. 'type' => 'error',
  3561. 'script' => [],
  3562. 'episode' => [],
  3563. 'answer' => '',
  3564. 'reasoning' => '',
  3565. 'usage' => [],
  3566. 'error' => '接口返回数据异常,请重新请求'
  3567. ];
  3568. return;
  3569. }
  3570. // 处理流式输出
  3571. foreach ($streamGenerator as $chunk) {
  3572. if (isset($chunk['type'])) {
  3573. if ($chunk['type'] === 'done') {
  3574. // 最终结果
  3575. $fullContent = $chunk['full_content'];
  3576. $fullReasoningContent = $chunk['full_reasoning'];
  3577. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3578. } else {
  3579. // 逐块yield数据
  3580. yield $chunk;
  3581. }
  3582. }
  3583. }
  3584. } catch (\Exception $e) {
  3585. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3586. 'model' => $model,
  3587. 'anime_id' => $anime_id,
  3588. 'trace' => $e->getTraceAsString()
  3589. ]);
  3590. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3591. 'error' => $e->getMessage(),
  3592. 'model' => $model
  3593. ]);
  3594. yield [
  3595. 'type' => 'error',
  3596. 'script' => [],
  3597. 'episode' => [],
  3598. 'answer' => '',
  3599. 'reasoning' => '',
  3600. 'usage' => [],
  3601. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3602. ];
  3603. return;
  3604. }
  3605. dLog('deepseek')->info('完整内容: '.$fullContent);
  3606. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3607. // 处理完整内容并返回最终结果
  3608. $script_arr = [];
  3609. if ($fullContent) {
  3610. $script_arr = handleScriptContent($fullContent);
  3611. dLog('deepseek')->info('解析内容', $script_arr);
  3612. logDB('deepseek', 'info', '解析内容', $script_arr);
  3613. }
  3614. if (empty($script_arr['roles'])) {
  3615. // 未生成剧本相关内容,保存对话记录并返回提示
  3616. dLog('deepseek')->info('未生成剧本相关的内容');
  3617. try {
  3618. DB::beginTransaction();
  3619. $now = date('Y-m-d H:i:s');
  3620. // 保存对话记录
  3621. $records = [
  3622. [
  3623. 'uid' => $uid,
  3624. 'anime_id' => $anime_id,
  3625. 'sequence' => 0,
  3626. 'role' => 'user',
  3627. 'content' => $prompt,
  3628. 'created_at' => $now,
  3629. 'updated_at' => $now
  3630. ],
  3631. [
  3632. 'uid' => $uid,
  3633. 'anime_id' => $anime_id,
  3634. 'sequence' => 0,
  3635. 'role' => 'assistant',
  3636. // 'content' => $fullContent,
  3637. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3638. 'created_at' => $now,
  3639. 'updated_at' => $now
  3640. ]
  3641. ];
  3642. DB::table('mp_anime_records')->insert($records);
  3643. DB::commit();
  3644. } catch (\Exception $e) {
  3645. DB::rollBack();
  3646. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3647. }
  3648. yield [
  3649. 'type' => 'done',
  3650. 'script' => [],
  3651. 'episode' => [],
  3652. 'answer' => $fullContent,
  3653. 'reasoning' => $fullReasoningContent,
  3654. 'usage' => $usage,
  3655. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3656. ];
  3657. return;
  3658. }
  3659. // 如果需要生成原文内容,从script_arr中提取
  3660. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3661. $content = $script_arr['content'];
  3662. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3663. if (!$content) {
  3664. yield [
  3665. 'type' => 'done',
  3666. 'script' => [],
  3667. 'episode' => [],
  3668. 'answer' => $fullContent,
  3669. 'reasoning' => $fullReasoningContent,
  3670. 'usage' => $usage,
  3671. 'error' => '未生成剧本内容,请调整提示词再试'
  3672. ];
  3673. return;
  3674. }
  3675. }
  3676. // 替换美术风格
  3677. if ($mappedArtStyle !== '') {
  3678. $script_arr['art_style'] = $mappedArtStyle;
  3679. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3680. }
  3681. // 新建动漫
  3682. if ($user_anime_name == '新剧本策划') {
  3683. $anime_name = getProp($script_arr, 'script_name');
  3684. // if (!$anime_name) {
  3685. // // 未识别到剧本名,保存对话记录并返回提示
  3686. // dLog('deepseek')->info('未能识别到剧本名称');
  3687. // try {
  3688. // DB::beginTransaction();
  3689. // $now = date('Y-m-d H:i:s');
  3690. // // 保存对话记录
  3691. // $records = [
  3692. // [
  3693. // 'uid' => $uid,
  3694. // 'anime_id' => $anime_id,
  3695. // 'sequence' => 0,
  3696. // 'role' => 'user',
  3697. // 'content' => $prompt,
  3698. // 'created_at' => $now,
  3699. // 'updated_at' => $now
  3700. // ],
  3701. // [
  3702. // 'uid' => $uid,
  3703. // 'anime_id' => $anime_id,
  3704. // 'sequence' => 0,
  3705. // 'role' => 'assistant',
  3706. // 'content' => '未能生成剧本名称,请重试',
  3707. // 'created_at' => $now,
  3708. // 'updated_at' => $now
  3709. // ]
  3710. // ];
  3711. // DB::table('mp_anime_records')->insert($records);
  3712. // DB::commit();
  3713. // } catch (\Exception $e) {
  3714. // DB::rollBack();
  3715. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3716. // }
  3717. // yield [
  3718. // 'type' => 'done',
  3719. // 'script' => [],
  3720. // 'episode' => [],
  3721. // 'answer' => $fullContent,
  3722. // 'reasoning' => $fullReasoningContent,
  3723. // 'usage' => $usage,
  3724. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3725. // ];
  3726. // return;
  3727. // }
  3728. // 确认对话名称唯一性
  3729. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3730. $anime_name = $anime_name . '_' . date('YmdHis');
  3731. }
  3732. }else {
  3733. $anime_name = $user_anime_name;
  3734. }
  3735. $table_data = [
  3736. 'user_id' => $uid,
  3737. 'anime_name' => $anime_name,
  3738. 'model' => $model,
  3739. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3740. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3741. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3742. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3743. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3744. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3745. 'art_style_type' => $input_art_style,
  3746. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3747. 'status' => '解析完成',
  3748. 'content' => $content,
  3749. 'is_multi' => $is_multi,
  3750. 'ace_mode' => $ace_mode,
  3751. 'generate_status' => '待执行',
  3752. 'updated_at' => date('Y-m-d H:i:s')
  3753. ];
  3754. if ($table_data['content']) {
  3755. $chapters = splitContent($table_data['content']);
  3756. $chapter_count = count($chapters);
  3757. if ($chapter_count > 0) {
  3758. $table_data['start_episode_sequence'] = 1;
  3759. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3760. }
  3761. }
  3762. // 如果有剧本ID则进行绑定
  3763. if ($script_id) {
  3764. $table_data['script_id'] = $script_id;
  3765. }
  3766. $single_episode = [];
  3767. try {
  3768. DB::beginTransaction();
  3769. $now = date('Y-m-d H:i:s');
  3770. // 更新动漫大纲
  3771. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3772. if (!$boolen) {
  3773. dLog('deepseek')->info('动漫保存失败', $table_data);
  3774. Utils::throwError('20003:动漫保存失败');
  3775. }
  3776. // 保存对话记录
  3777. $records = [
  3778. [
  3779. 'uid' => $uid,
  3780. 'anime_id' => $anime_id,
  3781. 'sequence' => 0,
  3782. 'role' => 'user',
  3783. 'content' => $prompt,
  3784. 'created_at' => date('Y-m-d H:i:s'),
  3785. 'updated_at' => date('Y-m-d H:i:s')
  3786. ],
  3787. [
  3788. 'uid' => $uid,
  3789. 'anime_id' => $anime_id,
  3790. 'sequence' => 0,
  3791. 'role' => 'assistant',
  3792. 'content' => $fullContent,
  3793. 'created_at' => date('Y-m-d H:i:s'),
  3794. 'updated_at' => date('Y-m-d H:i:s')
  3795. ]
  3796. ];
  3797. // 保存对话记录
  3798. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3799. if (!$boolen3) {
  3800. Utils::throwError('20003:对话记录保存失败');
  3801. }
  3802. if ($is_single) {
  3803. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3804. if (empty($episode_arr['acts'])) {
  3805. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3806. }
  3807. $saveResult = $this->saveEpisodeVersionData(
  3808. $anime_id,
  3809. 1,
  3810. $episode_arr,
  3811. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3812. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3813. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3814. null,
  3815. null,
  3816. false,
  3817. $content,
  3818. $now
  3819. );
  3820. $single_episode = $saveResult['episode'];
  3821. $episode_id = $saveResult['episode_id'];
  3822. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3823. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3824. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3825. 'props' => json_encode($saveResult['merged_props'], 256),
  3826. 'updated_at' => $now
  3827. ]);
  3828. if ($boolen5 === false) {
  3829. Utils::throwError('20003:单剧集主表资源同步失败');
  3830. }
  3831. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3832. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3833. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3834. $episode_record_content = '确认分镜大纲';
  3835. if ($content !== '') {
  3836. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3837. }
  3838. $episode_records = [
  3839. [
  3840. 'uid' => $uid,
  3841. 'anime_id' => $anime_id,
  3842. 'role' => 'user',
  3843. 'content' => $episode_record_content,
  3844. 'sequence' => 1,
  3845. 'episode_id' => $episode_id,
  3846. 'created_at' => $now,
  3847. 'updated_at' => $now
  3848. ],
  3849. [
  3850. 'uid' => $uid,
  3851. 'anime_id' => $anime_id,
  3852. 'role' => 'assistant',
  3853. 'content' => $fullContent,
  3854. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3855. 'sequence' => 1,
  3856. 'episode_id' => $episode_id,
  3857. 'created_at' => $now,
  3858. 'updated_at' => $now
  3859. ]
  3860. ];
  3861. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3862. if (!$boolen4) {
  3863. Utils::throwError('20003:单剧集分镜记录保存失败');
  3864. }
  3865. }
  3866. }catch (\Exception $e) {
  3867. DB::rollBack();
  3868. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3869. yield [
  3870. 'type' => 'done',
  3871. 'answer' => $fullContent,
  3872. 'reasoning' => $fullReasoningContent,
  3873. 'usage' => $usage,
  3874. 'error' => $e->getMessage(),
  3875. ];
  3876. return;
  3877. }
  3878. DB::commit();
  3879. dLog('deepseek')->info('保存完毕');
  3880. if ($is_single && !empty($single_episode)) {
  3881. // $this->batchSetGlobalRoleImg([
  3882. // 'anime_id' => $anime_id,
  3883. // ]);
  3884. // $this->batchSetGlobalSceneImg([
  3885. // 'anime_id' => $anime_id,
  3886. // ]);
  3887. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3888. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3889. }
  3890. $table_data['anime_id'] = $anime_id;
  3891. $table_data['roles'] = json_decode($table_data['roles'], true);
  3892. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3893. // $table_data['episodes'] = $script_arr['episodes'];
  3894. unset($table_data['created_at']);
  3895. unset($table_data['updated_at']);
  3896. unset($table_data['status']);
  3897. dLog('deepseek')->info('开始返回');
  3898. yield [
  3899. 'type' => 'done',
  3900. 'script' => $table_data,
  3901. 'episode' => $single_episode,
  3902. 'answer' => $fullContent,
  3903. 'reasoning' => $fullReasoningContent,
  3904. 'usage' => $usage
  3905. ];
  3906. }
  3907. public function reGenerateAnime($data) {
  3908. $uid = Site::getUid();
  3909. $file = getProp($data, 'file');
  3910. $content = getProp($data, 'content', '');
  3911. $bid = getProp($data, 'bid', 0);
  3912. $script_id = getProp($data, 'script_id', 0);
  3913. $anime_id = getProp($data, 'anime_id');
  3914. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3915. if (!$anime) {
  3916. Utils::throwError('20003:该对话不存在');
  3917. }
  3918. $user_anime_name = getProp($anime, 'anime_name');
  3919. $prompt = getProp($data, 'prompt');
  3920. // 处理文本模型
  3921. $model = getProp($data, 'model');
  3922. if (!$model) {
  3923. // 用户没有输入,从anime表获取
  3924. $model = getProp($anime, 'model');
  3925. if (!$model) {
  3926. // anime表也没有,使用默认值
  3927. $model = 'doubao-seed-2-0-mini-260215';
  3928. }
  3929. }
  3930. // 验证模型是否在可用模型表中
  3931. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3932. $model = 'doubao-seed-2-0-mini-260215';
  3933. }
  3934. $is_multi = getProp($anime, 'is_multi', 1);
  3935. $is_single = (int)$is_multi !== 1;
  3936. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3937. if ($is_single) {
  3938. $episode_exists = DB::table('mp_anime_episodes')
  3939. ->where('anime_id', $anime_id)
  3940. ->where('sequence', 1)
  3941. ->exists();
  3942. if ($episode_exists) {
  3943. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3944. }
  3945. }
  3946. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3947. if ($prompt) {
  3948. $question .= "本次修改要求如下:\n{$prompt}";
  3949. }
  3950. // 提取文件内容
  3951. if ($file) {
  3952. $content = $this->extractFileContent($file);
  3953. if (!$content) {
  3954. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3955. }
  3956. } elseif ($script_id) {
  3957. $content = $this->getContentByScriptId($script_id);
  3958. if (!$content) {
  3959. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3960. }
  3961. } elseif ($bid) {
  3962. $content = $this->getContentByBid($bid);
  3963. if (!$content) {
  3964. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3965. }
  3966. } elseif ($content) {
  3967. $content = filterContent($content);
  3968. }else {
  3969. $content = filterContent(getProp($anime, 'content'));
  3970. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3971. $need_generate_content = true;
  3972. }
  3973. }
  3974. // 判断是否需要生成原文内容
  3975. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3976. // 如果需要生成原文内容,添加额外的要求
  3977. $content_generation_requirement = $need_generate_content
  3978. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3979. : "";
  3980. // 美术风格
  3981. $input_art_style = getProp($anime, 'art_style');
  3982. if (!$input_art_style) {
  3983. $input_art_style = getProp($data, 'art_style');
  3984. }
  3985. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3986. // 美术风格
  3987. if (!$mappedArtStyle) {
  3988. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3989. }else {
  3990. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3991. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3992. }else {
  3993. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3994. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3995. }
  3996. }
  3997. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3998. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3999. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4000. 中年女:邻居阿姨
  4001. 老年男:幽默大爷
  4002. 老年女:婆婆
  4003. 萌娃:奶气萌娃";
  4004. $system_message = ['role'=>'system', 'content'=>$is_single
  4005. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4006. 强制要求:
  4007. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4008. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4009. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4010. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4011. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4012. 普通要求:
  4013. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4014. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4015. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4016. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4017. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4018. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4019. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4020. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4021. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4022. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4023. 3.$mappedArtStyle_prompt\n\n
  4024. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4025. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4026. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4027. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4028. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4029. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4030. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4031. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4032. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4033. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4034. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4035. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4036. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4037. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4038. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4039. 示例如下:\n
  4040. ###剧本名:西昆仑
  4041. ###故事梗概
  4042. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4043. ###剧本亮点
  4044. 亮点1:绝境奇药,生死一线
  4045. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4046. 亮点2:结拜兄妹,化解尴尬
  4047. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4048. 亮点3:纤发夺命,情愫暗涌
  4049. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4050. ###人物关系
  4051. 阿雪与梁萧之间存在兄妹之情。
  4052. ###核心矛盾
  4053. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4054. ###主体列表
  4055. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4056. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4057. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4058. 姿态:站立。}{{甜心小美}}
  4059. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4060. 全景,正面拍摄,青年女性,亚洲人。
  4061. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4062. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4063. 姿态:站立。}{{阳光青年}}
  4064. ###美术风格
  4065. 基础画风风格词:厚涂古风
  4066. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4067. ###场景列表
  4068. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4069. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4070. 无人物。}
  4071. ###分镜剧本
  4072. ##第1幕:徐家老旧厨房 白天 室内
  4073. 分镜1
  4074. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4075. 场景:徐家老旧厨房
  4076. 构图设计:全景,低角度仰视
  4077. 运镜调度:手持拍摄
  4078. 配音角色:旁白
  4079. 出镜角色:许芸-校服装、徐母
  4080. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4081. 画面类型:普通画面
  4082. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4083. 分镜2
  4084. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4085. 场景:徐家老旧厨房
  4086. 构图设计:近景,徐母面部特写
  4087. 运镜调度:固定镜头
  4088. 配音角色:徐母
  4089. 出镜角色:徐母
  4090. 台词内容:问我夜不归宿死哪儿去了。
  4091. 画面类型:对口型
  4092. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4093. ##第2幕:徐家简陋客厅 黄昏 室内
  4094. 分镜3
  4095. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4096. 场景:徐家简陋客厅
  4097. 构图设计:全景,景深虚化
  4098. 运镜调度:固定镜头
  4099. 配音角色:旁白
  4100. 出镜角色:无
  4101. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4102. 画面类型:普通画面
  4103. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4104. 分镜4
  4105. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4106. 场景:徐家简陋客厅
  4107. 构图设计:特写,火车票
  4108. 运镜调度:固定镜头
  4109. 配音角色:旁白
  4110. 出镜角色:无
  4111. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4112. 画面类型:普通画面
  4113. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4114. "
  4115. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4116. 强制要求:\n
  4117. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4118. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4119. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4120. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4121. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4122. 普通要求:\n
  4123. 1.剧本名(必须生成)必须与文档内容高度相关
  4124. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4125. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4126. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4127. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4128. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4129. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4130. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4131. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4132. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4133. 4.$mappedArtStyle_prompt\n\n
  4134. 示例如下:\n
  4135. ###剧本名:西昆仑
  4136. ###故事梗概
  4137. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4138. ###剧本亮点
  4139. 亮点1:绝境奇药,生死一线
  4140. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4141. 亮点2:结拜兄妹,化解尴尬
  4142. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4143. 亮点3:纤发夺命,情愫暗涌
  4144. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4145. ###人物关系
  4146. 阿雪与梁萧之间存在兄妹之情。
  4147. ###核心矛盾
  4148. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4149. ###主体列表
  4150. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4151. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4152. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4153. 姿态:站立。}{{甜心小美}}
  4154. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4155. 全景,正面拍摄,青年女性,亚洲人。
  4156. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4157. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4158. 姿态:站立。}{{阳光青年}}
  4159. ###美术风格
  4160. 基础画风风格词:厚涂古风
  4161. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4162. ###场景列表
  4163. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4164. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4165. 无人物。}"];
  4166. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4167. $episode_count = $this->extractEpisodeNumber($prompt);
  4168. if ((int)getProp($anime, 'is_multi') !== 1) {
  4169. yield [
  4170. 'type' => 'done',
  4171. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4172. 'reasoning' => '',
  4173. 'usage' => []
  4174. ];
  4175. return;
  4176. }
  4177. if ($episode_count) {
  4178. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4179. $system_message = [
  4180. 'role' => 'system',
  4181. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4182. 强制要求:\n
  4183. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4184. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4185. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4186. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4187. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4188. 普通要求:\n
  4189. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4190. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4191. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4192. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4193. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4194. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4195. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4196. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4197. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4198. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4199. 示例如下:\n
  4200. ###剧本名:西昆仑
  4201. ###故事梗概
  4202. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4203. ###剧本亮点
  4204. 亮点1:绝境奇药,生死一线
  4205. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4206. 亮点2:结拜兄妹,化解尴尬
  4207. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4208. 亮点3:纤发夺命,情愫暗涌
  4209. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4210. ###人物关系
  4211. 阿雪与梁萧之间存在兄妹之情。
  4212. ###核心矛盾
  4213. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4214. ###主体列表
  4215. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4216. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4217. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4218. 姿态:站立。}{{甜心小美}}
  4219. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4220. 全景,正面拍摄,青年女性,亚洲人。
  4221. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4222. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4223. 姿态:站立。}{{阳光青年}}
  4224. ###美术风格
  4225. 基础画风风格词:厚涂古风
  4226. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4227. ###场景列表
  4228. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4229. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4230. 无人物。}
  4231. ###分集详细内容
  4232. ##第1章 重生
  4233. 我重生了。
  4234. 源于一个男人偏执的暗恋。
  4235. ##第2章 相救
  4236. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4237. 我眼睛扫向站在锅炉后的卞大伟。"
  4238. ];
  4239. // 构建消息
  4240. $messages = [
  4241. $system_message,
  4242. [
  4243. 'role' => 'user',
  4244. 'content' => "以下是文档内容:
  4245. {$content}
  4246. 用户问题:
  4247. {$question}"
  4248. ]
  4249. ];
  4250. }else {
  4251. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4252. // 构建消息
  4253. $messages = [
  4254. $system_message,
  4255. [
  4256. 'role' => 'user',
  4257. 'content' => "以下是文档内容:
  4258. {$content}
  4259. 用户问题:
  4260. {$question}"
  4261. ]
  4262. ];
  4263. }else {
  4264. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4265. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4266. return (array)$value;
  4267. })->toArray();
  4268. array_unshift($messages, $system_message);
  4269. $messages[] = [
  4270. 'role' => 'user',
  4271. 'content' => $prompt
  4272. ];
  4273. }
  4274. }
  4275. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4276. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4277. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4278. if ($model === 'deepseek-chat') {
  4279. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4280. $model = 'deepseek-v4-flash';
  4281. $thinkingMode = 'disabled';
  4282. } elseif ($model === 'deepseek-reasoner') {
  4283. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4284. $model = 'deepseek-v4-flash';
  4285. $thinkingMode = 'enabled';
  4286. }
  4287. $post_data = [
  4288. 'model' => $model,
  4289. 'messages' => $messages,
  4290. // 'max_tokens' => 8192,
  4291. 'temperature' => 0.7,
  4292. 'frequency_penalty' => 0,
  4293. 'presence_penalty' => 0,
  4294. 'response_format' => ['type' => 'text'],
  4295. 'thinking' => ['type' => $thinkingMode],
  4296. 'stream' => true // 启用流式输出
  4297. ];
  4298. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4299. // 根据模型类型选择调用方法
  4300. $fullContent = '';
  4301. $fullReasoningContent = '';
  4302. $usage = [];
  4303. // dd($post_data);
  4304. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4305. try {
  4306. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4307. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4308. } else if (in_array($model, $this->gpt_text_models)) {
  4309. // GPT-5.4 模型使用 TokenRouter API
  4310. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4311. } else {
  4312. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4313. }
  4314. // 验证返回值类型
  4315. if (!is_iterable($streamGenerator)) {
  4316. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4317. dLog('deepseek')->error('方法名流式生成器无效', [
  4318. 'generator_type' => $errorType,
  4319. 'model' => $model,
  4320. // 添加其他上下文信息
  4321. ]);
  4322. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4323. 'type' => $errorType,
  4324. 'model' => $model
  4325. ]);
  4326. yield [
  4327. 'type' => 'error',
  4328. // 根据方法返回相应的空数据结构
  4329. 'answer' => '',
  4330. 'reasoning' => '',
  4331. 'usage' => [],
  4332. 'error' => '接口返回数据异常,请重新请求'
  4333. ];
  4334. return;
  4335. }
  4336. // 处理流式输出
  4337. foreach ($streamGenerator as $chunk) {
  4338. if (isset($chunk['type'])) {
  4339. if ($chunk['type'] === 'done') {
  4340. $fullContent = $chunk['full_content'];
  4341. $fullReasoningContent = $chunk['full_reasoning'];
  4342. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4343. } else {
  4344. yield $chunk;
  4345. }
  4346. }
  4347. }
  4348. } catch (\Exception $e) {
  4349. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4350. 'model' => $model,
  4351. 'trace' => $e->getTraceAsString()
  4352. ]);
  4353. logDB('deepseek', 'error', '方法名流式处理失败', [
  4354. 'error' => $e->getMessage(),
  4355. 'model' => $model
  4356. ]);
  4357. yield [
  4358. 'type' => 'error',
  4359. // 根据方法返回相应的空数据结构
  4360. 'answer' => '',
  4361. 'reasoning' => '',
  4362. 'usage' => [],
  4363. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4364. ];
  4365. return;
  4366. }
  4367. dLog('deepseek')->info('完整内容: '.$fullContent);
  4368. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4369. // 处理完整内容并返回最终结果
  4370. $script_arr = [];
  4371. if ($fullContent) {
  4372. $script_arr = handleScriptContent($fullContent);
  4373. dLog('deepseek')->info('解析内容', $script_arr);
  4374. logDB('deepseek', 'info', '解析内容', $script_arr);
  4375. }
  4376. if (empty($script_arr['roles'])) {
  4377. // 未生成剧本相关内容,保存对话记录并返回提示
  4378. dLog('deepseek')->info('未生成剧本相关的内容');
  4379. try {
  4380. $now = date('Y-m-d H:i:s');
  4381. // 保存对话记录
  4382. $records = [
  4383. [
  4384. 'uid' => $uid,
  4385. 'anime_id' => $anime_id,
  4386. 'sequence' => 0,
  4387. 'role' => 'user',
  4388. 'content' => $prompt,
  4389. 'created_at' => $now,
  4390. 'updated_at' => $now
  4391. ],
  4392. [
  4393. 'uid' => $uid,
  4394. 'anime_id' => $anime_id,
  4395. 'sequence' => 0,
  4396. 'role' => 'assistant',
  4397. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4398. 'created_at' => $now,
  4399. 'updated_at' => $now
  4400. ]
  4401. ];
  4402. DB::table('mp_anime_records')->insert($records);
  4403. } catch (\Exception $e) {
  4404. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4405. }
  4406. yield [
  4407. 'type' => 'done',
  4408. 'script' => [],
  4409. 'episode' => [],
  4410. 'answer' => $fullContent,
  4411. 'reasoning' => $fullReasoningContent,
  4412. 'usage' => $usage,
  4413. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4414. ];
  4415. return;
  4416. }
  4417. // 替换美术风格
  4418. if ($mappedArtStyle !== '') {
  4419. $script_arr['art_style'] = $mappedArtStyle;
  4420. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4421. }
  4422. if ($user_anime_name != '新剧本策划') {
  4423. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4424. // 确认对话名称唯一性
  4425. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4426. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4427. }
  4428. }else {
  4429. $anime_name = $user_anime_name;
  4430. }
  4431. $table_data = [
  4432. 'user_id' => $uid,
  4433. 'model' => $model,
  4434. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4435. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4436. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4437. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4438. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4439. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4440. 'art_style_type' => $input_art_style,
  4441. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4442. 'status' => '解析完成',
  4443. 'generate_status' => '待执行',
  4444. 'updated_at' => date('Y-m-d H:i:s')
  4445. ];
  4446. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4447. // 如果是修改集数,则将content内容更新(会改变原文)
  4448. if (isset($episode_count) && $episode_count > 0) {
  4449. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4450. $table_data['start_episode_sequence'] = 1;
  4451. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4452. }else {
  4453. // 如果需要生成原文内容,从script_arr中提取
  4454. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4455. $table_data['content'] = $script_arr['content'];
  4456. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4457. if (!$table_data['content']) {
  4458. yield [
  4459. 'type' => 'done',
  4460. 'script' => [],
  4461. 'episode' => [],
  4462. 'answer' => $fullContent,
  4463. 'reasoning' => $fullReasoningContent,
  4464. 'usage' => $usage,
  4465. 'error' => '未生成剧本内容,请调整提示词再试'
  4466. ];
  4467. return;
  4468. }
  4469. }
  4470. if (isset($table_data['content']) && $table_data['content']) {
  4471. $chapters = splitContent($table_data['content']);
  4472. $chapter_count = count($chapters);
  4473. if ($chapter_count > 0) {
  4474. $table_data['start_episode_sequence'] = 1;
  4475. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4476. }
  4477. }
  4478. }
  4479. $single_episode = [];
  4480. try {
  4481. DB::beginTransaction();
  4482. $now = date('Y-m-d H:i:s');
  4483. // 更新动漫大纲
  4484. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4485. if (!$boolen) {
  4486. dLog('deepseek')->info('对话修改失败', $table_data);
  4487. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4488. Utils::throwError('20003:对话修改失败');
  4489. }
  4490. // 保存对话记录
  4491. $records = [
  4492. [
  4493. 'uid' => $uid,
  4494. 'anime_id' => $anime_id,
  4495. 'sequence' => 0,
  4496. 'role' => 'user',
  4497. 'content' => $prompt,
  4498. 'created_at' => $now,
  4499. 'updated_at' => $now
  4500. ],
  4501. [
  4502. 'uid' => $uid,
  4503. 'anime_id' => $anime_id,
  4504. 'sequence' => 0,
  4505. 'role' => 'assistant',
  4506. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4507. 'content' => $fullContent,
  4508. 'created_at' => $now,
  4509. 'updated_at' => $now
  4510. ]
  4511. ];
  4512. // 保存对话记录
  4513. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4514. if (!$boolen3) {
  4515. Utils::throwError('20003:对话记录保存失败');
  4516. }
  4517. // 单剧集模式:生成并保存剧集信息
  4518. if ($is_single) {
  4519. $anime_name = getProp($anime, 'anime_name', '未命名');
  4520. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4521. if (empty($episode_arr['acts'])) {
  4522. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4523. }
  4524. $saveResult = $this->saveEpisodeVersionData(
  4525. $anime_id,
  4526. 1,
  4527. $episode_arr,
  4528. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4529. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4530. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4531. null,
  4532. null,
  4533. false,
  4534. $content,
  4535. $now
  4536. );
  4537. $single_episode = $saveResult['episode'];
  4538. $episode_id = $saveResult['episode_id'];
  4539. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4540. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4541. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4542. 'props' => json_encode($saveResult['merged_props'], 256),
  4543. 'updated_at' => $now
  4544. ]);
  4545. if ($boolen5 === false) {
  4546. Utils::throwError('20003:单剧集主表资源同步失败');
  4547. }
  4548. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4549. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4550. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4551. $episode_record_content = '确认分镜大纲';
  4552. if ($content !== '') {
  4553. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4554. }
  4555. $episode_records = [
  4556. [
  4557. 'uid' => $uid,
  4558. 'anime_id' => $anime_id,
  4559. 'role' => 'user',
  4560. 'content' => $episode_record_content,
  4561. 'sequence' => 1,
  4562. 'episode_id' => $episode_id,
  4563. 'created_at' => $now,
  4564. 'updated_at' => $now
  4565. ],
  4566. [
  4567. 'uid' => $uid,
  4568. 'anime_id' => $anime_id,
  4569. 'role' => 'assistant',
  4570. 'content' => $fullContent,
  4571. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4572. 'sequence' => 1,
  4573. 'episode_id' => $episode_id,
  4574. 'created_at' => $now,
  4575. 'updated_at' => $now
  4576. ]
  4577. ];
  4578. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4579. if (!$boolen4) {
  4580. Utils::throwError('20003:单剧集分镜记录保存失败');
  4581. }
  4582. }
  4583. }catch (\Exception $e) {
  4584. DB::rollBack();
  4585. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4586. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4587. yield [
  4588. 'type' => 'done',
  4589. 'answer' => $fullContent,
  4590. 'reasoning' => $fullReasoningContent,
  4591. 'usage' => $usage,
  4592. 'error' => $e->getMessage(),
  4593. ];
  4594. return;
  4595. }
  4596. DB::commit();
  4597. dLog('deepseek')->info('保存完毕');
  4598. if ($is_single && !empty($single_episode)) {
  4599. // $this->batchSetGlobalRoleImg([
  4600. // 'anime_id' => $anime_id,
  4601. // ]);
  4602. // $this->batchSetGlobalSceneImg([
  4603. // 'anime_id' => $anime_id,
  4604. // ]);
  4605. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4606. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4607. }
  4608. $table_data['anime_id'] = $anime_id;
  4609. $table_data['roles'] = json_decode($table_data['roles'], true);
  4610. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4611. unset($table_data['updated_at']);
  4612. unset($table_data['status']);
  4613. yield [
  4614. 'type' => 'done',
  4615. 'script' => $table_data,
  4616. 'episode' => $single_episode,
  4617. 'answer' => $fullContent,
  4618. 'reasoning' => $fullReasoningContent,
  4619. 'usage' => $usage
  4620. ];
  4621. }
  4622. public function chat($data) {
  4623. $uid = Site::getUid();
  4624. $anime_id = getProp($data, 'anime_id');
  4625. $file = getProp($data, 'file');
  4626. $content = getProp($data, 'content', '');
  4627. $bid = getProp($data, 'bid', 0);
  4628. $script_id = getProp($data, 'script_id', 0);
  4629. $episode_number = getProp($data, 'episode_number', 1);
  4630. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4631. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4632. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4633. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4634. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4635. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4636. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4637. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4638. $roles = is_array($roles) ? $roles : [];
  4639. $scenes = is_array($scenes) ? $scenes : [];
  4640. // 获取最后一集序号
  4641. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4642. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4643. // 转换主体列表和场景列表的格式
  4644. // 获取参考主体或场景
  4645. if ((int)$episode_number === 1) {
  4646. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4647. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4648. }else {
  4649. $prev_episode_number = $episode_number - 1;
  4650. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4651. }
  4652. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4653. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4654. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4655. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4656. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4657. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4658. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4659. 中年女:邻居阿姨
  4660. 老年男:幽默大爷
  4661. 老年女:婆婆
  4662. 萌娃:奶气萌娃";
  4663. if ($roles_content) {
  4664. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4665. 主体范围:\n {$roles_content}\n
  4666. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4667. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4668. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4669. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4670. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4671. }else {
  4672. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4673. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4674. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4675. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4676. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4677. }
  4678. if ($scenes_content) {
  4679. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4680. 场景范围:\n {$scenes_content}\n
  4681. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4682. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4683. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4684. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4685. }else {
  4686. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4687. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4688. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4689. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4690. }
  4691. // 提取文件内容
  4692. if ($file) {
  4693. $uploaded_content = $this->extractFileContent($file);
  4694. if (!$uploaded_content) {
  4695. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4696. }
  4697. } elseif ($script_id) {
  4698. $uploaded_content = $this->getContentByScriptId($script_id);
  4699. if (!$uploaded_content) {
  4700. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4701. }
  4702. } elseif ($bid) {
  4703. $uploaded_content = $this->getContentByBid($bid);
  4704. if (!$uploaded_content) {
  4705. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4706. }
  4707. } elseif ($content) {
  4708. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4709. }
  4710. // elseif ($prompt) {
  4711. // $uploaded_content = filterContent($prompt);
  4712. // }
  4713. else {
  4714. $uploaded_content = '';
  4715. }
  4716. $input_art_style = getProp($anime, 'art_style');
  4717. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4718. // 美术风格
  4719. if (!$mappedArtStyle) {
  4720. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4721. }else {
  4722. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4723. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4724. }else {
  4725. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4726. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4727. }
  4728. }
  4729. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4730. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4731. // 强制要求:
  4732. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4733. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4734. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4735. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4736. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4737. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4738. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4739. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4740. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4741. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4742. // - 分镜要和场景列表、人物主体保持一致\n
  4743. // 普通要求:
  4744. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4745. // {$role_demo}
  4746. // {$scene_demo}
  4747. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4748. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4749. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4750. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4751. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4752. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4753. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4754. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4755. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4756. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4757. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4758. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4759. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4760. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4761. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4762. // 5.$mappedArtStyle_prompt\n\n
  4763. // 示例格式:\n
  4764. // 第1集:隐形的守护者
  4765. // ###故事梗概
  4766. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4767. // ###美术风格
  4768. // 基础画风风格词:韩漫二次元
  4769. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4770. // ###主体列表
  4771. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4772. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4773. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4774. // ###场景列表
  4775. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4776. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4777. // 无人物。}
  4778. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4779. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4780. // 无人物。}
  4781. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4782. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4783. // 无人物。}
  4784. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4785. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4786. // 无人物。}
  4787. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4788. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4789. // 无人物。}
  4790. // ###分镜剧本
  4791. // ##第1幕:徐家老旧厨房 白天 室内
  4792. // 分镜1
  4793. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4794. // 场景:徐家老旧厨房
  4795. // 构图设计:全景,低角度仰视
  4796. // 运镜调度:手持拍摄
  4797. // 配音角色:旁白
  4798. // 出镜角色:许芸-校服装、徐母
  4799. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4800. // 画面类型:普通画面
  4801. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4802. // 分镜2
  4803. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4804. // 场景:徐家老旧厨房
  4805. // 构图设计:近景,徐母面部特写
  4806. // 运镜调度:固定镜头
  4807. // 配音角色:徐母
  4808. // 出镜角色:徐母
  4809. // 台词内容:问我夜不归宿死哪儿去了。
  4810. // 画面类型:对口型
  4811. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4812. // ##第2幕:徐家简陋客厅 黄昏 室内
  4813. // 分镜3
  4814. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4815. // 场景:徐家简陋客厅
  4816. // 构图设计:全景,景深虚化
  4817. // 运镜调度:固定镜头
  4818. // 配音角色:旁白
  4819. // 出镜角色:无
  4820. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4821. // 画面类型:普通画面
  4822. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4823. // 分镜4
  4824. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4825. // 场景:徐家简陋客厅
  4826. // 构图设计:特写,火车票
  4827. // 运镜调度:固定镜头
  4828. // 配音角色:旁白
  4829. // 出镜角色:无
  4830. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4831. // 画面类型:普通画面
  4832. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4833. // \n\n";
  4834. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4835. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4836. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4837. 普通要求:
  4838. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4839. {$role_demo}
  4840. {$scene_demo}
  4841. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4842. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4843. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4844. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4845. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4846. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4847. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4848. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4849. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4850. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4851. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4852. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4853. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4854. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4855. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4856. 5.$mappedArtStyle_prompt
  4857. 6.《情绪-视听语言映射表》:
  4858. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4859. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4860. -----|---------|------------|----------------
  4861. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4862. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4863. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4864. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4865. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4866. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4867. -----|---------|------------|----------------
  4868. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4869. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4870. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4871. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4872. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4873. --------|---------|--------------|-------------
  4874. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4875. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4876. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4877. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4878. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4879. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4880. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4881. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4882. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4883. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4884. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4885. -----|---------|------------|------------
  4886. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4887. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4888. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4889. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4890. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4891. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4892. --------|---------|--------------|----------
  4893. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4894. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4895. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4896. 6.6 声音设计与潜意识影响 (Soundscape)
  4897. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4898. -----|---------|------------|------------------
  4899. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4900. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4901. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4902. 理论基石:
  4903. - The Five C's of Cinematography by Joseph V. Mascelli
  4904. - Film Art: An Introduction by David Bordwell
  4905. - Sight, Sound, Motion by Herbert Zettl
  4906. - Notes on the Cinematograph by Robert Bresson
  4907. \n\n
  4908. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4909. 示例格式:\n
  4910. 第1集:隐形的守护者
  4911. ###故事梗概
  4912. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4913. ###美术风格
  4914. 基础画风风格词:韩漫二次元
  4915. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4916. ###主体列表
  4917. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4918. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4919. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4920. ###场景列表
  4921. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4922. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4923. 无人物。}
  4924. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4925. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4926. 无人物。}
  4927. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4928. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4929. 无人物。}
  4930. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4931. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4932. 无人物。}
  4933. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4934. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4935. 无人物。}
  4936. ###分镜剧本
  4937. ##第1幕:徐家老旧厨房 白天 室内
  4938. 分镜1
  4939. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4940. 场景:徐家老旧厨房
  4941. 构图设计:全景,低角度仰视
  4942. 运镜调度:手持拍摄
  4943. 配音角色:旁白
  4944. 出镜角色:许芸-校服装、徐母
  4945. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4946. 画面类型:普通画面
  4947. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4948. 分镜2
  4949. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4950. 场景:徐家老旧厨房
  4951. 构图设计:近景,徐母面部特写
  4952. 运镜调度:固定镜头
  4953. 配音角色:徐母
  4954. 出镜角色:徐母
  4955. 台词内容:问我夜不归宿死哪儿去了。
  4956. 画面类型:对口型
  4957. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4958. ##第2幕:徐家简陋客厅 黄昏 室内
  4959. 分镜3
  4960. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4961. 场景:徐家简陋客厅
  4962. 构图设计:全景,景深虚化
  4963. 运镜调度:固定镜头
  4964. 配音角色:旁白
  4965. 出镜角色:无
  4966. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4967. 画面类型:普通画面
  4968. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4969. 分镜4
  4970. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4971. 场景:徐家简陋客厅
  4972. 构图设计:特写,火车票
  4973. 运镜调度:固定镜头
  4974. 配音角色:旁白
  4975. 出镜角色:无
  4976. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4977. 画面类型:普通画面
  4978. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4979. \n\n";
  4980. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4981. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4982. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4983. $prompt = $origin_prompt;
  4984. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4985. // 获取章节内容
  4986. $full_content = getProp($anime, 'content');
  4987. if ($uploaded_content) {
  4988. $full_content = $uploaded_content;
  4989. }
  4990. // 根据章节内容拆分章节
  4991. $chapters = splitContent($full_content);
  4992. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4993. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4994. $messages = [];
  4995. if ($prompt == '确认分镜大纲') {
  4996. // 暂时保留
  4997. $content = $chapter_content;
  4998. if ($is_single) $content = $full_content; // 单剧集使用全文
  4999. if (!$content) {
  5000. Utils::throwError('20003:章节内容无法获取,请确认');
  5001. }
  5002. $question = $is_single
  5003. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5004. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5005. // 构建消息
  5006. $messages[] =
  5007. [
  5008. 'role' => 'user',
  5009. 'content' => $question
  5010. ];
  5011. }else if ($prompt == '继续策划下一集') {
  5012. if ($is_single) {
  5013. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5014. }
  5015. $content = $chapter_content;
  5016. if (!$content) {
  5017. Utils::throwError('20003:章节内容无法获取,请确认');
  5018. }
  5019. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5020. // 获取上一集最后记录
  5021. $prev_sequence = $episode_number - 1;
  5022. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5023. // 构建消息
  5024. $messages[] =
  5025. [
  5026. 'role' => 'user',
  5027. 'content' => $question
  5028. ];
  5029. }else {
  5030. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5031. if (!$content) {
  5032. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5033. }
  5034. if (!$content) {
  5035. Utils::throwError('20003:章节内容无法获取,请确认');
  5036. }
  5037. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5038. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5039. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5040. if ($origin_prompt) {
  5041. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5042. }
  5043. $messages[] =
  5044. [
  5045. 'role' => 'user',
  5046. 'content' => $question
  5047. ];
  5048. }
  5049. // 处理文本模型
  5050. $model = getProp($data, 'model');
  5051. if (!$model) {
  5052. // 用户没有输入,从anime表获取
  5053. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5054. $model = getProp($anime, 'model');
  5055. if (!$model) {
  5056. // anime表也没有,使用默认值
  5057. $model = 'doubao-seed-2-0-mini-260215';
  5058. }
  5059. }
  5060. // 验证模型是否在可用模型表中
  5061. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5062. $model = 'doubao-seed-2-0-mini-260215';
  5063. }
  5064. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5065. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5066. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5067. if ($model === 'deepseek-chat') {
  5068. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5069. $model = 'deepseek-v4-flash';
  5070. $thinkingMode = 'disabled';
  5071. } elseif ($model === 'deepseek-reasoner') {
  5072. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5073. $model = 'deepseek-v4-flash';
  5074. $thinkingMode = 'enabled';
  5075. }
  5076. $post_data = [
  5077. 'model' => $model,
  5078. 'messages' => $messages,
  5079. // 'max_tokens' => 8192,
  5080. 'temperature' => 0.2,
  5081. 'frequency_penalty' => 0,
  5082. 'presence_penalty' => 0,
  5083. 'response_format' => ['type' => 'text'],
  5084. 'thinking' => ['type' => $thinkingMode],
  5085. 'stream' => true // 启用流式输出
  5086. ];
  5087. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5088. // 根据模型类型选择调用方法
  5089. $fullContent = '';
  5090. $fullReasoningContent = '';
  5091. $usage = [];
  5092. try {
  5093. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5094. // DeepSeek 官方模型使用 DeepSeek API
  5095. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5096. } else if (in_array($model, $this->gpt_text_models)) {
  5097. // GPT-5.4 模型使用 TokenRouter API
  5098. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5099. } else {
  5100. // 其他模型使用火山引擎API
  5101. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5102. }
  5103. // 验证返回值类型
  5104. if (!is_iterable($streamGenerator)) {
  5105. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5106. dLog('deepseek')->error('chat流式生成器无效', [
  5107. 'generator_type' => $errorType,
  5108. 'model' => $model,
  5109. 'anime_id' => $anime_id,
  5110. 'episode_number' => $episode_number
  5111. ]);
  5112. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5113. 'type' => $errorType,
  5114. 'model' => $model
  5115. ]);
  5116. yield [
  5117. 'type' => 'error',
  5118. 'episode' => [],
  5119. 'answer' => '',
  5120. 'reasoning' => '',
  5121. 'usage' => [],
  5122. 'error' => '接口返回数据异常,请重新请求'
  5123. ];
  5124. return;
  5125. }
  5126. // 处理流式输出
  5127. foreach ($streamGenerator as $chunk) {
  5128. if (isset($chunk['type'])) {
  5129. if ($chunk['type'] === 'done') {
  5130. // 最终结果
  5131. $fullContent = $chunk['full_content'];
  5132. $fullReasoningContent = $chunk['full_reasoning'];
  5133. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5134. } else {
  5135. // 逐块yield数据
  5136. yield $chunk;
  5137. }
  5138. }
  5139. }
  5140. } catch (\Exception $e) {
  5141. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5142. 'model' => $model,
  5143. 'anime_id' => $anime_id,
  5144. 'episode_number' => $episode_number,
  5145. 'trace' => $e->getTraceAsString()
  5146. ]);
  5147. logDB('deepseek', 'error', 'chat流式处理失败', [
  5148. 'error' => $e->getMessage(),
  5149. 'model' => $model
  5150. ]);
  5151. yield [
  5152. 'type' => 'error',
  5153. 'episode' => [],
  5154. 'answer' => '',
  5155. 'reasoning' => '',
  5156. 'usage' => [],
  5157. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5158. ];
  5159. return;
  5160. }
  5161. dLog('deepseek')->info('完整内容: '.$fullContent);
  5162. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5163. // 处理完整内容并返回最终结果
  5164. $episode_arr = handleEpisodeContent($fullContent);
  5165. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5166. if (empty($episode_arr['acts'])) {
  5167. // 未生成剧本相关内容,保存对话记录并返回提示
  5168. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5169. try {
  5170. $now = date('Y-m-d H:i:s');
  5171. // 保存对话记录
  5172. $records = [
  5173. [
  5174. 'uid' => $uid,
  5175. 'anime_id' => $anime_id,
  5176. 'sequence' => $episode_number,
  5177. 'role' => 'user',
  5178. 'content' => $prompt,
  5179. 'created_at' => $now,
  5180. 'updated_at' => $now
  5181. ],
  5182. [
  5183. 'uid' => $uid,
  5184. 'anime_id' => $anime_id,
  5185. 'sequence' => $episode_number,
  5186. 'role' => 'assistant',
  5187. 'content' => $fullContent,
  5188. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5189. 'created_at' => $now,
  5190. 'updated_at' => $now
  5191. ]
  5192. ];
  5193. DB::table('mp_anime_records')->insert($records);
  5194. } catch (\Exception $e) {
  5195. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5196. }
  5197. yield [
  5198. 'type' => 'done',
  5199. 'episode' => [],
  5200. 'answer' => $fullContent,
  5201. 'reasoning' => $fullReasoningContent,
  5202. 'usage' => $usage,
  5203. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5204. ];
  5205. return;
  5206. }
  5207. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5208. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5209. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5210. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5211. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5212. $existing_props = is_array($existing_props) ? $existing_props : [];
  5213. $now = date('Y-m-d H:i:s');
  5214. try {
  5215. DB::beginTransaction();
  5216. $saveResult = $this->saveEpisodeVersionData(
  5217. $anime_id,
  5218. $episode_number,
  5219. $episode_arr,
  5220. $existing_roles,
  5221. $existing_scenes,
  5222. $existing_props,
  5223. $current_episode,
  5224. $base_episode,
  5225. $is_regenerate_version,
  5226. $content,
  5227. $now
  5228. );
  5229. $episode = $saveResult['episode'];
  5230. $episode_id = $saveResult['episode_id'];
  5231. $merged_roles = $saveResult['merged_roles'];
  5232. $merged_scenes = $saveResult['merged_scenes'];
  5233. $merged_props = $saveResult['merged_props'];
  5234. $record_content = $origin_prompt;
  5235. if ($uploaded_content !== '') {
  5236. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5237. }
  5238. $records = [
  5239. [
  5240. 'uid' => $uid,
  5241. 'anime_id' => $anime_id,
  5242. 'role' => 'user',
  5243. 'content' => $record_content,
  5244. 'sequence' => $episode_number,
  5245. 'episode_id' => $episode_id,
  5246. 'created_at' => $now,
  5247. 'updated_at' => $now
  5248. ],
  5249. [
  5250. 'uid' => $uid,
  5251. 'anime_id' => $anime_id,
  5252. 'role' => 'assistant',
  5253. 'content' => $fullContent,
  5254. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5255. 'sequence' => $episode_number,
  5256. 'episode_id' => $episode_id,
  5257. 'created_at' => $now,
  5258. 'updated_at' => $now
  5259. ]
  5260. ];
  5261. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5262. if (!$boolen4) {
  5263. Utils::throwError('20003:对话记录保存失败');
  5264. }
  5265. // 保存模型和内容到anime表
  5266. $update_anime_data = [
  5267. 'model' => $model,
  5268. 'updated_at' => $now
  5269. ];
  5270. if ($uploaded_content) {
  5271. $update_anime_data['content'] = $uploaded_content;
  5272. }
  5273. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5274. }catch (\Exception $e) {
  5275. DB::rollBack();
  5276. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5277. yield [
  5278. 'type' => 'done',
  5279. 'answer' => $fullContent,
  5280. 'reasoning' => $fullReasoningContent,
  5281. 'usage' => $usage,
  5282. 'error' => $e->getMessage(),
  5283. ];
  5284. return;
  5285. }
  5286. DB::commit();
  5287. if ($is_global_generate_pics) {
  5288. // // 批量生成全局角色图片
  5289. // $this->batchSetGlobalRoleImg([
  5290. // 'anime_id' => $anime_id,
  5291. // ], true);
  5292. // // 批量生成全局场景图片
  5293. // $this->batchSetGlobalSceneImg([
  5294. // 'anime_id' => $anime_id,
  5295. // ], true);
  5296. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5297. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5298. }
  5299. $episode['episode_id'] = $episode_id;
  5300. $episode['roles'] = $merged_roles;
  5301. $episode['scenes'] = $merged_scenes;
  5302. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5303. yield [
  5304. 'type' => 'done',
  5305. 'episode' => $episode,
  5306. 'answer' => $fullContent,
  5307. 'reasoning' => $fullReasoningContent,
  5308. 'usage' => $usage
  5309. ];
  5310. }
  5311. public function addChatForAce($data) {
  5312. $uid = Site::getUid();
  5313. $anime_id = getProp($data, 'anime_id');
  5314. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5315. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5316. if (!$anime) Utils::throwError('20003:对话不存在');
  5317. $file = getProp($data, 'file');
  5318. $content = getProp($data, 'content', '');
  5319. $bid = getProp($data, 'bid', 0);
  5320. $script_id = getProp($data, 'script_id', 0);
  5321. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5322. $prompt = getProp($data, 'prompt');
  5323. $is_multi = getProp($anime, 'is_multi');
  5324. $is_single = (int)$is_multi !== 1;
  5325. $extra_products = getProp($data, 'products', []);
  5326. if (!$extra_products) {
  5327. $extra_products = getProp($anime, 'extra_products');
  5328. if ($extra_products) {
  5329. $extra_products = json_decode($extra_products, true);
  5330. }else {
  5331. $extra_products = [];
  5332. }
  5333. }else {
  5334. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5335. }
  5336. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5337. $anime_script_id = getProp($anime, 'script_id');
  5338. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5339. $cpid = Site::getCpid();
  5340. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5341. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5342. ->where('mapping.script_id', $anime_script_id)
  5343. ->where('product.cpid', $cpid)
  5344. ->where('product.is_deleted', 0);
  5345. $mappings = $script_products_mappings->select(
  5346. 'mapping.product_id',
  5347. 'mapping.episode_number',
  5348. 'product.product_name',
  5349. 'product.type',
  5350. 'product.product',
  5351. 'product.pic_prompt',
  5352. 'product.url',
  5353. 'product.pic_task_id',
  5354. 'product.pic_task_status',
  5355. 'product.three_view_image_url'
  5356. )
  5357. ->get();
  5358. // 按 product_id 分组,合并 episode_number
  5359. $productMap = [];
  5360. foreach ($mappings as $item) {
  5361. $product_id = $item->product_id;
  5362. $product_name = $item->product_name;
  5363. // 处理product_name两边的符号
  5364. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5365. if (!isset($productMap[$product_id])) {
  5366. $productMap[$product_id] = [
  5367. 'product_id' => $product_id,
  5368. 'product_name' => $product_name,
  5369. 'type' => (int)$item->type,
  5370. 'product' => (int)$item->product,
  5371. 'pic_prompt' => $item->pic_prompt,
  5372. 'url' => $item->url,
  5373. 'pic_task_id' => $item->pic_task_id,
  5374. 'pic_task_status' => $item->pic_task_status,
  5375. 'episode_numbers' => [],
  5376. ];
  5377. }
  5378. // 添加 episode_number(去重)
  5379. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5380. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5381. }
  5382. }
  5383. // 将查询到的剧本资产合并到extra_products中
  5384. // 先构建extra_products的索引(以product_id为key,用于去重)
  5385. $extraProductsMap = [];
  5386. foreach ($extra_products as $item) {
  5387. $key = getProp($item, 'product_id');
  5388. if ($key) {
  5389. $extraProductsMap[$key] = $item;
  5390. }
  5391. }
  5392. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5393. foreach ($productMap as $product) {
  5394. $product_id = $product['product_id'];
  5395. // 如果不存在则添加(不带episode_number信息)
  5396. if (!isset($extraProductsMap[$product_id])) {
  5397. $extraProductsMap[$product_id] = [
  5398. 'product_id' => $product['product_id'],
  5399. 'product_name' => $product['product_name'],
  5400. 'type' => $product['type'],
  5401. 'product' => $product['product'],
  5402. 'pic_prompt' => $product['pic_prompt'],
  5403. 'url' => $product['url'],
  5404. 'pic_task_id' => $product['pic_task_id'],
  5405. 'pic_task_status' => $product['pic_task_status'],
  5406. ];
  5407. }
  5408. }
  5409. // 重新赋值给extra_products
  5410. $extra_products = array_values($extraProductsMap);
  5411. }
  5412. $user_anime_name = getProp($anime, 'anime_name');
  5413. // 处理提示词
  5414. if ($prompt && $extra_products) {
  5415. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5416. foreach($extra_products as $item) {
  5417. $product_name = getProp($item, 'product_name');
  5418. if ($product_name) {
  5419. // 替换 {product_name} 为 product_name
  5420. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5421. }
  5422. }
  5423. }
  5424. // 处理文本模型
  5425. $model = getProp($data, 'model');
  5426. if (!$model) {
  5427. // 用户没有输入,从anime表获取
  5428. $model = getProp($anime, 'model');
  5429. if (!$model) {
  5430. // anime表也没有,使用默认值
  5431. $model = 'deepseek-v4-pro';
  5432. }
  5433. }
  5434. // 验证模型是否在可用模型表中
  5435. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5436. $model = 'deepseek-v4-pro';
  5437. }
  5438. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5439. if ($prompt) {
  5440. $question .= "本次修改要求如下:\n{$prompt}";
  5441. }
  5442. // if (!$file && !$content && !$bid) {
  5443. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5444. // }
  5445. // 提取文件内容
  5446. if ($file) {
  5447. $content = $this->extractFileContent($file);
  5448. if (!$content) {
  5449. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5450. }
  5451. } elseif ($script_id) {
  5452. $content = $this->getContentByScriptId($script_id);
  5453. if (!$content) {
  5454. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5455. }
  5456. } elseif ($bid) {
  5457. $content = $this->getContentByBid($bid);
  5458. if (!$content) {
  5459. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5460. }
  5461. } elseif ($content) {
  5462. $content = filterContent($content);
  5463. } else {
  5464. $content = getProp($anime, 'content');
  5465. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5466. $need_generate_content = true;
  5467. }
  5468. }
  5469. // 美术风格
  5470. $input_art_style = getProp($data, 'art_style');
  5471. if (!$input_art_style) {
  5472. $mappedArtStyle = getProp($anime, 'art_style');
  5473. }else {
  5474. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5475. }
  5476. // 判断是否需要生成原文内容
  5477. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5478. // 如果需要生成原文内容,添加额外的要求
  5479. $content_generation_requirement = $need_generate_content
  5480. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5481. : "";
  5482. // 美术风格
  5483. if (!$mappedArtStyle) {
  5484. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5485. }else {
  5486. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5487. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5488. }else {
  5489. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5490. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5491. }
  5492. }
  5493. // 构建主体、场景和道具提示词
  5494. $extra_role_prompt = "\n";
  5495. $extra_scene_prompt = "\n";
  5496. $extra_prop_prompt = "\n";
  5497. $ref_products = []; // 参考资产
  5498. if ($extra_products) {
  5499. foreach($extra_products as $item) {
  5500. $product = getProp($item, 'product');
  5501. $product_name = getProp($item, 'product_name');
  5502. if ($product_name == '旁白') continue;
  5503. $ref_products[$product_name] = $item;
  5504. $pic_prompt = getProp($item, 'pic_prompt');
  5505. if ((int)$product === 1) {
  5506. // 拼接角色信息
  5507. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5508. } elseif ((int)$product === 2) {
  5509. // 拼接场景信息
  5510. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5511. } elseif ((int)$product === 3) {
  5512. // 拼接道具信息
  5513. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5514. }
  5515. }
  5516. // 优化提示词,融入剧本
  5517. if (!empty(trim($extra_role_prompt))) {
  5518. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5519. }
  5520. if (!empty(trim($extra_scene_prompt))) {
  5521. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5522. }
  5523. if (!empty(trim($extra_prop_prompt))) {
  5524. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5525. }
  5526. }
  5527. if ($anime_script_id && $is_single) {
  5528. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5529. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5530. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5531. }else {
  5532. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5533. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5534. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5535. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5536. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5537. {$extra_role_prompt}";
  5538. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5539. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5540. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5541. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5542. {$extra_scene_prompt}";
  5543. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5544. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5545. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5546. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5547. {$extra_prop_prompt}";
  5548. }
  5549. $systemPrompt = $is_single
  5550. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5551. 强制要求:
  5552. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5553. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5554. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5555. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5556. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5557. 普通要求:
  5558. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5559. $role_demo
  5560. $scene_demo
  5561. $prop_demo
  5562. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5563. 5.1片段分割逻辑(优先级从高到低):
  5564. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5565. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5566. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5567. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5568. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5569. - 片段数量格式为: 片段数量:8
  5570. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5571. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5572. 5.3分镜结构:每个分镜包含以下字段:
  5573. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5574. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5575. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5576. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5577. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5578. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5579. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5580. - 运镜:场景+画面描述+运镜
  5581. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5582. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5583. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5584. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5585. 6.{$mappedArtStyle_prompt}\n\n
  5586. 示例如下:\n
  5587. ###剧本名:西昆仑
  5588. ###故事梗概
  5589. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5590. ###剧本亮点
  5591. 亮点1:绝境奇药,生死一线
  5592. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5593. 亮点2:结拜兄妹,化解尴尬
  5594. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5595. 亮点3:纤发夺命,情愫暗涌
  5596. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5597. ###人物关系
  5598. 阿雪与梁萧之间存在兄妹之情。
  5599. ###核心矛盾
  5600. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5601. ###主体列表
  5602. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5603. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5604. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5605. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5606. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5607. 全景,正面拍摄,青年女性,亚洲人。
  5608. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5609. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5610. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5611. ###美术风格
  5612. 基础画风风格词:厚涂古风
  5613. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5614. ###场景列表
  5615. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5616. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5617. 无人物。}
  5618. ###分段剧本
  5619. 片段数量:8
  5620. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5621. ##片段1
  5622. 时长:12s
  5623. 分镜1
  5624. 出场角色:刀疤脸
  5625. 场景:边境小镇街道
  5626. 出场道具:酒杯-高脚杯
  5627. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5628. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5629. 配音台词:
  5630. 背景音效:
  5631. 分镜2
  5632. 出场角色:刀疤脸
  5633. 场景:悦来酒馆
  5634. 出场道具:酒杯-高脚杯
  5635. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5636. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5637. 配音台词:
  5638. 背景音效:
  5639. 分镜3
  5640. 出场角色:刀疤脸
  5641. 场景:悦来酒馆
  5642. 出场道具:酒杯-高脚杯
  5643. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5644. 运镜:从中景推向令牌特写。
  5645. 配音台词:
  5646. 背景音效:
  5647. 分镜4
  5648. 出场角色:刀疤脸
  5649. 场景:悦来酒馆
  5650. 出场道具:酒杯-高脚杯
  5651. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5652. 运镜:极速推向酒水溅起的瞬间。
  5653. 配音台词:
  5654. 背景音效:
  5655. 分镜5
  5656. 出场角色:刀疤脸
  5657. 场景:悦来酒馆
  5658. 出场道具:酒杯-高脚杯
  5659. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5660. 运镜:固定机位,利用倾斜构图制造压迫感。
  5661. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5662. 背景音效:
  5663. \n\n"
  5664. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5665. 强制要求:\n
  5666. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5667. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5668. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5669. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5670. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5671. 普通要求:\n
  5672. 1.剧本名(必须生成)必须与文档内容高度相关
  5673. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5674. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5675. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5676. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5677. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5678. {$extra_role_prompt}
  5679. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5680. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5681. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5682. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5683. {$extra_scene_prompt}
  5684. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5685. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5686. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5687. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5688. {$extra_prop_prompt}
  5689. 5.{$mappedArtStyle_prompt}\n\n
  5690. 示例如下:\n
  5691. ###剧本名:西昆仑
  5692. ###故事梗概
  5693. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5694. ###剧本亮点
  5695. 亮点1:绝境奇药,生死一线
  5696. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5697. 亮点2:结拜兄妹,化解尴尬
  5698. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5699. 亮点3:纤发夺命,情愫暗涌
  5700. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5701. ###人物关系
  5702. 阿雪与梁萧之间存在兄妹之情。
  5703. ###核心矛盾
  5704. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5705. ###主体列表
  5706. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5707. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5708. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5709. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5710. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5711. 全景,正面拍摄,青年女性,亚洲人。
  5712. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5713. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5714. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5715. ###美术风格
  5716. 基础画风风格词:厚涂古风
  5717. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5718. ###场景列表
  5719. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5720. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5721. 无人物。}
  5722. ###道具列表
  5723. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5724. // 构建消息
  5725. $messages = [
  5726. [
  5727. 'role' => 'system',
  5728. 'content' => $systemPrompt
  5729. ],
  5730. [
  5731. 'role' => 'user',
  5732. 'content' => "以下是文档内容:
  5733. {$content}
  5734. 用户问题:
  5735. {$question}"
  5736. ]
  5737. ];
  5738. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5739. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5740. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5741. if ($model === 'deepseek-chat') {
  5742. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5743. $model = 'deepseek-v4-flash';
  5744. $thinkingMode = 'disabled';
  5745. } elseif ($model === 'deepseek-reasoner') {
  5746. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5747. $model = 'deepseek-v4-flash';
  5748. $thinkingMode = 'enabled';
  5749. }
  5750. $post_data = [
  5751. 'model' => $model,
  5752. 'messages' => $messages,
  5753. // 'max_tokens' => 8192,
  5754. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5755. 'frequency_penalty' => 0,
  5756. 'presence_penalty' => 0,
  5757. 'response_format' => ['type' => 'text'],
  5758. 'thinking' => ['type'=>$thinkingMode],
  5759. 'stream' => true // 启用流式输出
  5760. ];
  5761. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5762. // 根据模型类型选择调用方法
  5763. $fullContent = '';
  5764. $fullReasoningContent = '';
  5765. $usage = [];
  5766. try {
  5767. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5768. // DeepSeek 官方模型使用 DeepSeek API
  5769. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5770. } else if (in_array($model, $this->gpt_text_models)) {
  5771. // GPT-5.4 模型使用 TokenRouter API
  5772. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5773. } else {
  5774. // 其他模型使用火山引擎API
  5775. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5776. }
  5777. // 验证返回值类型
  5778. if (!is_iterable($streamGenerator)) {
  5779. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5780. dLog('deepseek')->error('addChat流式生成器无效', [
  5781. 'generator_type' => $errorType,
  5782. 'model' => $model,
  5783. 'anime_id' => $anime_id
  5784. ]);
  5785. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5786. 'type' => $errorType,
  5787. 'model' => $model
  5788. ]);
  5789. yield [
  5790. 'type' => 'error',
  5791. 'script' => [],
  5792. 'episode' => [],
  5793. 'answer' => '',
  5794. 'reasoning' => '',
  5795. 'usage' => [],
  5796. 'error' => '接口返回数据异常,请重新请求'
  5797. ];
  5798. return;
  5799. }
  5800. // 处理流式输出
  5801. foreach ($streamGenerator as $chunk) {
  5802. if (isset($chunk['type'])) {
  5803. if ($chunk['type'] === 'done') {
  5804. // 最终结果
  5805. $fullContent = $chunk['full_content'];
  5806. $fullReasoningContent = $chunk['full_reasoning'];
  5807. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5808. } else {
  5809. // 逐块yield数据
  5810. yield $chunk;
  5811. }
  5812. }
  5813. }
  5814. } catch (\Exception $e) {
  5815. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5816. 'model' => $model,
  5817. 'anime_id' => $anime_id,
  5818. 'trace' => $e->getTraceAsString()
  5819. ]);
  5820. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5821. 'error' => $e->getMessage(),
  5822. 'model' => $model
  5823. ]);
  5824. yield [
  5825. 'type' => 'error',
  5826. 'script' => [],
  5827. 'episode' => [],
  5828. 'answer' => '',
  5829. 'reasoning' => '',
  5830. 'usage' => [],
  5831. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5832. ];
  5833. return;
  5834. }
  5835. dLog('deepseek')->info('完整内容: '.$fullContent);
  5836. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5837. // 处理完整内容并返回最终结果
  5838. $script_arr = [];
  5839. if ($fullContent) {
  5840. $script_arr = handleScriptContentForAce($fullContent);
  5841. dLog('deepseek')->info('解析内容', $script_arr);
  5842. logDB('deepseek', 'info', '解析内容', $script_arr);
  5843. }
  5844. if (empty($script_arr['roles'])) {
  5845. // 未生成剧本相关内容,保存对话记录并返回提示
  5846. dLog('deepseek')->info('未生成剧本相关的内容');
  5847. try {
  5848. DB::beginTransaction();
  5849. $now = date('Y-m-d H:i:s');
  5850. // 保存对话记录
  5851. $records = [
  5852. [
  5853. 'uid' => $uid,
  5854. 'anime_id' => $anime_id,
  5855. 'sequence' => 0,
  5856. 'role' => 'user',
  5857. 'content' => $prompt,
  5858. 'created_at' => $now,
  5859. 'updated_at' => $now
  5860. ],
  5861. [
  5862. 'uid' => $uid,
  5863. 'anime_id' => $anime_id,
  5864. 'sequence' => 0,
  5865. 'role' => 'assistant',
  5866. // 'content' => $fullContent,
  5867. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5868. 'created_at' => $now,
  5869. 'updated_at' => $now
  5870. ]
  5871. ];
  5872. DB::table('mp_anime_records')->insert($records);
  5873. DB::commit();
  5874. } catch (\Exception $e) {
  5875. DB::rollBack();
  5876. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5877. }
  5878. yield [
  5879. 'type' => 'done',
  5880. 'script' => [],
  5881. 'episode' => [],
  5882. 'answer' => $fullContent,
  5883. 'reasoning' => $fullReasoningContent,
  5884. 'usage' => $usage,
  5885. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5886. ];
  5887. return;
  5888. }
  5889. // 如果需要生成原文内容,从script_arr中提取
  5890. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5891. $content = $script_arr['content'];
  5892. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5893. if (!$content) {
  5894. yield [
  5895. 'type' => 'done',
  5896. 'script' => [],
  5897. 'episode' => [],
  5898. 'answer' => $fullContent,
  5899. 'reasoning' => $fullReasoningContent,
  5900. 'usage' => $usage,
  5901. 'error' => '未生成剧本内容,请调整提示词再试'
  5902. ];
  5903. return;
  5904. }
  5905. }
  5906. // 替换美术风格
  5907. if ($mappedArtStyle !== '') {
  5908. $script_arr['art_style'] = $mappedArtStyle;
  5909. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5910. }
  5911. // 新建动漫
  5912. if ($user_anime_name == '新剧本策划') {
  5913. $anime_name = getProp($script_arr, 'script_name');
  5914. // if (!$anime_name) {
  5915. // // 未识别到剧本名,保存对话记录并返回提示
  5916. // dLog('deepseek')->info('未能识别到剧本名称');
  5917. // try {
  5918. // DB::beginTransaction();
  5919. // $now = date('Y-m-d H:i:s');
  5920. // // 保存对话记录
  5921. // $records = [
  5922. // [
  5923. // 'uid' => $uid,
  5924. // 'anime_id' => $anime_id,
  5925. // 'sequence' => 0,
  5926. // 'role' => 'user',
  5927. // 'content' => $prompt,
  5928. // 'created_at' => $now,
  5929. // 'updated_at' => $now
  5930. // ],
  5931. // [
  5932. // 'uid' => $uid,
  5933. // 'anime_id' => $anime_id,
  5934. // 'sequence' => 0,
  5935. // 'role' => 'assistant',
  5936. // 'content' => '未能生成剧本名称,请重试',
  5937. // 'created_at' => $now,
  5938. // 'updated_at' => $now
  5939. // ]
  5940. // ];
  5941. // DB::table('mp_anime_records')->insert($records);
  5942. // DB::commit();
  5943. // } catch (\Exception $e) {
  5944. // DB::rollBack();
  5945. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5946. // }
  5947. // yield [
  5948. // 'type' => 'done',
  5949. // 'script' => [],
  5950. // 'episode' => [],
  5951. // 'answer' => $fullContent,
  5952. // 'reasoning' => $fullReasoningContent,
  5953. // 'usage' => $usage,
  5954. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5955. // ];
  5956. // return;
  5957. // }
  5958. // 确认对话名称唯一性
  5959. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5960. $anime_name = $anime_name . '_' . date('YmdHis');
  5961. }
  5962. }else {
  5963. $anime_name = $user_anime_name;
  5964. }
  5965. $table_data = [
  5966. 'user_id' => $uid,
  5967. 'anime_name' => $anime_name,
  5968. 'model' => $model,
  5969. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5970. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5971. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5972. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5973. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5974. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5975. 'art_style_type' => $input_art_style,
  5976. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5977. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  5978. 'status' => '解析完成',
  5979. 'content' => $content,
  5980. 'is_multi' => $is_multi,
  5981. 'ace_mode' => $ace_mode,
  5982. 'generate_status' => '待执行',
  5983. 'updated_at' => date('Y-m-d H:i:s')
  5984. ];
  5985. if ($table_data['content']) {
  5986. $chapters = splitContent($table_data['content']);
  5987. $chapter_count = count($chapters);
  5988. if ($chapter_count > 0) {
  5989. $table_data['start_episode_sequence'] = 1;
  5990. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5991. }
  5992. }
  5993. if ($extra_products) {
  5994. $table_data['extra_products'] = json_encode($extra_products, 256);
  5995. }
  5996. // 如果有剧本ID则进行绑定
  5997. if ($script_id) {
  5998. $table_data['script_id'] = $script_id;
  5999. }
  6000. $single_episode = [];
  6001. try {
  6002. DB::beginTransaction();
  6003. $now = date('Y-m-d H:i:s');
  6004. // 更新动漫大纲
  6005. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6006. if (!$boolen) {
  6007. dLog('deepseek')->info('动漫保存失败', $table_data);
  6008. Utils::throwError('20003:动漫保存失败');
  6009. }
  6010. // 保存对话记录
  6011. $records = [
  6012. [
  6013. 'uid' => $uid,
  6014. 'anime_id' => $anime_id,
  6015. 'sequence' => 0,
  6016. 'role' => 'user',
  6017. 'content' => $prompt,
  6018. 'created_at' => date('Y-m-d H:i:s'),
  6019. 'updated_at' => date('Y-m-d H:i:s')
  6020. ],
  6021. [
  6022. 'uid' => $uid,
  6023. 'anime_id' => $anime_id,
  6024. 'sequence' => 0,
  6025. 'role' => 'assistant',
  6026. 'content' => $fullContent,
  6027. 'created_at' => date('Y-m-d H:i:s'),
  6028. 'updated_at' => date('Y-m-d H:i:s')
  6029. ]
  6030. ];
  6031. // 保存对话记录
  6032. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6033. if (!$boolen3) {
  6034. Utils::throwError('20003:对话记录保存失败');
  6035. }
  6036. if ($is_single) {
  6037. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6038. if (empty($episode_arr['acts'])) {
  6039. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6040. }
  6041. $saveResult = $this->saveEpisodeVersionData(
  6042. $anime_id,
  6043. 1,
  6044. $episode_arr,
  6045. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6046. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6047. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6048. null,
  6049. null,
  6050. false,
  6051. $content,
  6052. $now,
  6053. $ref_products
  6054. );
  6055. $single_episode = $saveResult['episode'];
  6056. $episode_id = $saveResult['episode_id'];
  6057. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6058. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6059. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6060. 'props' => json_encode($saveResult['merged_props'], 256),
  6061. 'updated_at' => $now
  6062. ]);
  6063. if ($boolen5 === false) {
  6064. Utils::throwError('20003:单剧集主表资源同步失败');
  6065. }
  6066. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6067. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6068. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6069. $episode_record_content = '确认分镜大纲';
  6070. if ($content !== '') {
  6071. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6072. }
  6073. $episode_records = [
  6074. [
  6075. 'uid' => $uid,
  6076. 'anime_id' => $anime_id,
  6077. 'role' => 'user',
  6078. 'content' => $episode_record_content,
  6079. 'sequence' => 1,
  6080. 'episode_id' => $episode_id,
  6081. 'created_at' => $now,
  6082. 'updated_at' => $now
  6083. ],
  6084. [
  6085. 'uid' => $uid,
  6086. 'anime_id' => $anime_id,
  6087. 'role' => 'assistant',
  6088. 'content' => $fullContent,
  6089. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6090. 'sequence' => 1,
  6091. 'episode_id' => $episode_id,
  6092. 'created_at' => $now,
  6093. 'updated_at' => $now
  6094. ]
  6095. ];
  6096. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6097. if (!$boolen4) {
  6098. Utils::throwError('20003:单剧集分镜记录保存失败');
  6099. }
  6100. }
  6101. }catch (\Exception $e) {
  6102. DB::rollBack();
  6103. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6104. yield [
  6105. 'type' => 'done',
  6106. 'answer' => $fullContent,
  6107. 'reasoning' => $fullReasoningContent,
  6108. 'usage' => $usage,
  6109. 'error' => $e->getMessage(),
  6110. ];
  6111. return;
  6112. }
  6113. DB::commit();
  6114. dLog('deepseek')->info('保存完毕');
  6115. if ($is_single && !empty($single_episode)) {
  6116. // $this->batchSetGlobalRoleImg([
  6117. // 'anime_id' => $anime_id,
  6118. // ]);
  6119. // $this->batchSetGlobalSceneImg([
  6120. // 'anime_id' => $anime_id,
  6121. // ]);
  6122. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6123. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6124. }
  6125. $table_data['anime_id'] = $anime_id;
  6126. $table_data['roles'] = json_decode($table_data['roles'], true);
  6127. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6128. // $table_data['episodes'] = $script_arr['episodes'];
  6129. unset($table_data['created_at']);
  6130. unset($table_data['updated_at']);
  6131. unset($table_data['status']);
  6132. dLog('deepseek')->info('开始返回');
  6133. yield [
  6134. 'type' => 'done',
  6135. 'script' => $table_data,
  6136. 'episode' => $single_episode,
  6137. 'answer' => $fullContent,
  6138. 'reasoning' => $fullReasoningContent,
  6139. 'usage' => $usage
  6140. ];
  6141. }
  6142. public function reGenerateAnimeForAce($data) {
  6143. $uid = Site::getUid();
  6144. $file = getProp($data, 'file');
  6145. $content = getProp($data, 'content', '');
  6146. $bid = getProp($data, 'bid', 0);
  6147. $script_id = getProp($data, 'script_id', 0);
  6148. $anime_id = getProp($data, 'anime_id');
  6149. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6150. if (!$anime) {
  6151. Utils::throwError('20003:该对话不存在');
  6152. }
  6153. $is_multi = getProp($anime, 'is_multi', 1);
  6154. $is_single = (int)$is_multi !== 1;
  6155. $extra_products = getProp($data, 'products', []);
  6156. if (!$extra_products) {
  6157. $extra_products = getProp($anime, 'extra_products');
  6158. if ($extra_products) {
  6159. $extra_products = json_decode($extra_products, true);
  6160. }else {
  6161. $extra_products = [];
  6162. }
  6163. }else {
  6164. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6165. }
  6166. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6167. $anime_script_id = getProp($anime, 'script_id');
  6168. if ($anime_script_id && $is_single) {
  6169. $cpid = Site::getCpid();
  6170. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6171. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6172. ->where('mapping.script_id', $anime_script_id)
  6173. ->where('product.cpid', $cpid)
  6174. ->where('product.is_deleted', 0);
  6175. $mappings = $script_products_mappings->select(
  6176. 'mapping.product_id',
  6177. 'mapping.episode_number',
  6178. 'product.product_name',
  6179. 'product.type',
  6180. 'product.product',
  6181. 'product.pic_prompt',
  6182. 'product.url',
  6183. 'product.pic_task_id',
  6184. 'product.pic_task_status',
  6185. 'product.three_view_image_url'
  6186. )
  6187. ->get();
  6188. // 按 product_id 分组,合并 episode_number
  6189. $productMap = [];
  6190. foreach ($mappings as $item) {
  6191. $product_id = $item->product_id;
  6192. $product_name = $item->product_name;
  6193. // 处理product_name两边的符号
  6194. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6195. if (!isset($productMap[$product_id])) {
  6196. $productMap[$product_id] = [
  6197. 'product_id' => $product_id,
  6198. 'product_name' => $product_name,
  6199. 'type' => (int)$item->type,
  6200. 'product' => (int)$item->product,
  6201. 'pic_prompt' => $item->pic_prompt,
  6202. 'url' => $item->url,
  6203. 'pic_task_id' => $item->pic_task_id,
  6204. 'pic_task_status' => $item->pic_task_status,
  6205. 'episode_numbers' => [],
  6206. ];
  6207. }
  6208. // 添加 episode_number(去重)
  6209. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6210. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6211. }
  6212. }
  6213. // 将查询到的剧本资产合并到extra_products中
  6214. // 先构建extra_products的索引(以product_id为key,用于去重)
  6215. $extraProductsMap = [];
  6216. foreach ($extra_products as $item) {
  6217. $key = getProp($item, 'product_id');
  6218. if ($key) {
  6219. $extraProductsMap[$key] = $item;
  6220. }
  6221. }
  6222. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6223. foreach ($productMap as $product) {
  6224. $product_id = $product['product_id'];
  6225. // 如果不存在则添加(不带episode_number信息)
  6226. if (!isset($extraProductsMap[$product_id])) {
  6227. $extraProductsMap[$product_id] = [
  6228. 'product_id' => $product['product_id'],
  6229. 'product_name' => $product['product_name'],
  6230. 'type' => $product['type'],
  6231. 'product' => $product['product'],
  6232. 'pic_prompt' => $product['pic_prompt'],
  6233. 'url' => $product['url'],
  6234. 'pic_task_id' => $product['pic_task_id'],
  6235. 'pic_task_status' => $product['pic_task_status'],
  6236. ];
  6237. }
  6238. }
  6239. // 重新赋值给extra_products
  6240. $extra_products = array_values($extraProductsMap);
  6241. }
  6242. $user_anime_name = getProp($anime, 'anime_name');
  6243. $prompt = getProp($data, 'prompt');
  6244. // 处理提示词
  6245. if ($prompt && $extra_products) {
  6246. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6247. foreach($extra_products as $item) {
  6248. $product_name = getProp($item, 'product_name');
  6249. if ($product_name) {
  6250. // 替换 {product_name} 为 product_name
  6251. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6252. }
  6253. }
  6254. }
  6255. // 处理文本模型
  6256. $model = getProp($data, 'model');
  6257. if (!$model) {
  6258. // 用户没有输入,从anime表获取
  6259. $model = getProp($anime, 'model');
  6260. if (!$model) {
  6261. // anime表也没有,使用默认值
  6262. $model = 'deepseek-v4-pro';
  6263. }
  6264. }
  6265. // 验证模型是否在可用模型表中
  6266. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6267. $model = 'deepseek-v4-pro';
  6268. }
  6269. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6270. if ($is_single) {
  6271. $episode_exists = DB::table('mp_anime_episodes')
  6272. ->where('anime_id', $anime_id)
  6273. ->where('sequence', 1)
  6274. ->exists();
  6275. if ($episode_exists) {
  6276. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6277. }
  6278. }
  6279. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6280. if ($prompt) {
  6281. $question .= "本次修改要求如下:\n{$prompt}";
  6282. }
  6283. // 提取文件内容
  6284. if ($file) {
  6285. $content = $this->extractFileContent($file);
  6286. if (!$content) {
  6287. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6288. }
  6289. } elseif ($script_id) {
  6290. $content = $this->getContentByScriptId($script_id);
  6291. if (!$content) {
  6292. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6293. }
  6294. } elseif ($bid) {
  6295. $content = $this->getContentByBid($bid);
  6296. if (!$content) {
  6297. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6298. }
  6299. } elseif ($content) {
  6300. $content = filterContent($content);
  6301. }else {
  6302. $content = filterContent(getProp($anime, 'content'));
  6303. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6304. $need_generate_content = true;
  6305. }
  6306. }
  6307. // 判断是否需要生成原文内容
  6308. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6309. // 如果需要生成原文内容,添加额外的要求
  6310. $content_generation_requirement = $need_generate_content
  6311. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6312. : "";
  6313. // 美术风格
  6314. $input_art_style = getProp($data, 'art_style');
  6315. if (!$input_art_style) {
  6316. $mappedArtStyle = getProp($anime, 'art_style');
  6317. }else {
  6318. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6319. }
  6320. if (!$mappedArtStyle) {
  6321. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6322. }else {
  6323. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6324. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6325. }else {
  6326. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6327. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6328. }
  6329. }
  6330. // 构建主体、场景和道具提示词
  6331. $extra_role_prompt = "\n";
  6332. $extra_scene_prompt = "\n";
  6333. $extra_prop_prompt = "\n";
  6334. $ref_products = []; // 参考资产
  6335. if ($extra_products) {
  6336. foreach($extra_products as $item) {
  6337. $product = getProp($item, 'product');
  6338. $product_name = getProp($item, 'product_name');
  6339. if ($product_name == '旁白') continue;
  6340. $ref_products[$product_name] = $item;
  6341. $pic_prompt = getProp($item, 'pic_prompt');
  6342. if ((int)$product === 1) {
  6343. // 拼接角色信息
  6344. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6345. } elseif ((int)$product === 2) {
  6346. // 拼接场景信息
  6347. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6348. } elseif ((int)$product === 3) {
  6349. // 拼接道具信息
  6350. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6351. }
  6352. }
  6353. // 优化提示词,融入剧本
  6354. if (!empty(trim($extra_role_prompt))) {
  6355. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6356. }
  6357. if (!empty(trim($extra_scene_prompt))) {
  6358. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6359. }
  6360. if (!empty(trim($extra_prop_prompt))) {
  6361. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6362. }
  6363. }
  6364. if ($anime_script_id && $is_single) {
  6365. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6366. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6367. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6368. }else {
  6369. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6370. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6371. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6372. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6373. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6374. {$extra_role_prompt}";
  6375. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6376. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6377. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6378. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6379. {$extra_scene_prompt}";
  6380. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6381. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6382. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6383. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6384. {$extra_prop_prompt}";
  6385. }
  6386. $system_message = ['role'=>'system', 'content'=>$is_single
  6387. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6388. 强制要求:
  6389. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6390. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6391. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6392. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6393. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6394. 普通要求:
  6395. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6396. $role_demo
  6397. $scene_demo
  6398. $prop_demo
  6399. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6400. 5.1片段分割逻辑(优先级从高到低):
  6401. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6402. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6403. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6404. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6405. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6406. - 片段数量格式为: 片段数量:8
  6407. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6408. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6409. 5.3分镜结构:每个分镜包含以下字段:
  6410. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6411. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6412. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6413. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6414. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6415. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6416. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6417. - 运镜:场景+画面描述+运镜
  6418. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6419. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6420. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6421. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6422. 6.{$mappedArtStyle_prompt}\n\n
  6423. 示例如下:\n
  6424. ###剧本名:西昆仑
  6425. ###故事梗概
  6426. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6427. ###剧本亮点
  6428. 亮点1:绝境奇药,生死一线
  6429. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6430. 亮点2:结拜兄妹,化解尴尬
  6431. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6432. 亮点3:纤发夺命,情愫暗涌
  6433. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6434. ###人物关系
  6435. 阿雪与梁萧之间存在兄妹之情。
  6436. ###核心矛盾
  6437. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6438. ###主体列表
  6439. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6440. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6441. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6442. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6443. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6444. 全景,正面拍摄,青年女性,亚洲人。
  6445. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6446. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6447. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6448. ###美术风格
  6449. 基础画风风格词:厚涂古风
  6450. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6451. ###场景列表
  6452. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6453. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6454. 无人物。}
  6455. ###分段剧本
  6456. 片段数量:8
  6457. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6458. ##片段1
  6459. 时长:12s
  6460. 分镜1
  6461. 出场角色:刀疤脸
  6462. 场景:边境小镇街道
  6463. 出场道具:酒杯-高脚杯
  6464. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6465. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6466. 配音台词:
  6467. 背景音效:
  6468. 分镜2
  6469. 出场角色:刀疤脸
  6470. 场景:悦来酒馆
  6471. 出场道具:酒杯-高脚杯
  6472. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6473. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6474. 配音台词:
  6475. 背景音效:
  6476. 分镜3
  6477. 出场角色:刀疤脸
  6478. 场景:悦来酒馆
  6479. 出场道具:酒杯-高脚杯
  6480. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6481. 运镜:从中景推向令牌特写。
  6482. 配音台词:
  6483. 背景音效:
  6484. 分镜4
  6485. 出场角色:刀疤脸
  6486. 场景:悦来酒馆
  6487. 出场道具:酒杯-高脚杯
  6488. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6489. 运镜:极速推向酒水溅起的瞬间。
  6490. 配音台词:
  6491. 背景音效:
  6492. 分镜5
  6493. 出场角色:刀疤脸
  6494. 场景:悦来酒馆
  6495. 出场道具:酒杯-高脚杯
  6496. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6497. 运镜:固定机位,利用倾斜构图制造压迫感。
  6498. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6499. 背景音效:
  6500. \n\n"
  6501. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6502. 强制要求:\n
  6503. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6504. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6505. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6506. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6507. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6508. 普通要求:\n
  6509. 1.剧本名(必须生成)必须与文档内容高度相关
  6510. $role_demo
  6511. $scene_demo
  6512. $prop_demo
  6513. 5.{$mappedArtStyle_prompt}\n\n
  6514. 示例如下:\n
  6515. ###剧本名:西昆仑
  6516. ###故事梗概
  6517. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6518. ###剧本亮点
  6519. 亮点1:绝境奇药,生死一线
  6520. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6521. 亮点2:结拜兄妹,化解尴尬
  6522. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6523. 亮点3:纤发夺命,情愫暗涌
  6524. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6525. ###人物关系
  6526. 阿雪与梁萧之间存在兄妹之情。
  6527. ###核心矛盾
  6528. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6529. ###主体列表
  6530. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6531. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6532. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6533. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6534. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6535. 全景,正面拍摄,青年女性,亚洲人。
  6536. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6537. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6538. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6539. ###美术风格
  6540. 基础画风风格词:厚涂古风
  6541. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6542. ###场景列表
  6543. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6544. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6545. 无人物。}
  6546. ###道具列表
  6547. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6548. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6549. $episode_count = $this->extractEpisodeNumber($prompt);
  6550. if ((int)getProp($anime, 'is_multi') !== 1) {
  6551. yield [
  6552. 'type' => 'done',
  6553. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6554. 'reasoning' => '',
  6555. 'usage' => []
  6556. ];
  6557. return;
  6558. }
  6559. if ($episode_count) {
  6560. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6561. $system_message = [
  6562. 'role' => 'system',
  6563. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6564. 强制要求:\n
  6565. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6566. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6567. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6568. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6569. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6570. 普通要求:\n
  6571. 1.<故事梗概>控制在200-300字左右
  6572. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6573. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6574. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6575. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6576. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6577. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6578. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6579. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6580. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6581. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6582. 示例如下:\n
  6583. ###剧本名:西昆仑
  6584. ###故事梗概
  6585. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6586. ###剧本亮点
  6587. 亮点1:绝境奇药,生死一线
  6588. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6589. 亮点2:结拜兄妹,化解尴尬
  6590. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6591. 亮点3:纤发夺命,情愫暗涌
  6592. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6593. ###人物关系
  6594. 阿雪与梁萧之间存在兄妹之情。
  6595. ###核心矛盾
  6596. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6597. ###主体列表
  6598. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6599. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6600. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6601. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6602. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6603. 全景,正面拍摄,青年女性,亚洲人。
  6604. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6605. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6606. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6607. ###美术风格
  6608. 基础画风风格词:厚涂古风
  6609. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6610. ###场景列表
  6611. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6612. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6613. 无人物。}
  6614. ###分集详细内容
  6615. ##第1章 重生
  6616. 我重生了。
  6617. 源于一个男人偏执的暗恋。
  6618. ##第2章 相救
  6619. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6620. 我眼睛扫向站在锅炉后的卞大伟。"
  6621. ];
  6622. // 构建消息
  6623. $messages = [
  6624. $system_message,
  6625. [
  6626. 'role' => 'user',
  6627. 'content' => "以下是文档内容:
  6628. {$content}
  6629. 用户问题:
  6630. {$question}"
  6631. ]
  6632. ];
  6633. }else {
  6634. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6635. // 构建消息
  6636. $messages = [
  6637. $system_message,
  6638. [
  6639. 'role' => 'user',
  6640. 'content' => "以下是文档内容:
  6641. {$content}
  6642. 用户问题:
  6643. {$question}"
  6644. ]
  6645. ];
  6646. }else {
  6647. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6648. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6649. return (array)$value;
  6650. })->toArray();
  6651. array_unshift($messages, $system_message);
  6652. $messages[] = [
  6653. 'role' => 'user',
  6654. 'content' => $prompt
  6655. ];
  6656. }
  6657. }
  6658. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6659. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6660. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6661. if ($model === 'deepseek-chat') {
  6662. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6663. $model = 'deepseek-v4-flash';
  6664. $thinkingMode = 'disabled';
  6665. } elseif ($model === 'deepseek-reasoner') {
  6666. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6667. $model = 'deepseek-v4-flash';
  6668. $thinkingMode = 'enabled';
  6669. }
  6670. $post_data = [
  6671. 'model' => $model,
  6672. 'messages' => $messages,
  6673. // 'max_tokens' => 8192,
  6674. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6675. 'frequency_penalty' => 0,
  6676. 'presence_penalty' => 0,
  6677. 'response_format' => ['type' => 'text'],
  6678. 'thinking' => ['type' => $thinkingMode],
  6679. 'stream' => true // 启用流式输出
  6680. ];
  6681. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6682. // 根据模型类型选择调用方法
  6683. $fullContent = '';
  6684. $fullReasoningContent = '';
  6685. $usage = [];
  6686. // dd($post_data);
  6687. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6688. try {
  6689. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6690. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6691. } else if (in_array($model, $this->gpt_text_models)) {
  6692. // GPT-5.4 模型使用 TokenRouter API
  6693. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6694. } else {
  6695. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6696. }
  6697. // 验证返回值类型
  6698. if (!is_iterable($streamGenerator)) {
  6699. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6700. dLog('deepseek')->error('方法名流式生成器无效', [
  6701. 'generator_type' => $errorType,
  6702. 'model' => $model,
  6703. // 添加其他上下文信息
  6704. ]);
  6705. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6706. 'type' => $errorType,
  6707. 'model' => $model
  6708. ]);
  6709. yield [
  6710. 'type' => 'error',
  6711. // 根据方法返回相应的空数据结构
  6712. 'answer' => '',
  6713. 'reasoning' => '',
  6714. 'usage' => [],
  6715. 'error' => '接口返回数据异常,请重新请求'
  6716. ];
  6717. return;
  6718. }
  6719. // 处理流式输出
  6720. foreach ($streamGenerator as $chunk) {
  6721. if (isset($chunk['type'])) {
  6722. if ($chunk['type'] === 'done') {
  6723. $fullContent = $chunk['full_content'];
  6724. $fullReasoningContent = $chunk['full_reasoning'];
  6725. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6726. } else {
  6727. yield $chunk;
  6728. }
  6729. }
  6730. }
  6731. } catch (\Exception $e) {
  6732. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6733. 'model' => $model,
  6734. 'trace' => $e->getTraceAsString()
  6735. ]);
  6736. logDB('deepseek', 'error', '方法名流式处理失败', [
  6737. 'error' => $e->getMessage(),
  6738. 'model' => $model
  6739. ]);
  6740. yield [
  6741. 'type' => 'error',
  6742. // 根据方法返回相应的空数据结构
  6743. 'answer' => '',
  6744. 'reasoning' => '',
  6745. 'usage' => [],
  6746. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6747. ];
  6748. return;
  6749. }
  6750. dLog('deepseek')->info('完整内容: '.$fullContent);
  6751. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6752. // 处理完整内容并返回最终结果
  6753. $script_arr = [];
  6754. if ($fullContent) {
  6755. $script_arr = handleScriptContentForAce($fullContent);
  6756. dLog('deepseek')->info('解析内容', $script_arr);
  6757. logDB('deepseek', 'info', '解析内容', $script_arr);
  6758. }
  6759. if (empty($script_arr['roles'])) {
  6760. // 未生成剧本相关内容,保存对话记录并返回提示
  6761. dLog('deepseek')->info('未生成剧本相关的内容');
  6762. try {
  6763. $now = date('Y-m-d H:i:s');
  6764. // 保存对话记录
  6765. $records = [
  6766. [
  6767. 'uid' => $uid,
  6768. 'anime_id' => $anime_id,
  6769. 'sequence' => 0,
  6770. 'role' => 'user',
  6771. 'content' => $prompt,
  6772. 'created_at' => $now,
  6773. 'updated_at' => $now
  6774. ],
  6775. [
  6776. 'uid' => $uid,
  6777. 'anime_id' => $anime_id,
  6778. 'sequence' => 0,
  6779. 'role' => 'assistant',
  6780. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6781. 'created_at' => $now,
  6782. 'updated_at' => $now
  6783. ]
  6784. ];
  6785. DB::table('mp_anime_records')->insert($records);
  6786. } catch (\Exception $e) {
  6787. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6788. }
  6789. yield [
  6790. 'type' => 'done',
  6791. 'script' => [],
  6792. 'episode' => [],
  6793. 'answer' => $fullContent,
  6794. 'reasoning' => $fullReasoningContent,
  6795. 'usage' => $usage,
  6796. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6797. ];
  6798. return;
  6799. }
  6800. // 替换美术风格
  6801. if ($mappedArtStyle !== '') {
  6802. $script_arr['art_style'] = $mappedArtStyle;
  6803. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6804. }
  6805. if ($user_anime_name != '新剧本策划') {
  6806. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6807. // 确认对话名称唯一性
  6808. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6809. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6810. }
  6811. }else {
  6812. $anime_name = $user_anime_name;
  6813. }
  6814. $table_data = [
  6815. 'user_id' => $uid,
  6816. 'model' => $model,
  6817. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6818. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6819. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6820. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6821. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6822. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6823. 'art_style_type' => $input_art_style,
  6824. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6825. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6826. 'status' => '解析完成',
  6827. 'generate_status' => '待执行',
  6828. 'updated_at' => date('Y-m-d H:i:s')
  6829. ];
  6830. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6831. // 如果是修改集数,则将content内容更新(会改变原文)
  6832. if (isset($episode_count) && $episode_count > 0) {
  6833. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6834. $table_data['start_episode_sequence'] = 1;
  6835. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6836. }else {
  6837. // 如果需要生成原文内容,从script_arr中提取
  6838. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6839. $table_data['content'] = $script_arr['content'];
  6840. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6841. if (!$table_data['content']) {
  6842. yield [
  6843. 'type' => 'done',
  6844. 'script' => [],
  6845. 'episode' => [],
  6846. 'answer' => $fullContent,
  6847. 'reasoning' => $fullReasoningContent,
  6848. 'usage' => $usage,
  6849. 'error' => '未生成剧本内容,请调整提示词再试'
  6850. ];
  6851. return;
  6852. }
  6853. }
  6854. if (isset($table_data['content']) && $table_data['content']) {
  6855. $chapters = splitContent($table_data['content']);
  6856. $chapter_count = count($chapters);
  6857. if ($chapter_count > 0) {
  6858. $table_data['start_episode_sequence'] = 1;
  6859. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6860. }
  6861. }
  6862. }
  6863. if ($extra_products) {
  6864. $table_data['extra_products'] = json_encode($extra_products, 256);
  6865. }
  6866. $single_episode = [];
  6867. try {
  6868. DB::beginTransaction();
  6869. $now = date('Y-m-d H:i:s');
  6870. // 更新动漫大纲
  6871. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6872. if (!$boolen) {
  6873. dLog('deepseek')->info('对话修改失败', $table_data);
  6874. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6875. Utils::throwError('20003:对话修改失败');
  6876. }
  6877. // 保存对话记录
  6878. $records = [
  6879. [
  6880. 'uid' => $uid,
  6881. 'anime_id' => $anime_id,
  6882. 'sequence' => 0,
  6883. 'role' => 'user',
  6884. 'content' => $prompt,
  6885. 'created_at' => $now,
  6886. 'updated_at' => $now
  6887. ],
  6888. [
  6889. 'uid' => $uid,
  6890. 'anime_id' => $anime_id,
  6891. 'sequence' => 0,
  6892. 'role' => 'assistant',
  6893. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6894. 'content' => $fullContent,
  6895. 'created_at' => $now,
  6896. 'updated_at' => $now
  6897. ]
  6898. ];
  6899. // 保存对话记录
  6900. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6901. if (!$boolen3) {
  6902. Utils::throwError('20003:对话记录保存失败');
  6903. }
  6904. // 单剧集模式:生成并保存剧集信息
  6905. if ($is_single) {
  6906. $anime_name = getProp($anime, 'anime_name', '未命名');
  6907. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6908. if (empty($episode_arr['acts'])) {
  6909. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6910. }
  6911. $saveResult = $this->saveEpisodeVersionData(
  6912. $anime_id,
  6913. 1,
  6914. $episode_arr,
  6915. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6916. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6917. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6918. null,
  6919. null,
  6920. false,
  6921. $content,
  6922. $now,
  6923. $ref_products
  6924. );
  6925. $single_episode = $saveResult['episode'];
  6926. $episode_id = $saveResult['episode_id'];
  6927. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6928. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6929. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6930. 'props' => json_encode($saveResult['merged_props'], 256),
  6931. 'updated_at' => $now
  6932. ]);
  6933. if ($boolen5 === false) {
  6934. Utils::throwError('20003:单剧集主表资源同步失败');
  6935. }
  6936. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6937. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6938. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6939. $episode_record_content = '确认分镜大纲';
  6940. if ($content !== '') {
  6941. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6942. }
  6943. $episode_records = [
  6944. [
  6945. 'uid' => $uid,
  6946. 'anime_id' => $anime_id,
  6947. 'role' => 'user',
  6948. 'content' => $episode_record_content,
  6949. 'sequence' => 1,
  6950. 'episode_id' => $episode_id,
  6951. 'created_at' => $now,
  6952. 'updated_at' => $now
  6953. ],
  6954. [
  6955. 'uid' => $uid,
  6956. 'anime_id' => $anime_id,
  6957. 'role' => 'assistant',
  6958. 'content' => $fullContent,
  6959. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6960. 'sequence' => 1,
  6961. 'episode_id' => $episode_id,
  6962. 'created_at' => $now,
  6963. 'updated_at' => $now
  6964. ]
  6965. ];
  6966. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6967. if (!$boolen4) {
  6968. Utils::throwError('20003:单剧集分镜记录保存失败');
  6969. }
  6970. }
  6971. }catch (\Exception $e) {
  6972. DB::rollBack();
  6973. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6974. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6975. yield [
  6976. 'type' => 'done',
  6977. 'answer' => $fullContent,
  6978. 'reasoning' => $fullReasoningContent,
  6979. 'usage' => $usage,
  6980. 'error' => $e->getMessage(),
  6981. ];
  6982. return;
  6983. }
  6984. DB::commit();
  6985. dLog('deepseek')->info('保存完毕');
  6986. if ($is_single && !empty($single_episode)) {
  6987. // $this->batchSetGlobalRoleImg([
  6988. // 'anime_id' => $anime_id,
  6989. // ]);
  6990. // $this->batchSetGlobalSceneImg([
  6991. // 'anime_id' => $anime_id,
  6992. // ]);
  6993. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6994. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6995. }
  6996. $table_data['anime_id'] = $anime_id;
  6997. $table_data['roles'] = json_decode($table_data['roles'], true);
  6998. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6999. $table_data['props'] = json_decode($table_data['props'], true);
  7000. unset($table_data['updated_at']);
  7001. unset($table_data['status']);
  7002. yield [
  7003. 'type' => 'done',
  7004. 'script' => $table_data,
  7005. 'episode' => $single_episode,
  7006. 'answer' => $fullContent,
  7007. 'reasoning' => $fullReasoningContent,
  7008. 'usage' => $usage
  7009. ];
  7010. }
  7011. public function chatForAce($data) {
  7012. $uid = Site::getUid();
  7013. $anime_id = getProp($data, 'anime_id');
  7014. $file = getProp($data, 'file');
  7015. $content = getProp($data, 'content', '');
  7016. $bid = getProp($data, 'bid', 0);
  7017. $script_id = getProp($data, 'script_id', 0);
  7018. $episode_number = getProp($data, 'episode_number', 1);
  7019. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7020. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7021. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7022. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7023. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7024. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7025. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7026. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7027. $roles = is_array($roles) ? $roles : [];
  7028. $scenes = is_array($scenes) ? $scenes : [];
  7029. $extra_products = getProp($data, 'products', []);
  7030. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7031. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7032. $anime_script_id = getProp($anime, 'script_id');
  7033. if ($anime_script_id) {
  7034. $cpid = Site::getCpid();
  7035. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7036. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7037. ->where('mapping.script_id', $anime_script_id)
  7038. ->where('product.cpid', $cpid)
  7039. ->where('product.is_deleted', 0);
  7040. // 如果提供了 episode_number,则过滤指定集数
  7041. if ($episode_number !== null && $episode_number !== '') {
  7042. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7043. }
  7044. $mappings = $script_products_mappings->select(
  7045. 'mapping.product_id',
  7046. 'mapping.episode_number',
  7047. 'product.product_name',
  7048. 'product.type',
  7049. 'product.product',
  7050. 'product.pic_prompt',
  7051. 'product.url',
  7052. 'product.pic_task_id',
  7053. 'product.pic_task_status',
  7054. 'product.three_view_image_url'
  7055. )
  7056. ->get();
  7057. // 按 product_id 分组,合并 episode_number
  7058. $productMap = [];
  7059. foreach ($mappings as $item) {
  7060. $product_id = $item->product_id;
  7061. $product_name = $item->product_name;
  7062. // 处理product_name两边的符号
  7063. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7064. if (!isset($productMap[$product_id])) {
  7065. $productMap[$product_id] = [
  7066. 'product_id' => $product_id,
  7067. 'product_name' => $product_name,
  7068. 'type' => (int)$item->type,
  7069. 'product' => (int)$item->product,
  7070. 'pic_prompt' => $item->pic_prompt,
  7071. 'url' => $item->url,
  7072. 'pic_task_id' => $item->pic_task_id,
  7073. 'pic_task_status' => $item->pic_task_status,
  7074. 'episode_numbers' => [],
  7075. ];
  7076. }
  7077. // 添加 episode_number(去重)
  7078. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7079. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7080. }
  7081. }
  7082. // 将查询到的剧本资产合并到extra_products中
  7083. // 先构建extra_products的索引(以product_id+episode_number为key)
  7084. $extraProductsMap = [];
  7085. foreach ($extra_products as $item) {
  7086. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7087. $extraProductsMap[$key] = $item;
  7088. }
  7089. // 合并剧本资产(去重:product_id+episode_number)
  7090. foreach ($productMap as $product) {
  7091. foreach ($product['episode_numbers'] as $ep_num) {
  7092. $key = $product['product_id'] . '_' . $ep_num;
  7093. // 如果不存在则添加
  7094. if (!isset($extraProductsMap[$key])) {
  7095. $extraProductsMap[$key] = [
  7096. 'product_id' => $product['product_id'],
  7097. 'product_name' => $product['product_name'],
  7098. 'type' => $product['type'],
  7099. 'product' => $product['product'],
  7100. 'pic_prompt' => $product['pic_prompt'],
  7101. 'url' => $product['url'],
  7102. 'pic_task_id' => $product['pic_task_id'],
  7103. 'pic_task_status' => $product['pic_task_status'],
  7104. 'episode_number' => $ep_num,
  7105. ];
  7106. }
  7107. }
  7108. }
  7109. // 重新赋值给extra_products
  7110. $extra_products = array_values($extraProductsMap);
  7111. }
  7112. // 处理提示词
  7113. if ($prompt && $extra_products) {
  7114. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7115. foreach($extra_products as $item) {
  7116. $product_name = getProp($item, 'product_name');
  7117. if ($product_name) {
  7118. // 替换 {product_name} 为 product_name
  7119. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7120. }
  7121. }
  7122. }
  7123. // 获取最后一集序号
  7124. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7125. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7126. // 转换主体列表和场景列表的格式
  7127. // 获取参考主体或场景
  7128. if ((int)$episode_number === 1) {
  7129. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7130. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7131. }else {
  7132. $prev_episode_number = $episode_number - 1;
  7133. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7134. }
  7135. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7136. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7137. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7138. // 合并anime_products和extra_products(extra_products优先,去重)
  7139. $anime_products = getProp($anime, 'extra_products');
  7140. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7141. $ref_products = [];
  7142. foreach($anime_products as $item) {
  7143. $product_name = getProp($item, 'product_name');
  7144. $ref_products[$product_name] = $item;
  7145. }
  7146. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7147. $extra_roles = []; // 从extra_products中提取的角色
  7148. $extra_scenes = []; // 从extra_products中提取的场景
  7149. $extra_props = []; // 从extra_products中提取的道具
  7150. if ($extra_products && is_array($extra_products)) {
  7151. foreach($extra_products as $item) {
  7152. $product = (int)getProp($item, 'product');
  7153. $product_name = getProp($item, 'product_name');
  7154. if ($product_name == '旁白') continue;
  7155. $pic_prompt = getProp($item, 'pic_prompt');
  7156. $ref_products[$product_name] = $item;
  7157. if ($product === 1) {
  7158. // 角色
  7159. $extra_roles[$product_name] = [
  7160. 'role' => $product_name,
  7161. 'pic_prompt' => $pic_prompt,
  7162. 'url' => getProp($item, 'url', ''),
  7163. ];
  7164. } elseif ($product === 2) {
  7165. // 场景
  7166. $extra_scenes[$product_name] = [
  7167. 'scene' => $product_name,
  7168. 'pic_prompt' => $pic_prompt,
  7169. 'url' => getProp($item, 'url', ''),
  7170. ];
  7171. } elseif ($product === 3) {
  7172. // 道具
  7173. $extra_props[$product_name] = [
  7174. 'prop' => $product_name,
  7175. 'pic_prompt' => $pic_prompt,
  7176. 'url' => getProp($item, 'url', ''),
  7177. ];
  7178. }
  7179. }
  7180. }
  7181. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7182. $merged_roles = [];
  7183. foreach($ref_roles as $role) {
  7184. $role_name = getProp($role, 'role');
  7185. if (!isset($extra_roles[$role_name])) {
  7186. $merged_roles[$role_name] = $role;
  7187. }
  7188. }
  7189. // 添加extra_roles
  7190. foreach($extra_roles as $role_name => $role) {
  7191. $merged_roles[$role_name] = $role;
  7192. }
  7193. $ref_roles = array_values($merged_roles);
  7194. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7195. $merged_scenes = [];
  7196. foreach($ref_scenes as $scene) {
  7197. $scene_name = getProp($scene, 'scene');
  7198. if (!isset($extra_scenes[$scene_name])) {
  7199. $merged_scenes[$scene_name] = $scene;
  7200. }
  7201. }
  7202. // 添加extra_scenes
  7203. foreach($extra_scenes as $scene_name => $scene) {
  7204. $merged_scenes[$scene_name] = $scene;
  7205. }
  7206. $ref_scenes = array_values($merged_scenes);
  7207. // 合并ref_props和extra_props(extra_props优先,去重)
  7208. $merged_props = [];
  7209. foreach($ref_props as $prop) {
  7210. $prop_name = getProp($prop, 'prop');
  7211. if (!isset($extra_props[$prop_name])) {
  7212. $merged_props[$prop_name] = $prop;
  7213. }
  7214. }
  7215. // 添加extra_props
  7216. foreach($extra_props as $prop_name => $prop) {
  7217. $merged_props[$prop_name] = $prop;
  7218. }
  7219. $ref_props = array_values($merged_props);
  7220. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7221. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7222. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7223. // 构建强制主体、场景和道具提示词
  7224. $forced_roles_prompt = "";
  7225. $forced_scenes_prompt = "";
  7226. $forced_props_prompt = "";
  7227. if (!empty($extra_roles)) {
  7228. $forced_roles_list = "";
  7229. foreach($extra_roles as $role_name => $role) {
  7230. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7231. }
  7232. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7233. }
  7234. if (!empty($extra_scenes)) {
  7235. $forced_scenes_list = "";
  7236. foreach($extra_scenes as $scene_name => $scene) {
  7237. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7238. }
  7239. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7240. }
  7241. if (!empty($extra_props)) {
  7242. $forced_props_list = "";
  7243. foreach($extra_props as $prop_name => $prop) {
  7244. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7245. }
  7246. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7247. }
  7248. if ($anime_script_id) {
  7249. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7250. }else if ($roles_content) {
  7251. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7252. 主体范围:\n {$roles_content}\n
  7253. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7254. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7255. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7256. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7257. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7258. }else {
  7259. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7260. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7261. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7262. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7263. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7264. }
  7265. if ($anime_script_id) {
  7266. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7267. }else if ($scenes_content) {
  7268. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7269. 场景范围:\n {$scenes_content}\n
  7270. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7271. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7272. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7273. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7274. }else {
  7275. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7276. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7277. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7278. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7279. }
  7280. if ($anime_script_id) {
  7281. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7282. }else if ($props_content) {
  7283. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7284. 道具范围:\n {$props_content}\n
  7285. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7286. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7287. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7288. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7289. }else {
  7290. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7291. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7292. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7293. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7294. }
  7295. // 提取文件内容
  7296. if ($file) {
  7297. $uploaded_content = $this->extractFileContent($file);
  7298. if (!$uploaded_content) {
  7299. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7300. }
  7301. } elseif ($script_id) {
  7302. $uploaded_content = $this->getContentByScriptId($script_id);
  7303. if (!$uploaded_content) {
  7304. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7305. }
  7306. } elseif ($bid) {
  7307. $uploaded_content = $this->getContentByBid($bid);
  7308. if (!$uploaded_content) {
  7309. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7310. }
  7311. } elseif ($content) {
  7312. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7313. }
  7314. // elseif ($prompt) {
  7315. // $uploaded_content = filterContent($prompt);
  7316. // }
  7317. else {
  7318. $uploaded_content = '';
  7319. }
  7320. // 美术风格
  7321. $input_art_style = getProp($data, 'art_style');
  7322. if (!$input_art_style) {
  7323. $mappedArtStyle = getProp($anime, 'art_style');
  7324. }else {
  7325. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7326. }
  7327. if (!$mappedArtStyle) {
  7328. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7329. }else {
  7330. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7331. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7332. }else {
  7333. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7334. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7335. }
  7336. }
  7337. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7338. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7339. // 强制要求:
  7340. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7341. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7342. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7343. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7344. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7345. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7346. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7347. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7348. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7349. // 10.分镜要和场景列表、人物主体保持一致\n
  7350. // 普通要求:
  7351. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7352. // {$role_demo}
  7353. // {$scene_demo}
  7354. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7355. // 4.1片段分割逻辑(优先级从高到低):
  7356. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7357. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7358. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7359. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7360. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7361. // - 片段数量格式为: 片段数量:8
  7362. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7363. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7364. // 4.3分镜结构:每个分镜包含以下字段:
  7365. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7366. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7367. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7368. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7369. // - 运镜:场景+画面描述+运镜
  7370. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7371. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7372. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7373. // 5.$mappedArtStyle_prompt\n\n
  7374. // 示例格式:\n
  7375. // 第1集:隐形的守护者
  7376. // ###故事梗概
  7377. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7378. // ###美术风格
  7379. // 基础画风风格词:胡金铨武侠
  7380. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7381. // ###主体列表
  7382. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7383. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7384. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7385. // ###场景列表
  7386. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7387. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7388. // ###分段剧本
  7389. // 片段数量:8
  7390. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7391. // ##片段1
  7392. // 时长:12s
  7393. // 分镜1
  7394. // 场景:边境小镇街道
  7395. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7396. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7397. // 配音台词:
  7398. // 背景音效:
  7399. // 分镜2
  7400. // 场景:悦来酒馆
  7401. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7402. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7403. // 配音台词:
  7404. // 背景音效:
  7405. // 分镜3
  7406. // 场景:悦来酒馆
  7407. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7408. // 运镜:从中景推向令牌特写。
  7409. // 配音台词:
  7410. // 背景音效:
  7411. // 分镜4
  7412. // 场景:悦来酒馆
  7413. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7414. // 运镜:极速推向酒水溅起的瞬间。
  7415. // 配音台词:
  7416. // 背景音效:
  7417. // 分镜5
  7418. // 镜头描述
  7419. // 场景:悦来酒馆
  7420. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7421. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7422. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7423. // 背景音效:
  7424. // \n\n";
  7425. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7426. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7427. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7428. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7429. 普通要求:
  7430. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7431. {$role_demo}
  7432. {$scene_demo}
  7433. {$prop_demo}
  7434. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7435. 5.1片段分割逻辑(优先级从高到低):
  7436. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7437. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7438. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7439. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7440. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7441. - 片段数量格式为: 片段数量:8
  7442. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7443. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7444. 5.3分镜结构:每个分镜包含以下字段:
  7445. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7446. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7447. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7448. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7449. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7450. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7451. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7452. - 运镜:场景+画面描述+运镜
  7453. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7454. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7455. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7456. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7457. 6.《情绪-视听语言映射表》:
  7458. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7459. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7460. -----|---------|------------|----------------
  7461. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7462. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7463. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7464. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7465. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7466. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7467. -----|---------|------------|----------------
  7468. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7469. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7470. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7471. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7472. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7473. --------|---------|--------------|-------------
  7474. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7475. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7476. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7477. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7478. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7479. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7480. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7481. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7482. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7483. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7484. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7485. -----|---------|------------|------------
  7486. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7487. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7488. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7489. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7490. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7491. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7492. --------|---------|--------------|----------
  7493. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7494. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7495. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7496. 6.6 声音设计与潜意识影响 (Soundscape)
  7497. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7498. -----|---------|------------|------------------
  7499. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7500. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7501. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7502. 理论基石:
  7503. - The Five C's of Cinematography by Joseph V. Mascelli
  7504. - Film Art: An Introduction by David Bordwell
  7505. - Sight, Sound, Motion by Herbert Zettl
  7506. - Notes on the Cinematograph by Robert Bresson
  7507. \n\n
  7508. 7.{$mappedArtStyle_prompt}
  7509. 示例格式:\n
  7510. 第1集:隐形的守护者
  7511. ###故事梗概
  7512. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7513. ###美术风格
  7514. 基础画风风格词:胡金铨武侠
  7515. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7516. ###主体列表
  7517. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7518. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7519. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7520. ###场景列表
  7521. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7522. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7523. ###道具列表
  7524. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7525. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7526. ###分段剧本
  7527. 片段数量:8
  7528. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7529. ##片段1
  7530. 时长:12s
  7531. 分镜1
  7532. 出场角色:刀疤脸
  7533. 场景:边境小镇街道
  7534. 出场道具:酒杯-高脚杯
  7535. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7536. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7537. 配音台词:
  7538. 背景音效:
  7539. 分镜2
  7540. 出场角色:刀疤脸
  7541. 场景:悦来酒馆
  7542. 出场道具:酒杯-高脚杯
  7543. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7544. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7545. 配音台词:
  7546. 背景音效:
  7547. 分镜3
  7548. 出场角色:刀疤脸
  7549. 场景:悦来酒馆
  7550. 出场道具:酒杯-高脚杯
  7551. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7552. 运镜:从中景推向令牌特写。
  7553. 配音台词:
  7554. 背景音效:
  7555. 分镜4
  7556. 出场角色:刀疤脸
  7557. 场景:悦来酒馆
  7558. 出场道具:酒杯-高脚杯
  7559. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7560. 运镜:极速推向酒水溅起的瞬间。
  7561. 配音台词:
  7562. 背景音效:
  7563. 分镜5
  7564. 出场角色:刀疤脸
  7565. 场景:悦来酒馆
  7566. 出场道具:酒杯-高脚杯
  7567. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7568. 运镜:固定机位,利用倾斜构图制造压迫感。
  7569. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7570. 背景音效:
  7571. \n\n";
  7572. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7573. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7574. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7575. $prompt = $origin_prompt;
  7576. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7577. // 获取章节内容
  7578. $full_content = getProp($anime, 'content');
  7579. if ($uploaded_content) {
  7580. $full_content = $uploaded_content;
  7581. }
  7582. // 根据章节内容拆分章节
  7583. $chapters = splitContent($full_content);
  7584. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7585. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7586. $messages = [];
  7587. if ($prompt == '确认分镜大纲') {
  7588. // 暂时保留
  7589. $content = $chapter_content;
  7590. if ($is_single) $content = $full_content; // 单剧集使用全文
  7591. if (!$content) {
  7592. Utils::throwError('20003:章节内容无法获取,请确认');
  7593. }
  7594. $question = $is_single
  7595. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7596. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7597. // 构建消息
  7598. $messages[] =
  7599. [
  7600. 'role' => 'user',
  7601. 'content' => $question
  7602. ];
  7603. }else if ($prompt == '继续策划下一集') {
  7604. if ($is_single) {
  7605. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7606. }
  7607. $content = $chapter_content;
  7608. if (!$content) {
  7609. Utils::throwError('20003:章节内容无法获取,请确认');
  7610. }
  7611. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7612. // 获取上一集最后记录
  7613. $prev_sequence = $episode_number - 1;
  7614. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7615. // 构建消息
  7616. $messages[] =
  7617. [
  7618. 'role' => 'user',
  7619. 'content' => $question
  7620. ];
  7621. // dd($messages);
  7622. }else {
  7623. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7624. if (!$content) {
  7625. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7626. }
  7627. if (!$content) {
  7628. Utils::throwError('20003:章节内容无法获取,请确认');
  7629. }
  7630. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7631. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7632. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7633. if ($origin_prompt) {
  7634. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7635. }
  7636. $messages[] =
  7637. [
  7638. 'role' => 'user',
  7639. 'content' => $question
  7640. ];
  7641. }
  7642. // 处理文本模型
  7643. $model = getProp($data, 'model');
  7644. if (!$model) {
  7645. // 用户没有输入,从anime表获取
  7646. $model = getProp($anime, 'model');
  7647. if (!$model) {
  7648. // anime表也没有,使用默认值
  7649. $model = 'deepseek-v4-pro';
  7650. }
  7651. }
  7652. // 验证模型是否在可用模型表中
  7653. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7654. $model = 'deepseek-v4-pro';
  7655. }
  7656. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7657. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7658. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7659. if ($model === 'deepseek-chat') {
  7660. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7661. $model = 'deepseek-v4-flash';
  7662. $thinkingMode = 'disabled';
  7663. } elseif ($model === 'deepseek-reasoner') {
  7664. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7665. $model = 'deepseek-v4-flash';
  7666. $thinkingMode = 'enabled';
  7667. }
  7668. $post_data = [
  7669. 'model' => $model,
  7670. 'messages' => $messages,
  7671. // 'max_tokens' => 8192,
  7672. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7673. 'frequency_penalty' => 0,
  7674. 'presence_penalty' => 0,
  7675. 'response_format' => ['type' => 'text'],
  7676. 'thinking' => ['type' => $thinkingMode],
  7677. 'stream' => true // 启用流式输出
  7678. ];
  7679. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7680. // 根据模型类型选择调用方法
  7681. $fullContent = '';
  7682. $fullReasoningContent = '';
  7683. $usage = [];
  7684. try {
  7685. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7686. // DeepSeek 官方模型使用 DeepSeek API
  7687. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7688. } else if (in_array($model, $this->gpt_text_models)) {
  7689. // GPT-5.4 模型使用 TokenRouter API
  7690. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7691. } else {
  7692. // 其他模型使用火山引擎API
  7693. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7694. }
  7695. // 验证返回值类型
  7696. if (!is_iterable($streamGenerator)) {
  7697. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7698. dLog('deepseek')->error('chat流式生成器无效', [
  7699. 'generator_type' => $errorType,
  7700. 'model' => $model,
  7701. 'anime_id' => $anime_id,
  7702. 'episode_number' => $episode_number
  7703. ]);
  7704. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7705. 'type' => $errorType,
  7706. 'model' => $model
  7707. ]);
  7708. yield [
  7709. 'type' => 'error',
  7710. 'episode' => [],
  7711. 'answer' => '',
  7712. 'reasoning' => '',
  7713. 'usage' => [],
  7714. 'error' => '接口返回数据异常,请重新请求'
  7715. ];
  7716. return;
  7717. }
  7718. // 处理流式输出
  7719. foreach ($streamGenerator as $chunk) {
  7720. if (isset($chunk['type'])) {
  7721. if ($chunk['type'] === 'done') {
  7722. // 最终结果
  7723. $fullContent = $chunk['full_content'];
  7724. $fullReasoningContent = $chunk['full_reasoning'];
  7725. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7726. } else {
  7727. // 逐块yield数据
  7728. yield $chunk;
  7729. }
  7730. }
  7731. }
  7732. } catch (\Exception $e) {
  7733. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7734. 'model' => $model,
  7735. 'anime_id' => $anime_id,
  7736. 'episode_number' => $episode_number,
  7737. 'trace' => $e->getTraceAsString()
  7738. ]);
  7739. logDB('deepseek', 'error', 'chat流式处理失败', [
  7740. 'error' => $e->getMessage(),
  7741. 'model' => $model
  7742. ]);
  7743. yield [
  7744. 'type' => 'error',
  7745. 'episode' => [],
  7746. 'answer' => '',
  7747. 'reasoning' => '',
  7748. 'usage' => [],
  7749. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7750. ];
  7751. return;
  7752. }
  7753. dLog('deepseek')->info('完整内容: '.$fullContent);
  7754. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7755. // 处理完整内容并返回最终结果
  7756. $episode_arr = handleEpisodeContentForAce($fullContent);
  7757. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7758. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7759. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7760. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7761. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7762. // }
  7763. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7764. $max_retries = 3;
  7765. $retry_count = 0;
  7766. $validation_failed = false;
  7767. $validation_error_msg = '';
  7768. // 验证生成的内容
  7769. if ($anime_script_id) {
  7770. // 检查是否有acts数据
  7771. if (empty($episode_arr['acts'])) {
  7772. $validation_failed = true;
  7773. $validation_error_msg = '未生成分镜剧本相关的内容';
  7774. } else {
  7775. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7776. $generated_roles = array_column($episode_arr['roles'], 'role');
  7777. // 过滤掉"旁白"角色
  7778. $generated_roles = array_filter($generated_roles, function($role) {
  7779. return $role !== '旁白';
  7780. });
  7781. $expected_roles = array_keys($extra_roles);
  7782. // 找出生成的主体中不在预期列表中的主体
  7783. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7784. if (!empty($invalid_roles)) {
  7785. $validation_failed = true;
  7786. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7787. }
  7788. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7789. if (!$validation_failed) {
  7790. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7791. $expected_scenes = array_keys($extra_scenes);
  7792. // 找出生成的场景中不在预期列表中的场景
  7793. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7794. if (!empty($invalid_scenes)) {
  7795. $validation_failed = true;
  7796. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7797. }
  7798. }
  7799. }
  7800. } else {
  7801. // 如果没有anime_script_id,只检查是否有acts数据
  7802. if (empty($episode_arr['acts'])) {
  7803. $validation_failed = true;
  7804. $validation_error_msg = '未生成分镜剧本相关的内容';
  7805. }
  7806. }
  7807. // 重试逻辑
  7808. while ($validation_failed && $retry_count < $max_retries) {
  7809. $retry_count++;
  7810. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7811. 'reason' => $validation_error_msg,
  7812. 'anime_id' => $anime_id,
  7813. 'episode_number' => $episode_number
  7814. ]);
  7815. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7816. 'reason' => $validation_error_msg,
  7817. 'anime_id' => $anime_id
  7818. ]);
  7819. // 发送流式重试提示
  7820. yield [
  7821. 'type' => 'retry',
  7822. 'retry_count' => $retry_count,
  7823. 'reason' => $validation_error_msg
  7824. ];
  7825. // 构建重试提示词
  7826. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7827. if ($anime_script_id) {
  7828. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7829. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7830. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7831. } else {
  7832. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7833. }
  7834. // 添加重试消息到messages
  7835. $messages[] = [
  7836. 'role' => 'assistant',
  7837. 'content' => $fullContent
  7838. ];
  7839. $messages[] = [
  7840. 'role' => 'user',
  7841. 'content' => $retry_prompt
  7842. ];
  7843. // 更新post_data的messages
  7844. $post_data['messages'] = $messages;
  7845. // 重新调用API
  7846. try {
  7847. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7848. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7849. } else if (in_array($model, $this->gpt_text_models)) {
  7850. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7851. } else {
  7852. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7853. }
  7854. // 处理流式输出
  7855. $fullContent = '';
  7856. $fullReasoningContent = '';
  7857. foreach ($streamGenerator as $chunk) {
  7858. if (isset($chunk['type'])) {
  7859. if ($chunk['type'] === 'done') {
  7860. $fullContent = $chunk['full_content'];
  7861. $fullReasoningContent = $chunk['full_reasoning'];
  7862. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7863. } else {
  7864. yield $chunk;
  7865. }
  7866. }
  7867. }
  7868. // 重新解析内容
  7869. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7870. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7871. $episode_arr = handleEpisodeContentForAce($fullContent);
  7872. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7873. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7874. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7875. // }
  7876. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7877. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7878. // 重新验证
  7879. $validation_failed = false;
  7880. $validation_error_msg = '';
  7881. if ($anime_script_id) {
  7882. if (empty($episode_arr['acts'])) {
  7883. $validation_failed = true;
  7884. $validation_error_msg = '未生成分镜剧本相关的内容';
  7885. } else {
  7886. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7887. $generated_roles = array_column($episode_arr['roles'], 'role');
  7888. // 过滤掉"旁白"角色
  7889. $generated_roles = array_filter($generated_roles, function($role) {
  7890. return $role !== '旁白';
  7891. });
  7892. $expected_roles = array_keys($extra_roles);
  7893. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7894. if (!empty($invalid_roles)) {
  7895. $validation_failed = true;
  7896. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7897. }
  7898. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7899. if (!$validation_failed) {
  7900. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7901. $expected_scenes = array_keys($extra_scenes);
  7902. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7903. if (!empty($invalid_scenes)) {
  7904. $validation_failed = true;
  7905. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7906. }
  7907. }
  7908. }
  7909. } else {
  7910. if (empty($episode_arr['acts'])) {
  7911. $validation_failed = true;
  7912. $validation_error_msg = '未生成分镜剧本相关的内容';
  7913. }
  7914. }
  7915. } catch (\Exception $e) {
  7916. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7917. 'trace' => $e->getTraceAsString()
  7918. ]);
  7919. break;
  7920. }
  7921. }
  7922. // 如果重试后仍然失败
  7923. if ($validation_failed) {
  7924. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7925. 'retry_count' => $retry_count,
  7926. 'last_error' => $validation_error_msg
  7927. ]);
  7928. try {
  7929. $now = date('Y-m-d H:i:s');
  7930. $records = [
  7931. [
  7932. 'uid' => $uid,
  7933. 'anime_id' => $anime_id,
  7934. 'sequence' => $episode_number,
  7935. 'role' => 'user',
  7936. 'content' => $prompt,
  7937. 'created_at' => $now,
  7938. 'updated_at' => $now
  7939. ],
  7940. [
  7941. 'uid' => $uid,
  7942. 'anime_id' => $anime_id,
  7943. 'sequence' => $episode_number,
  7944. 'role' => 'assistant',
  7945. 'content' => $fullContent,
  7946. 'created_at' => $now,
  7947. 'updated_at' => $now
  7948. ]
  7949. ];
  7950. DB::table('mp_anime_records')->insert($records);
  7951. } catch (\Exception $e) {
  7952. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7953. }
  7954. yield [
  7955. 'type' => 'done',
  7956. 'episode' => [],
  7957. 'answer' => $fullContent,
  7958. 'reasoning' => $fullReasoningContent,
  7959. 'usage' => $usage,
  7960. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  7961. ];
  7962. return;
  7963. }
  7964. // 验证成功,记录日志
  7965. if ($retry_count > 0) {
  7966. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  7967. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  7968. }
  7969. // 老逻辑
  7970. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7971. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7972. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7973. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7974. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7975. $existing_props = is_array($existing_props) ? $existing_props : [];
  7976. $now = date('Y-m-d H:i:s');
  7977. try {
  7978. DB::beginTransaction();
  7979. $saveResult = $this->saveEpisodeVersionData(
  7980. $anime_id,
  7981. $episode_number,
  7982. $episode_arr,
  7983. $existing_roles,
  7984. $existing_scenes,
  7985. $existing_props,
  7986. $current_episode,
  7987. $base_episode,
  7988. $is_regenerate_version,
  7989. $content,
  7990. $now,
  7991. $ref_products
  7992. );
  7993. $episode = $saveResult['episode'];
  7994. $episode_id = $saveResult['episode_id'];
  7995. $merged_roles = $saveResult['merged_roles'];
  7996. $merged_scenes = $saveResult['merged_scenes'];
  7997. $merged_props = $saveResult['merged_props'];
  7998. $record_content = $origin_prompt;
  7999. if ($uploaded_content !== '') {
  8000. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8001. }
  8002. $records = [
  8003. [
  8004. 'uid' => $uid,
  8005. 'anime_id' => $anime_id,
  8006. 'role' => 'user',
  8007. 'content' => $record_content,
  8008. 'sequence' => $episode_number,
  8009. 'episode_id' => $episode_id,
  8010. 'created_at' => $now,
  8011. 'updated_at' => $now
  8012. ],
  8013. [
  8014. 'uid' => $uid,
  8015. 'anime_id' => $anime_id,
  8016. 'role' => 'assistant',
  8017. 'content' => $fullContent,
  8018. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8019. 'sequence' => $episode_number,
  8020. 'episode_id' => $episode_id,
  8021. 'created_at' => $now,
  8022. 'updated_at' => $now
  8023. ]
  8024. ];
  8025. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8026. if (!$boolen4) {
  8027. Utils::throwError('20003:对话记录保存失败');
  8028. }
  8029. // 保存模型到anime表
  8030. $update_anime_data = [
  8031. 'model' => $model,
  8032. 'updated_at' => $now
  8033. ];
  8034. if ($uploaded_content) {
  8035. $update_anime_data['content'] = $uploaded_content;
  8036. }
  8037. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8038. }catch (\Exception $e) {
  8039. DB::rollBack();
  8040. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8041. yield [
  8042. 'type' => 'done',
  8043. 'answer' => $fullContent,
  8044. 'reasoning' => $fullReasoningContent,
  8045. 'usage' => $usage,
  8046. 'error' => $e->getMessage(),
  8047. ];
  8048. return;
  8049. }
  8050. DB::commit();
  8051. if ($is_global_generate_pics) {
  8052. // // 批量生成全局角色图片
  8053. // $this->batchSetGlobalRoleImg([
  8054. // 'anime_id' => $anime_id,
  8055. // ], true);
  8056. // // 批量生成全局场景图片
  8057. // $this->batchSetGlobalSceneImg([
  8058. // 'anime_id' => $anime_id,
  8059. // ], true);
  8060. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8061. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8062. }
  8063. $episode['episode_id'] = $episode_id;
  8064. $episode['roles'] = $merged_roles;
  8065. $episode['scenes'] = $merged_scenes;
  8066. $episode['props'] = $merged_props;
  8067. $episode['end_episode_sequence'] = $end_episode_sequence;
  8068. // 获取mp_animes表中的视频参数
  8069. $episode['video_params'] = [
  8070. 'video_model' => getProp($anime, 'video_model'),
  8071. 'video_resolution' => getProp($anime, 'video_resolution'),
  8072. 'ratio' => getProp($anime, 'video_ratio'),
  8073. ];
  8074. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8075. yield [
  8076. 'type' => 'done',
  8077. 'episode' => $episode,
  8078. 'answer' => $fullContent,
  8079. 'reasoning' => $fullReasoningContent,
  8080. 'usage' => $usage
  8081. ];
  8082. }
  8083. /**
  8084. * chatForAce的非流式版本 - 用于定时任务
  8085. * 只获取最终 type=done 的数据,并验证必要字段
  8086. *
  8087. * @param array $data 请求数据
  8088. * @return array 生成结果
  8089. */
  8090. public function chatForAceNonStream($data) {
  8091. $finalResult = null;
  8092. // 调用流式方法,只保存 type=done 的数据
  8093. foreach ($this->chatForAce($data) as $chunk) {
  8094. // 只关注最终结果
  8095. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8096. $finalResult = $chunk;
  8097. break; // 找到 done 就退出循环
  8098. }
  8099. }
  8100. // 验证最终结果
  8101. if (!$finalResult) {
  8102. return ['error' => '生成失败:未获取到最终结果'];
  8103. }
  8104. // 检查是否有错误
  8105. if (isset($finalResult['error']) && $finalResult['error']) {
  8106. return $finalResult;
  8107. }
  8108. // 验证必要字段
  8109. $episode = $finalResult['episode'] ?? [];
  8110. // 验证 roles
  8111. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8112. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8113. }
  8114. // 验证 scenes
  8115. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8116. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8117. }
  8118. // 验证 props(道具可以为空,但必须存在且为数组)
  8119. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8120. $episode['props'] = [];
  8121. }
  8122. // 验证 acts(分镜剧本)
  8123. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8124. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8125. }
  8126. // 更新验证后的 episode 数据
  8127. $finalResult['episode'] = $episode;
  8128. // 记录验证成功日志
  8129. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8130. 'roles_count' => count($episode['roles']),
  8131. 'scenes_count' => count($episode['scenes']),
  8132. 'props_count' => count($episode['props']),
  8133. 'acts_count' => count($episode['acts'])
  8134. ]);
  8135. return $finalResult;
  8136. }
  8137. /**
  8138. * 批量生成多个分集
  8139. *
  8140. * @param array $data 请求数据
  8141. * @return array 任务信息
  8142. */
  8143. public function batchGenerateEpisodes($data) {
  8144. $uid = Site::getUid();
  8145. $cpid = Site::getCpid();
  8146. $anime_id = getProp($data, 'anime_id');
  8147. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8148. if (!$anime_id) {
  8149. Utils::throwError('20003:anime_id参数缺失');
  8150. }
  8151. if ($generate_episode_number < 1) {
  8152. Utils::throwError('20003:生成集数必须大于0');
  8153. }
  8154. // 获取动漫信息
  8155. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8156. if (!$anime) {
  8157. Utils::throwError('20003:该剧集不存在');
  8158. }
  8159. // 检查是否是全能模式
  8160. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8161. Utils::throwError('20003:只有全能模式才支持批量生成');
  8162. }
  8163. // 检查是否是多剧集模式
  8164. if ((int)getProp($anime, 'is_multi') !== 1) {
  8165. Utils::throwError('20003:单剧集不支持批量生成');
  8166. }
  8167. // 获取当前已生成的最大集数
  8168. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8169. ->where('anime_id', $anime_id)
  8170. ->where('is_default', 1)
  8171. ->max('episode_number');
  8172. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8173. // 确定起始集数
  8174. $startEpisodeNumber = $currentMaxEpisode + 1;
  8175. // 计算结束集数
  8176. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8177. // 检查是否超过总集数限制
  8178. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8179. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8180. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8181. }
  8182. $now = date('Y-m-d H:i:s');
  8183. $createdTasks = [];
  8184. $skippedTasks = [];
  8185. // 为每一集创建详情记录
  8186. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8187. // 检查是否已有该集的任务记录
  8188. $existingTask = DB::table('mp_batch_episode_generation_details')
  8189. ->where('anime_id', $anime_id)
  8190. ->where('episode_number', $episodeNumber)
  8191. ->first();
  8192. if ($existingTask) {
  8193. // 如果已存在且未完成,跳过
  8194. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8195. $skippedTasks[] = $episodeNumber;
  8196. continue;
  8197. }
  8198. // 如果是失败状态,可以重新创建(删除旧记录)
  8199. if ($existingTask->status === 'failed') {
  8200. DB::table('mp_batch_episode_generation_details')
  8201. ->where('id', $existingTask->id)
  8202. ->delete();
  8203. }
  8204. // 如果是已完成状态,也跳过
  8205. if ($existingTask->status === 'completed') {
  8206. $skippedTasks[] = $episodeNumber;
  8207. continue;
  8208. }
  8209. }
  8210. // 准备任务数据
  8211. $taskData = [
  8212. 'anime_id' => $anime_id,
  8213. 'uid' => $uid,
  8214. 'cpid' => $cpid,
  8215. 'episode_number' => $episodeNumber,
  8216. 'status' => 'pending',
  8217. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8218. 'retry_count' => 0,
  8219. 'created_at' => $now,
  8220. 'updated_at' => $now
  8221. ];
  8222. // 创建任务记录
  8223. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8224. if ($taskId) {
  8225. $createdTasks[] = $episodeNumber;
  8226. }
  8227. }
  8228. if (empty($createdTasks)) {
  8229. if (!empty($skippedTasks)) {
  8230. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8231. } else {
  8232. Utils::throwError('20003:创建批量生成任务失败');
  8233. }
  8234. }
  8235. return [
  8236. 'anime_id' => $anime_id,
  8237. 'start_episode' => $startEpisodeNumber,
  8238. 'end_episode' => $endEpisodeNumber,
  8239. 'total_episodes' => $generate_episode_number,
  8240. 'created_episodes' => $createdTasks,
  8241. 'skipped_episodes' => $skippedTasks,
  8242. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8243. "已创建: " . implode(',', $createdTasks) .
  8244. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8245. ];
  8246. }
  8247. /**
  8248. * 获取批量生成任务状态
  8249. *
  8250. * @param array $data 请求数据
  8251. * @return array 任务状态信息
  8252. */
  8253. public function getBatchGenerationTaskStatus($data) {
  8254. $anime_id = getProp($data, 'anime_id');
  8255. if (!$anime_id) {
  8256. Utils::throwError('20003:anime_id参数缺失');
  8257. }
  8258. // 获取该anime的所有任务
  8259. $tasks = DB::table('mp_batch_episode_generation_details')
  8260. ->where('anime_id', $anime_id)
  8261. ->orderBy('episode_number')
  8262. ->get()
  8263. ->map(function($item) {
  8264. return [
  8265. 'id' => $item->id,
  8266. 'episode_number' => $item->episode_number,
  8267. 'status' => $item->status,
  8268. 'error_message' => $item->error_message,
  8269. 'retry_count' => $item->retry_count,
  8270. 'created_at' => $item->created_at,
  8271. 'updated_at' => $item->updated_at,
  8272. 'completed_at' => $item->completed_at
  8273. ];
  8274. })
  8275. ->toArray();
  8276. if (empty($tasks)) {
  8277. Utils::throwError('20003:该剧集没有批量生成任务');
  8278. }
  8279. // 统计各状态数量
  8280. $totalCount = count($tasks);
  8281. $pendingCount = 0;
  8282. $processingCount = 0;
  8283. $completedCount = 0;
  8284. $failedCount = 0;
  8285. foreach ($tasks as $task) {
  8286. switch ($task['status']) {
  8287. case 'pending':
  8288. $pendingCount++;
  8289. break;
  8290. case 'processing':
  8291. $processingCount++;
  8292. break;
  8293. case 'completed':
  8294. $completedCount++;
  8295. break;
  8296. case 'failed':
  8297. $failedCount++;
  8298. break;
  8299. }
  8300. }
  8301. // 计算进度百分比
  8302. $progress = 0;
  8303. if ($totalCount > 0) {
  8304. $progress = round(($completedCount / $totalCount) * 100, 2);
  8305. }
  8306. // 判断整体状态
  8307. $overallStatus = 'processing';
  8308. if ($completedCount === $totalCount) {
  8309. $overallStatus = 'completed';
  8310. } elseif ($pendingCount === $totalCount) {
  8311. $overallStatus = 'pending';
  8312. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8313. $overallStatus = 'failed';
  8314. }
  8315. return [
  8316. 'anime_id' => $anime_id,
  8317. 'total_episodes' => $totalCount,
  8318. 'pending_count' => $pendingCount,
  8319. 'processing_count' => $processingCount,
  8320. 'completed_count' => $completedCount,
  8321. 'failed_count' => $failedCount,
  8322. 'progress' => $progress,
  8323. 'overall_status' => $overallStatus,
  8324. 'tasks' => $tasks
  8325. ];
  8326. }
  8327. /**
  8328. * 智能匹配并替换主体和场景名称
  8329. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8330. *
  8331. * @param array $episode_arr 解析后的剧集数据
  8332. * @param array $extra_roles 强制主体设定(key为主体名称)
  8333. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8334. * @return array 替换后的剧集数据
  8335. */
  8336. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8337. $replaced_count = 0;
  8338. // 1. 处理主体列表
  8339. if (!empty($episode_arr['roles'])) {
  8340. foreach ($episode_arr['roles'] as &$role) {
  8341. $generated_role_name = $role['role'] ?? '';
  8342. // 跳过旁白
  8343. if ($generated_role_name === '旁白') {
  8344. continue;
  8345. }
  8346. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8347. if (!isset($extra_roles[$generated_role_name])) {
  8348. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8349. if ($matched_role) {
  8350. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8351. $role['role'] = $matched_role;
  8352. $replaced_count++;
  8353. }
  8354. }
  8355. }
  8356. }
  8357. // 2. 处理场景列表
  8358. if (!empty($episode_arr['scenes'])) {
  8359. foreach ($episode_arr['scenes'] as &$scene) {
  8360. $generated_scene_name = $scene['scene'] ?? '';
  8361. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8362. if (!isset($extra_scenes[$generated_scene_name])) {
  8363. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8364. if ($matched_scene) {
  8365. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8366. $scene['scene'] = $matched_scene;
  8367. $replaced_count++;
  8368. }
  8369. }
  8370. }
  8371. }
  8372. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8373. if (!empty($episode_arr['acts'])) {
  8374. foreach ($episode_arr['acts'] as &$act) {
  8375. if (!empty($act['segments'])) {
  8376. foreach ($act['segments'] as &$segment) {
  8377. if (!empty($segment['segment_content'])) {
  8378. $original_content = $segment['segment_content'];
  8379. $replaced_content = $original_content;
  8380. // 替换场景名 - 在文本中查找并替换
  8381. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8382. // 尝试找到可能的短名称
  8383. $potential_short_names = [];
  8384. // 提取场景名的主要部分(冒号之前)
  8385. if (mb_strpos($full_scene_name, ':') !== false) {
  8386. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8387. $potential_short_names[] = $short_name;
  8388. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8389. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8390. $potential_short_names[] = $short_name;
  8391. }
  8392. // 替换场景字段中的短名称
  8393. foreach ($potential_short_names as $short_name) {
  8394. if ($short_name !== $full_scene_name) {
  8395. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8396. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8397. if ($new_content !== $replaced_content) {
  8398. $replaced_content = $new_content;
  8399. $replaced_count++;
  8400. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8401. }
  8402. }
  8403. }
  8404. }
  8405. // 替换配音角色名(跳过旁白)
  8406. foreach (array_keys($extra_roles) as $full_role_name) {
  8407. if ($full_role_name === '旁白') {
  8408. continue;
  8409. }
  8410. // 尝试找到可能的短名称
  8411. $potential_short_names = [];
  8412. // 提取角色名的主要部分(短横线之前)
  8413. if (mb_strpos($full_role_name, '-') !== false) {
  8414. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8415. $potential_short_names[] = $short_name;
  8416. }
  8417. // 替换配音台词中的短名称
  8418. foreach ($potential_short_names as $short_name) {
  8419. if ($short_name !== $full_role_name) {
  8420. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8421. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8422. if ($new_content !== $replaced_content) {
  8423. $replaced_content = $new_content;
  8424. $replaced_count++;
  8425. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8426. }
  8427. }
  8428. }
  8429. }
  8430. // 如果有替换,更新segment_content
  8431. if ($replaced_content !== $original_content) {
  8432. $segment['segment_content'] = $replaced_content;
  8433. }
  8434. }
  8435. }
  8436. }
  8437. }
  8438. }
  8439. if ($replaced_count > 0) {
  8440. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8441. 'replaced_count' => $replaced_count
  8442. ]);
  8443. }
  8444. return $episode_arr;
  8445. }
  8446. /**
  8447. * 查找匹配的名称
  8448. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8449. *
  8450. * @param string $generated_name 生成的名称
  8451. * @param array $expected_names 预期的名称列表
  8452. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8453. */
  8454. private function findMatchingName($generated_name, $expected_names) {
  8455. if (empty($generated_name)) {
  8456. return null;
  8457. }
  8458. // 尝试精确匹配
  8459. if (in_array($generated_name, $expected_names)) {
  8460. return $generated_name;
  8461. }
  8462. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8463. foreach ($expected_names as $expected_name) {
  8464. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8465. if (mb_strpos($expected_name, $generated_name) === 0) {
  8466. return $expected_name;
  8467. }
  8468. }
  8469. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8470. // 这样可以处理一些变体,但优先级较低
  8471. foreach ($expected_names as $expected_name) {
  8472. if (mb_strpos($expected_name, $generated_name) !== false) {
  8473. return $expected_name;
  8474. }
  8475. }
  8476. return null;
  8477. }
  8478. /**
  8479. * 重新生成分段剧本
  8480. * @param array $data 包含以下字段:
  8481. * - prompt: string|null 用户修改要求(可选)
  8482. * - template_id: int|null 提示词模板ID(可选)
  8483. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8484. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8485. * @return array 返回生成结果
  8486. */
  8487. public function regenerateSegmentScript($data) {
  8488. $uid = Site::getUid();
  8489. $prompt = trim((string)getProp($data, 'prompt', ''));
  8490. $template_id = getProp($data, 'template_id', 0);
  8491. $act_id = getProp($data, 'act_id', 0);
  8492. $episode_id = getProp($data, 'episode_id', 0);
  8493. // 验证:prompt和template_id至少提供一个
  8494. if (empty($prompt) && empty($template_id)) {
  8495. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8496. }
  8497. // 验证:act_id和episode_id二选一
  8498. if (empty($act_id) && empty($episode_id)) {
  8499. Utils::throwError('20003:请提供片段ID或剧集ID');
  8500. }
  8501. if (!empty($act_id) && !empty($episode_id)) {
  8502. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8503. }
  8504. // 如果提供了template_id,获取模板提示词
  8505. $template_prompt = '';
  8506. if ($template_id > 0) {
  8507. $template = DB::table('mp_prompt_templates')
  8508. ->where('id', $template_id)
  8509. ->where('is_deleted', 0)
  8510. ->first();
  8511. if (!$template) {
  8512. Utils::throwError('20003:提示词模板不存在或已删除');
  8513. }
  8514. $template_prompt = $template->template_prompt ?? '';
  8515. }
  8516. // 合并用户提示词和模板提示词
  8517. $final_prompt = '';
  8518. if (!empty($template_prompt)) {
  8519. $final_prompt = $template_prompt;
  8520. if (!empty($prompt)) {
  8521. $final_prompt .= "\n\n补充要求:" . $prompt;
  8522. }
  8523. } else {
  8524. $final_prompt = $prompt;
  8525. }
  8526. // 获取需要重新生成的内容参考
  8527. $reference_content = '';
  8528. $target_episode_id = 0;
  8529. $target_anime_id = 0;
  8530. $target_episode_number = 0;
  8531. if ($act_id > 0) {
  8532. // 单个片段模式:获取该片段的内容
  8533. $segment = DB::table('mp_episode_segments')
  8534. ->where('id', $act_id)
  8535. ->first();
  8536. if (!$segment) {
  8537. Utils::throwError('20003:片段不存在');
  8538. }
  8539. $target_episode_id = $segment->episode_id;
  8540. $target_anime_id = $segment->anime_id;
  8541. $target_episode_number = $segment->episode_number;
  8542. $reference_content = $segment->act_content ?? '';
  8543. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8544. } else {
  8545. // 整个剧集模式:获取所有片段的内容
  8546. $segments = DB::table('mp_episode_segments')
  8547. ->where('episode_id', $episode_id)
  8548. ->orderBy('act_number')
  8549. ->get();
  8550. if ($segments->isEmpty()) {
  8551. Utils::throwError('20003:该剧集没有片段数据');
  8552. }
  8553. $target_episode_id = $episode_id;
  8554. $target_anime_id = $segments[0]->anime_id;
  8555. $target_episode_number = $segments[0]->episode_number;
  8556. // 拼接所有片段内容,保留格式用于AI理解
  8557. $act_contents = [];
  8558. foreach ($segments as $seg) {
  8559. $act_number = $seg->act_number;
  8560. $act_content = $seg->act_content ?? '';
  8561. if (!empty($act_content)) {
  8562. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8563. }
  8564. }
  8565. $reference_content = implode("\n\n", $act_contents);
  8566. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8567. if ($episode_content) {
  8568. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8569. }else {
  8570. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8571. }
  8572. }
  8573. if (empty($reference_content)) {
  8574. Utils::throwError('20003:没有可参考的片段内容');
  8575. }
  8576. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8577. $episode = DB::table('mp_anime_episodes')
  8578. ->where('id', $target_episode_id)
  8579. ->first();
  8580. if (!$episode) {
  8581. Utils::throwError('20003:剧集不存在');
  8582. }
  8583. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8584. $anime_script_id = getProp($anime, 'script_id');
  8585. $intro = $episode->intro ?? '';
  8586. $art_style = $episode->art_style ?? '';
  8587. $roles = json_decode($episode->roles ?? '[]', true);
  8588. $scenes = json_decode($episode->scenes ?? '[]', true);
  8589. $props = json_decode($episode->props ?? '[]', true);
  8590. // 构建提示词中的主体列表和场景列表参考
  8591. $roles_ref = '';
  8592. if (!empty($roles) && is_array($roles)) {
  8593. $roles_list = [];
  8594. foreach ($roles as $role) {
  8595. $role_name = getProp($role, 'role', '');
  8596. $role_desc = getProp($role, 'description', '');
  8597. $pic_prompt = getProp($role, 'pic_prompt', '');
  8598. $voice_prompt = getProp($role, 'voice_prompt', '');
  8599. if (!empty($role_name)) {
  8600. $role_line = $role_name;
  8601. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8602. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8603. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8604. $roles_list[] = $role_line;
  8605. }
  8606. }
  8607. if (!empty($roles_list)) {
  8608. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8609. }
  8610. }
  8611. $scenes_ref = '';
  8612. if (!empty($scenes) && is_array($scenes)) {
  8613. $scenes_list = [];
  8614. foreach ($scenes as $scene) {
  8615. $scene_name = getProp($scene, 'scene', '');
  8616. $scene_desc = getProp($scene, 'description', '');
  8617. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8618. if (!empty($scene_name)) {
  8619. $scene_line = $scene_name;
  8620. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8621. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8622. $scenes_list[] = $scene_line;
  8623. }
  8624. }
  8625. if (!empty($scenes_list)) {
  8626. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8627. }
  8628. }
  8629. $props_ref = '';
  8630. if (!empty($props) && is_array($props)) {
  8631. $props_list = [];
  8632. foreach ($props as $prop) {
  8633. $prop_name = getProp($prop, 'prop', '');
  8634. $prop_desc = getProp($prop, 'description', '');
  8635. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8636. if (!empty($prop_name)) {
  8637. $prop_line = $prop_name;
  8638. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8639. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8640. $props_list[] = $prop_line;
  8641. }
  8642. }
  8643. if (!empty($props_list)) {
  8644. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8645. }
  8646. }
  8647. // 构建美术风格参考
  8648. $art_style_ref = '';
  8649. if (!empty($art_style)) {
  8650. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8651. }
  8652. // 构建内容简介参考
  8653. $intro_ref = '';
  8654. if (!empty($intro)) {
  8655. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8656. }
  8657. // 构建完整的AI提示词
  8658. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8659. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8660. $user_prompt .= $intro_ref;
  8661. $user_prompt .= $art_style_ref;
  8662. $user_prompt .= $reference_content;
  8663. // $user_prompt .= $roles_ref;
  8664. // $user_prompt .= $scenes_ref;
  8665. $system_prompt = "\n\n【强制要求】\n";
  8666. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8667. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8668. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8669. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8670. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8671. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8672. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8673. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8674. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8675. ###分段剧本
  8676. 片段数量:8
  8677. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8678. ##片段1
  8679. 时长:12s
  8680. 分镜1
  8681. 出场角色:刀疤脸
  8682. 场景:边境小镇街道
  8683. 出场道具:酒杯-高脚杯
  8684. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8685. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8686. 配音台词:
  8687. 背景音效:
  8688. 分镜2
  8689. 出场角色:刀疤脸
  8690. 场景:悦来酒馆
  8691. 出场道具:酒杯-高脚杯
  8692. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8693. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8694. 配音台词:
  8695. 背景音效:
  8696. 分镜3
  8697. 出场角色:刀疤脸
  8698. 场景:悦来酒馆
  8699. 出场道具:酒杯-高脚杯
  8700. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8701. 运镜:从中景推向令牌特写。
  8702. 配音台词:
  8703. 背景音效:
  8704. 分镜4
  8705. 出场角色:刀疤脸
  8706. 场景:悦来酒馆
  8707. 出场道具:酒杯-高脚杯
  8708. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8709. 运镜:极速推向酒水溅起的瞬间。
  8710. 配音台词:
  8711. 背景音效:
  8712. 分镜5
  8713. 出场角色:刀疤脸
  8714. 场景:悦来酒馆
  8715. 出场道具:酒杯-高脚杯
  8716. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8717. 运镜:固定机位,利用倾斜构图制造压迫感。
  8718. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8719. 背景音效:";
  8720. // 获取模型配置
  8721. $model = getProp($data, 'model');
  8722. if (!$model) {
  8723. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8724. }
  8725. // 验证模型是否在可用模型表中
  8726. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8727. $model = 'deepseek-v4-pro';
  8728. }
  8729. // 模型兼容性处理
  8730. $thinkingMode = 'disabled';
  8731. $reasoningEffort = 'high';
  8732. if ($model === 'deepseek-chat') {
  8733. $model = 'deepseek-v4-flash';
  8734. $thinkingMode = 'disabled';
  8735. } elseif ($model === 'deepseek-reasoner') {
  8736. $model = 'deepseek-v4-flash';
  8737. $thinkingMode = 'enabled';
  8738. }
  8739. // 构建消息
  8740. $messages = [
  8741. [
  8742. 'role' => 'system',
  8743. 'content' => $system_prompt
  8744. ],
  8745. [
  8746. 'role' => 'user',
  8747. 'content' => $user_prompt
  8748. ]
  8749. ];
  8750. // dd($messages);
  8751. // 构建请求参数
  8752. $post_data = [
  8753. 'model' => $model,
  8754. 'messages' => $messages,
  8755. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8756. 'frequency_penalty' => 0,
  8757. 'presence_penalty' => 0,
  8758. 'response_format' => ['type' => 'text'],
  8759. 'thinking' => ['type' => $thinkingMode],
  8760. 'stream' => false // 非流式输出
  8761. ];
  8762. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8763. // 调用AI生成新的分段剧本
  8764. try {
  8765. $fullContent = '';
  8766. $usage = [];
  8767. // 根据模型类型选择调用方法
  8768. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8769. // DeepSeek 官方模型使用 DeepSeek API
  8770. $chatResult = $this->chatOnly($post_data);
  8771. } else if (in_array($model, $this->gpt_text_models)) {
  8772. // GPT 模型使用 TokenRouter API
  8773. $chatResult = $this->gpt54ChatOnly($post_data);
  8774. } else {
  8775. // 其他模型使用火山引擎API
  8776. $chatResult = $this->volcEngineChatCompletion($post_data);
  8777. }
  8778. if (is_array($chatResult)) {
  8779. $fullContent = $chatResult['fullContent'] ?? '';
  8780. $usage = $chatResult['usage'] ?? [];
  8781. }
  8782. $generated_content = $fullContent;
  8783. if (empty($generated_content)) {
  8784. Utils::throwError('20003:AI生成内容为空,请重试');
  8785. }
  8786. // 解析生成的内容 - 按片段分割
  8787. $parsed_segments = [];
  8788. // 先在开头添加换行符,确保第1片段也能被正确分割
  8789. $normalizedText = "\n" . $generated_content;
  8790. $parts = preg_split('/\n\s*##/', $normalizedText);
  8791. foreach ($parts as $part) {
  8792. $part = trim($part);
  8793. if (empty($part)) continue;
  8794. // 匹配"片段X"格式
  8795. if (!preg_match('/^片段\d+/', $part)) {
  8796. continue;
  8797. }
  8798. // 分离标题和内容
  8799. $lines = explode("\n", $part, 2);
  8800. $actTitle = trim($lines[0]);
  8801. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8802. // 解析标题,提取序号
  8803. $actNumber = 0;
  8804. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8805. $actNumber = intval($segmentTitleMatch[1]);
  8806. } else {
  8807. $actNumber = count($parsed_segments) + 1;
  8808. }
  8809. // 提取时长(仅保留数字)
  8810. $actDuration = 0;
  8811. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8812. $actDurationStr = trim($actDurationMatch[1]);
  8813. // 提取数字部分(支持整数和小数)
  8814. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8815. $actDuration = (float)$numMatch[1];
  8816. }
  8817. }
  8818. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8819. // 只保留分镜内容,并确保分镜标记使用【】格式
  8820. $cleaned_content = '';
  8821. $content_lines = explode("\n", $actContent);
  8822. $is_capturing = false; // 标记是否开始捕获分镜内容
  8823. $count = 0;
  8824. foreach ($content_lines as $line) {
  8825. $trimmed_line = trim($line);
  8826. // 跳过时长和旁白音色行
  8827. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8828. continue;
  8829. }
  8830. // 检测是否是分镜开始
  8831. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8832. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8833. $count++;
  8834. $is_capturing = true;
  8835. // 如果没有【】,则添加
  8836. if (!preg_match('/^【/u', $trimmed_line)) {
  8837. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8838. }
  8839. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8840. }
  8841. // 如果已经开始捕获,则添加该行
  8842. if ($is_capturing && !empty($trimmed_line)) {
  8843. $cleaned_content .= $trimmed_line."\n";
  8844. }
  8845. }
  8846. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8847. $parsed_segments[] = [
  8848. 'act_number' => $actNumber,
  8849. 'act_title' => $actTitle,
  8850. 'act_duration' => $actDuration,
  8851. 'act_content' => $cleaned_content,
  8852. ];
  8853. }
  8854. if (empty($parsed_segments)) {
  8855. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8856. }
  8857. // 收集所有资产名称(角色、场景、道具)
  8858. $product_names = [];
  8859. // 收集角色名称
  8860. if (!empty($roles) && is_array($roles)) {
  8861. foreach ($roles as $role) {
  8862. $role_name = getProp($role, 'role', '');
  8863. if (!empty($role_name)) {
  8864. $product_names[] = $role_name;
  8865. }
  8866. }
  8867. }
  8868. // 收集场景名称
  8869. if (!empty($scenes) && is_array($scenes)) {
  8870. foreach ($scenes as $scene) {
  8871. $scene_name = getProp($scene, 'scene', '');
  8872. if (!empty($scene_name)) {
  8873. $product_names[] = $scene_name;
  8874. }
  8875. }
  8876. }
  8877. // 收集道具名称
  8878. if (!empty($props) && is_array($props)) {
  8879. foreach ($props as $prop) {
  8880. $prop_name = getProp($prop, 'prop', '');
  8881. if (!empty($prop_name)) {
  8882. $product_names[] = $prop_name;
  8883. }
  8884. }
  8885. }
  8886. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8887. $product_names = array_unique($product_names);
  8888. usort($product_names, function($a, $b) {
  8889. return mb_strlen($b) - mb_strlen($a);
  8890. });
  8891. // 处理每个片段的 act_show_content
  8892. foreach ($parsed_segments as &$segment) {
  8893. $act_content = getProp($segment, 'act_content', '');
  8894. if (empty($act_content)) {
  8895. $segment['act_show_content'] = '';
  8896. continue;
  8897. }
  8898. $processed_content = $act_content;
  8899. // 统一替换所有资产名称为 {资产名} 格式
  8900. // 使用占位符避免嵌套替换问题
  8901. $placeholder_map = [];
  8902. $placeholder_index = 0;
  8903. foreach ($product_names as $product_name) {
  8904. // 转义特殊字符
  8905. $escaped_product = preg_quote($product_name, '/');
  8906. // 检查是否匹配且未被 {} 包裹
  8907. $processed_content = preg_replace_callback(
  8908. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8909. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8910. // 使用唯一占位符
  8911. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8912. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8913. $placeholder_index++;
  8914. return $placeholder;
  8915. },
  8916. $processed_content
  8917. );
  8918. }
  8919. // 将所有占位符替换回实际内容
  8920. foreach ($placeholder_map as $placeholder => $replacement) {
  8921. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8922. }
  8923. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8924. $shot_counter = 0;
  8925. $processed_content = preg_replace_callback(
  8926. '/【(?:镜头|分镜)(\d+)】/u',
  8927. function($matches) use (&$shot_counter) {
  8928. $shot_counter++;
  8929. return '【镜头' . $shot_counter . '】';
  8930. },
  8931. $processed_content
  8932. );
  8933. $segment['act_show_content'] = $processed_content;
  8934. }
  8935. unset($segment); // 解除引用
  8936. // 保存到数据库
  8937. $now = date('Y-m-d H:i:s');
  8938. $saved_acts = []; // 用于记录保存后的片段信息
  8939. if ($act_id > 0) {
  8940. // 单个片段模式:更新单条记录
  8941. if (count($parsed_segments) > 0) {
  8942. $new_segment = $parsed_segments[0];
  8943. $update_data = [
  8944. 'act_content' => getProp($new_segment, 'act_content', ''),
  8945. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  8946. 'act_title' => getProp($new_segment, 'act_title', ''),
  8947. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  8948. 'updated_at' => $now,
  8949. ];
  8950. DB::table('mp_episode_segments')
  8951. ->where('id', $act_id)
  8952. ->update($update_data);
  8953. // 获取更新后的记录
  8954. $updated_act = DB::table('mp_episode_segments')
  8955. ->where('id', $act_id)
  8956. ->first();
  8957. if ($updated_act) {
  8958. $saved_acts[] = [
  8959. 'act_id' => $updated_act->id,
  8960. 'act_number' => $updated_act->act_number,
  8961. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  8962. 'act_content' => $updated_act->act_content,
  8963. 'act_show_content' => $updated_act->act_show_content,
  8964. 'video_url' => $updated_act->video_url ?? '',
  8965. 'video_duration' => $updated_act->video_duration ?? 0,
  8966. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  8967. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  8968. ];
  8969. }
  8970. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  8971. }
  8972. } else {
  8973. // 整个剧集模式:删除原有记录并批量保存新记录
  8974. DB::beginTransaction();
  8975. try {
  8976. // 删除原有的所有片段记录
  8977. DB::table('mp_episode_segments')
  8978. ->where('episode_id', $target_episode_id)
  8979. ->delete();
  8980. // 批量插入新的片段记录
  8981. $segments_to_insert = [];
  8982. foreach ($parsed_segments as $index => $segment) {
  8983. $act_number = $index + 1;
  8984. $segments_to_insert[] = [
  8985. 'anime_id' => $target_anime_id,
  8986. 'episode_id' => $target_episode_id,
  8987. 'episode_number' => $target_episode_number,
  8988. 'act_number' => $act_number,
  8989. 'act_title' => getProp($segment, 'act_title', ''),
  8990. 'act_duration' => getProp($segment, 'act_duration', 0),
  8991. 'act_content' => getProp($segment, 'act_content', ''),
  8992. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  8993. 'created_at' => $now,
  8994. 'updated_at' => $now,
  8995. ];
  8996. }
  8997. if (!empty($segments_to_insert)) {
  8998. DB::table('mp_episode_segments')->insert($segments_to_insert);
  8999. }
  9000. DB::commit();
  9001. // 查询保存后的所有片段记录
  9002. $saved_segments = DB::table('mp_episode_segments')
  9003. ->where('episode_id', $target_episode_id)
  9004. ->orderBy('act_number')
  9005. ->get();
  9006. foreach ($saved_segments as $saved_segment) {
  9007. $saved_acts[] = [
  9008. 'act_id' => $saved_segment->id,
  9009. 'act_number' => $saved_segment->act_number,
  9010. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9011. 'act_content' => $saved_segment->act_content,
  9012. 'act_show_content' => $saved_segment->act_show_content,
  9013. 'video_url' => $saved_segment->video_url ?? '',
  9014. 'video_duration' => $saved_segment->video_duration ?? 0,
  9015. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9016. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9017. ];
  9018. }
  9019. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9020. 'episode_id' => $target_episode_id,
  9021. 'segments_count' => count($segments_to_insert)
  9022. ]);
  9023. } catch (\Exception $e) {
  9024. DB::rollBack();
  9025. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9026. Utils::throwError('20003:保存失败,请重试');
  9027. }
  9028. }
  9029. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9030. return [
  9031. 'anime_id' => $target_anime_id,
  9032. 'episode_id' => $target_episode_id,
  9033. 'title' => getProp($episode, 'title', ''),
  9034. 'episode_number' => $target_episode_number,
  9035. 'is_generated' => getProp($episode, 'is_generated', 0),
  9036. 'acts' => $saved_acts,
  9037. ];
  9038. } catch (\Exception $e) {
  9039. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9040. throw $e;
  9041. }
  9042. }
  9043. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9044. {
  9045. $episode_arr = [
  9046. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9047. 'intro' => getProp($script_arr, 'intro'),
  9048. 'art_style' => getProp($script_arr, 'art_style'),
  9049. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9050. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9051. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9052. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9053. ];
  9054. if (empty($episode_arr['acts'])) {
  9055. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9056. if (!empty($fallback_episode_arr['acts'])) {
  9057. $episode_arr = array_merge($fallback_episode_arr, [
  9058. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9059. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9060. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9061. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9062. ]);
  9063. }
  9064. }
  9065. // if (!getProp($episode_arr, 'episode_title')) {
  9066. // $episode_title = '';
  9067. // $episodes = getProp($script_arr, 'episodes', []);
  9068. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9069. // $episode_title = '第1集:' . $episodes[0]['title'];
  9070. // }
  9071. // if (!$episode_title) {
  9072. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9073. // }
  9074. // $episode_arr['episode_title'] = $episode_title;
  9075. // }
  9076. return $episode_arr;
  9077. }
  9078. private function saveEpisodeVersionData(
  9079. int $anime_id,
  9080. int $episode_number,
  9081. array $episode_arr,
  9082. array $existing_roles,
  9083. array $existing_scenes,
  9084. array $existing_props,
  9085. $current_episode,
  9086. $base_episode,
  9087. bool $is_regenerate_version,
  9088. string $content,
  9089. string $now,
  9090. array $ref_products = []
  9091. ): array {
  9092. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9093. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9094. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9095. // 过滤掉关键字段为空的条目
  9096. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9097. return !empty($item['role'] ?? null);
  9098. }));
  9099. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9100. return !empty($item['scene'] ?? null);
  9101. }));
  9102. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9103. return !empty($item['prop'] ?? null);
  9104. }));
  9105. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9106. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9107. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9108. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9109. $ace_mode = getProp($anime, 'ace_mode');
  9110. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9111. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9112. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9113. $global_roles = is_array($global_roles) ? $global_roles : [];
  9114. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9115. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9116. $art_style_type = getProp($anime, 'art_style_type');
  9117. // 检查并创建 roles 的图片生成任务
  9118. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9119. // 检查并创建 scenes 的图片生成任务
  9120. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9121. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9122. if ($arr && is_array($arr)) {
  9123. $merged_roles = $arr['roles'];
  9124. $merged_scenes = $arr['scenes'];
  9125. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9126. }
  9127. // 确保数据是数组类型
  9128. if (!is_array($merged_roles)) {
  9129. dLog('deepseek')->error('merged_roles不是数组类型', [
  9130. 'type' => gettype($merged_roles),
  9131. 'value' => $merged_roles
  9132. ]);
  9133. $merged_roles = [];
  9134. }
  9135. if (!is_array($merged_scenes)) {
  9136. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9137. 'type' => gettype($merged_scenes),
  9138. 'value' => $merged_scenes
  9139. ]);
  9140. $merged_scenes = [];
  9141. }
  9142. if (!is_array($merged_props)) {
  9143. dLog('deepseek')->error('merged_props不是数组类型', [
  9144. 'type' => gettype($merged_props),
  9145. 'value' => $merged_props
  9146. ]);
  9147. $merged_props = [];
  9148. }
  9149. // 同步新出现的主体和场景到全局
  9150. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9151. $role_arr = [];
  9152. foreach ($merged_roles as $item) {
  9153. $role_arr[$item['role']] = $item;
  9154. }
  9155. $version_count = DB::table('mp_anime_episodes')
  9156. ->where('anime_id', $anime_id)
  9157. ->where('episode_number', $episode_number)
  9158. ->count('id');
  9159. $episode = [
  9160. 'anime_id' => $anime_id,
  9161. 'episode_number' => $episode_number,
  9162. 'title' => getProp($episode_arr, 'episode_title'),
  9163. 'content' => $content,
  9164. 'intro' => getProp($episode_arr, 'intro'),
  9165. 'art_style' => getProp($episode_arr, 'art_style'),
  9166. 'roles' => json_encode($merged_roles, 256),
  9167. 'scenes' => json_encode($merged_scenes, 256),
  9168. 'props' => json_encode($merged_props, 256),
  9169. 'generate_status' => '待执行',
  9170. 'generate_at' => $now,
  9171. 'is_default' => 1,
  9172. 'updated_at' => $now,
  9173. ];
  9174. $del_flag = false;
  9175. if ($is_regenerate_version) {
  9176. DB::table('mp_anime_episodes')
  9177. ->where('anime_id', $anime_id)
  9178. ->where('episode_number', $episode_number)
  9179. ->update(['is_default' => 0, 'updated_at' => $now]);
  9180. $episode['sequence'] = $version_count + 1;
  9181. $episode['created_at'] = $now;
  9182. $episode['cpid'] = Site::getCpid();
  9183. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9184. if (!$episode_id) {
  9185. Utils::throwError('20003:创建剧集版本失败');
  9186. }
  9187. } else {
  9188. $target_episode = $current_episode ?: $base_episode;
  9189. if ($target_episode) {
  9190. $episode_id = getProp($target_episode, 'id');
  9191. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9192. DB::table('mp_anime_episodes')
  9193. ->where('anime_id', $anime_id)
  9194. ->where('episode_number', $episode_number)
  9195. ->where('id', '<>', $episode_id)
  9196. ->update(['is_default' => 0, 'updated_at' => $now]);
  9197. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9198. if ($boolen === false) {
  9199. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9200. Utils::throwError('20003:分集内容保存失败');
  9201. }
  9202. $del_flag = true;
  9203. } else {
  9204. DB::table('mp_anime_episodes')
  9205. ->where('anime_id', $anime_id)
  9206. ->where('episode_number', $episode_number)
  9207. ->update(['is_default' => 0, 'updated_at' => $now]);
  9208. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9209. $episode['created_at'] = $now;
  9210. $episode['cpid'] = Site::getCpid();
  9211. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9212. if (!$episode_id) {
  9213. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9214. Utils::throwError('20003:分集内容保存失败');
  9215. }
  9216. }
  9217. }
  9218. $segments = [];
  9219. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9220. // 如果是第2集及以后,获取上一集的主体音色数据
  9221. $previous_roles_voice = [];
  9222. if ($episode_number >= 2) {
  9223. $previous_episode = DB::table('mp_anime_episodes')
  9224. ->where('anime_id', $anime_id)
  9225. ->where('episode_number', $episode_number - 1)
  9226. ->where('is_default', 1)
  9227. ->first();
  9228. if ($previous_episode) {
  9229. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9230. if (is_array($previous_roles)) {
  9231. foreach ($previous_roles as $prev_role) {
  9232. $role_name = getProp($prev_role, 'role');
  9233. if ($role_name) {
  9234. $previous_roles_voice[$role_name] = [
  9235. 'voice_name' => getProp($prev_role, 'voice_name'),
  9236. 'voice_type' => getProp($prev_role, 'voice_type'),
  9237. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9238. ];
  9239. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9240. if ($voice_prompt) {
  9241. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9242. }
  9243. }
  9244. }
  9245. }
  9246. }
  9247. }
  9248. // 将继承的音色数据同步到当前集的主体列表
  9249. if (!empty($previous_roles_voice)) {
  9250. foreach ($merged_roles as &$role) {
  9251. $role_name = getProp($role, 'role');
  9252. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9253. // 强制继承上一集的音色数据
  9254. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9255. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9256. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9257. // 如果上一集有 voice_prompt 则继承,否则跳过
  9258. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9259. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9260. }
  9261. }
  9262. }
  9263. unset($role); // 解除引用
  9264. // 更新 role_arr 以便后续使用
  9265. $role_arr = [];
  9266. foreach ($merged_roles as $item) {
  9267. $role_arr[$item['role']] = $item;
  9268. }
  9269. }
  9270. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9271. $emotion_list = array_flip($emotion_list);
  9272. foreach ($acts as $act) {
  9273. $act_segments = getProp($act, 'segments', []);
  9274. if (!is_array($act_segments)) {
  9275. continue;
  9276. }
  9277. if ((int)$ace_mode === 1) {
  9278. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9279. $merged_parts = [];
  9280. foreach ($act_segments as $seg) {
  9281. $seg_num = getProp($seg, 'segment_number');
  9282. $seg_content = getProp($seg, 'segment_content');
  9283. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9284. }
  9285. $act_content = implode("\n", $merged_parts);
  9286. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9287. $segments[] = [
  9288. 'anime_id' => $anime_id,
  9289. 'episode_id' => $episode_id,
  9290. 'episode_number' => $episode_number,
  9291. 'act_number' => getProp($act, 'act_number'),
  9292. 'act_title' => getProp($act, 'act_title'),
  9293. 'act_duration' => getProp($act, 'act_duration'),
  9294. 'act_content' => $act_content,
  9295. 'created_at' => $now,
  9296. 'updated_at' => $now
  9297. ];
  9298. } else {
  9299. foreach ($act_segments as $segment) {
  9300. $voice_actor = getProp($segment, 'voice_actor');
  9301. // 优先从上一集继承音色数据
  9302. $timbre_info = [];
  9303. if (isset($previous_roles_voice[$voice_actor])) {
  9304. // 从上一集继承音色数据
  9305. $timbre_info = $previous_roles_voice[$voice_actor];
  9306. } elseif (isset($role_arr[$voice_actor])) {
  9307. // 使用当前集的主体音色数据
  9308. $timbre_info = $role_arr[$voice_actor];
  9309. }
  9310. $voice_type = getProp($timbre_info, 'voice_type');
  9311. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9312. if ($timbre_emotion) {
  9313. $timbre_emotion = explode(',', $timbre_emotion);
  9314. } else {
  9315. $timbre_emotion = [];
  9316. }
  9317. $emotion = getProp($segment, 'emotion', '中性');
  9318. if (!in_array($emotion, $timbre_emotion)) {
  9319. $emotion = '中性';
  9320. }
  9321. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9322. $segments[] = [
  9323. 'anime_id' => $anime_id,
  9324. 'episode_id' => $episode_id,
  9325. 'episode_number' => $episode_number,
  9326. 'act_number' => getProp($act, 'act_number'),
  9327. 'act_title' => getProp($act, 'act_title'),
  9328. 'act_duration' => getProp($act, 'act_duration'),
  9329. 'segment_id' => getProp($segment, 'segment_id'),
  9330. 'segment_number' => getProp($segment, 'segment_number'),
  9331. 'segment_content' => getProp($segment, 'segment_content'),
  9332. 'description' => getProp($segment, 'description'),
  9333. 'composition' => getProp($segment, 'composition'),
  9334. 'camera_movement' => getProp($segment, 'camera_movement'),
  9335. 'voice_actor' => $voice_actor,
  9336. 'dialogue' => getProp($segment, 'dialogue'),
  9337. 'frame_type' => getProp($segment, 'frame_type'),
  9338. 'scene' => getProp($segment, 'scene'),
  9339. 'characters' => getProp($segment, 'characters'),
  9340. 'tail_frame' => getProp($segment, 'tail_frame'),
  9341. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9342. 'voice_type' => $voice_type,
  9343. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9344. 'emotion' => $emotion,
  9345. 'emotion_type' => $emotion_type,
  9346. 'gender' => getProp($segment, 'gender', '0'),
  9347. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9348. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9349. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9350. 'pitch' => getProp($segment, 'pitch', 0),
  9351. 'created_at' => $now,
  9352. 'updated_at' => $now
  9353. ];
  9354. }
  9355. }
  9356. }
  9357. if ($segments) {
  9358. if ($del_flag) {
  9359. DB::table('mp_episode_segments')
  9360. ->where('anime_id', $anime_id)
  9361. ->where('episode_id', $episode_id)
  9362. ->delete();
  9363. }
  9364. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9365. if (!$boolen) {
  9366. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9367. Utils::throwError('20003:分镜内容保存失败');
  9368. }
  9369. }
  9370. dLog('deepseek')->info('segments', $segments);
  9371. // ace_mode=1: acts 返回值按合并格式调整
  9372. if ((int)$ace_mode === 1) {
  9373. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9374. $act_map = [];
  9375. foreach ($table_act_data as $item) {
  9376. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9377. }
  9378. $restructured_acts = [];
  9379. foreach ($acts as $act) {
  9380. $act_segments = getProp($act, 'segments', []);
  9381. if (!is_array($act_segments)) {
  9382. continue;
  9383. }
  9384. $merged_parts = [];
  9385. foreach ($act_segments as $seg) {
  9386. $seg_num = getProp($seg, 'segment_number');
  9387. $seg_content = getProp($seg, 'segment_content');
  9388. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9389. }
  9390. $act_content = implode("\n", $merged_parts);
  9391. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9392. $restructured_acts[] = [
  9393. 'anime_id' => $anime_id,
  9394. 'episode_id' => $episode_id,
  9395. 'episode_number' => $episode_number,
  9396. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9397. 'act_number' => getProp($act, 'act_number'),
  9398. 'act_title' => getProp($act, 'act_title'),
  9399. 'act_duration' => getProp($act, 'act_duration'),
  9400. 'act_content' => $act_content,
  9401. 'created_at' => $now,
  9402. 'updated_at' => $now,
  9403. ];
  9404. }
  9405. $acts = $restructured_acts;
  9406. }
  9407. $episode['episode_id'] = $episode_id;
  9408. $episode['roles'] = $merged_roles;
  9409. $episode['scenes'] = $merged_scenes;
  9410. $episode['props'] = $merged_props;
  9411. $episode['acts'] = $acts;
  9412. return [
  9413. 'episode' => $episode,
  9414. 'episode_id' => $episode_id,
  9415. 'merged_roles' => $merged_roles,
  9416. 'merged_scenes' => $merged_scenes,
  9417. 'merged_props' => $merged_props,
  9418. ];
  9419. }
  9420. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9421. {
  9422. $content = '';
  9423. foreach ($items as $item) {
  9424. $name = trim((string)getProp($item, $nameKey));
  9425. if ($name === '' || $name === '旁白') {
  9426. continue;
  9427. }
  9428. $description = trim((string)getProp($item, 'description'));
  9429. $content .= $name . ': ' . $description;
  9430. if ($nameKey == 'role') {
  9431. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9432. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9433. $voice_name = trim(getProp($item, 'voice_name'));
  9434. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9435. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9436. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9437. }else {
  9438. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9439. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9440. }
  9441. $content .= "\n";
  9442. }
  9443. return trim($content);
  9444. }
  9445. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9446. if ((int)$sequence <= 0) {
  9447. return [];
  9448. }
  9449. $origin_content = '';
  9450. if ($content) {
  9451. $origin_content = '本集剧情内容:'.$content;
  9452. }else {
  9453. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9454. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9455. }
  9456. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9457. // 获取分集信息
  9458. $episode = DB::table('mp_anime_episodes')
  9459. ->where('anime_id', $animeId)
  9460. ->where('episode_number', $sequence)
  9461. ->where('is_default', 1)
  9462. ->first();
  9463. if (!$episode) {
  9464. return [];
  9465. }
  9466. $episode_id = getProp($episode, 'id');
  9467. $episode_number = getProp($episode, 'episode_number');
  9468. $title = getProp($episode, 'title');
  9469. $intro = getProp($episode, 'intro');
  9470. $art_style = getProp($episode, 'art_style');
  9471. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9472. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9473. // 组装纯文本内容
  9474. $content = '';
  9475. // 添加分集标题和梗概
  9476. $content .= "###第{$episode_number}集:{$title}\n\n";
  9477. $content .= "###故事梗概\n";
  9478. $content .= trim($intro) . "\n\n";
  9479. // 添加美术风格
  9480. $content .= "###美术风格\n";
  9481. $content .= trim($art_style) . "\n\n";
  9482. // 添加主体列表
  9483. $content .= "###主体列表\n";
  9484. $pangbai_voice_prompt = "";
  9485. foreach ($roles as $role) {
  9486. $name = getProp($role, 'role');
  9487. $description = getProp($role, 'description');
  9488. $pic_prompt = getProp($role, 'pic_prompt');
  9489. $voice_prompt = getProp($role, 'voice_prompt');
  9490. $voice_name = getProp($role, 'voice_name');
  9491. $content .= "{$name}: {$description}";
  9492. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9493. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9494. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9495. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9496. $content .= "\n";
  9497. }
  9498. $content .= "\n";
  9499. // 添加场景列表
  9500. $content .= "###场景列表\n";
  9501. foreach ($scenes as $scene) {
  9502. $name = getProp($scene, 'scene');
  9503. $description = getProp($scene, 'description');
  9504. $pic_prompt = getProp($scene, 'pic_prompt');
  9505. $content .= "{$name}: {$description}";
  9506. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9507. $content .= "\n";
  9508. }
  9509. $content .= "\n";
  9510. // 获取分镜信息
  9511. $segments = DB::table('mp_episode_segments')
  9512. ->where('anime_id', $animeId)
  9513. ->where('episode_id', $episode_id)
  9514. ->orderBy('segment_number')
  9515. ->get();
  9516. if ($segments && count($segments) > 0) {
  9517. if ((int)$ace_mode === 1) {
  9518. $content .= "###分段剧本\n";
  9519. // 获取片段数量
  9520. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9521. $content .= "片段数量:{$act_count}\n";
  9522. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9523. $content .= "\n";
  9524. }else {
  9525. $content .= "###分镜剧本\n";
  9526. }
  9527. // 按幕分组
  9528. $currentAct = null;
  9529. foreach ($segments as $segment) {
  9530. $act_number = getProp($segment, 'act_number');
  9531. $act_title = getProp($segment, 'act_title');
  9532. $act_duration = getProp($segment, 'act_duration');
  9533. $segment_number = getProp($segment, 'segment_number');
  9534. $segment_content = getProp($segment, 'segment_content');
  9535. $scene_description = getProp($segment, 'scene_description');
  9536. $scene_name = getProp($segment, 'scene_name');
  9537. $composition = getProp($segment, 'composition');
  9538. $camera_movement = getProp($segment, 'camera_movement');
  9539. $voice_type = getProp($segment, 'voice_type');
  9540. $characters = getProp($segment, 'characters');
  9541. $dialogue = getProp($segment, 'dialogue');
  9542. $frame_type = getProp($segment, 'frame_type');
  9543. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9544. // 判断是否是全能模式
  9545. if ((int)$ace_mode === 1) { // 全能模式
  9546. // 如果是新的分段,添加分段标题
  9547. if ($act_number !== $currentAct) {
  9548. $currentAct = $act_number;
  9549. $content .= "##{$act_title}\n";
  9550. $content .= "时长:{$act_duration}s\n";
  9551. }
  9552. }else {
  9553. // 如果是新的幕,添加幕标题
  9554. if ($act_number !== $currentAct) {
  9555. $currentAct = $act_number;
  9556. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9557. }
  9558. }
  9559. // 添加分镜信息
  9560. $content .= "分镜{$segment_number}\n";
  9561. $content .= "分镜内容:\n{$segment_content}\n";
  9562. // $content .= "画面描述:{$scene_description}\n";
  9563. // $content .= "场景:{$scene_name}\n";
  9564. // $content .= "构图设计:{$composition}\n";
  9565. // $content .= "运镜调度:{$camera_movement}\n";
  9566. // if (!empty($voice_type)) {
  9567. // $content .= "配音角色:{$voice_type}\n";
  9568. // }
  9569. // if (!empty($characters)) {
  9570. // $content .= "出镜角色:{$characters}\n";
  9571. // }
  9572. // if (!empty($dialogue)) {
  9573. // $content .= "台词内容:\"{$dialogue}\"\n";
  9574. // }
  9575. // $content .= "画面类型:{$frame_type}\n";
  9576. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9577. $content .= "\n";
  9578. }
  9579. }
  9580. $content = trim($content);
  9581. if($content) $content = "上集剧本内容:\n{$content}";
  9582. return [
  9583. [
  9584. 'role' => 'user',
  9585. 'content' => $origin_content
  9586. ],
  9587. [
  9588. 'role' => 'assistant',
  9589. 'content' => $content
  9590. ]
  9591. ];
  9592. }
  9593. private function getEpisodeChatMessages($animeId, $sequence): array
  9594. {
  9595. if ((int)$sequence <= 0) {
  9596. return [];
  9597. }
  9598. return DB::table('mp_anime_records')
  9599. ->where('anime_id', $animeId)
  9600. ->where('sequence', $sequence)
  9601. ->where('episode_id', '>', 0)
  9602. ->select('role', 'content')
  9603. ->orderBy('created_at')
  9604. ->orderBy('id')
  9605. ->get()
  9606. ->map(function ($value) {
  9607. return (array)$value;
  9608. })
  9609. ->toArray();
  9610. }
  9611. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9612. {
  9613. $existingMap = [];
  9614. foreach ($existingItems as $item) {
  9615. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9616. if ($itemKey === '') {
  9617. continue;
  9618. }
  9619. $existingMap[$itemKey] = $item;
  9620. }
  9621. if (!$generatedItems) {
  9622. return array_values($existingItems);
  9623. }
  9624. $merged = [];
  9625. foreach ($generatedItems as $item) {
  9626. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9627. if ($itemKey === '') {
  9628. continue;
  9629. }
  9630. if (isset($existingMap[$itemKey])) {
  9631. if (trim((string)getProp($item, 'description')) === '') {
  9632. $merged[] = $existingMap[$itemKey];
  9633. continue;
  9634. }
  9635. // 检查内容是否发生变化
  9636. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9637. if (!$isChanged) {
  9638. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9639. $mergedItem = [
  9640. $nameKey => trim((string)getProp($item, $nameKey)),
  9641. 'description' => trim((string)getProp($item, 'description')),
  9642. ];
  9643. // 如果有 pic_prompt,添加到合并项中
  9644. $picPrompt = getProp($item, 'pic_prompt');
  9645. if (!empty($picPrompt)) {
  9646. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9647. }
  9648. // 继承现有项的 URL
  9649. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9650. if (!empty($existingUrl)) {
  9651. $mergedItem['url'] = $existingUrl;
  9652. }
  9653. // 继承现有项的 task_id
  9654. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9655. if (!empty($existingTaskId)) {
  9656. $mergedItem['task_id'] = $existingTaskId;
  9657. }
  9658. // 继承现有项的 task_status
  9659. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9660. if (!empty($existingTaskStatus)) {
  9661. $mergedItem['task_status'] = $existingTaskStatus;
  9662. }
  9663. // 保留生成项的音色字段
  9664. $voiceName = getProp($item, 'voice_name');
  9665. if (!empty($voiceName)) {
  9666. $mergedItem['voice_name'] = $voiceName;
  9667. }
  9668. $voiceType = getProp($item, 'voice_type');
  9669. if (!empty($voiceType)) {
  9670. $mergedItem['voice_type'] = $voiceType;
  9671. }
  9672. $audioUrl = getProp($item, 'voice_audio_url');
  9673. if (!empty($audioUrl)) {
  9674. $mergedItem['voice_audio_url'] = $audioUrl;
  9675. }
  9676. $merged[] = $mergedItem;
  9677. } else {
  9678. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9679. $mergedItem = [
  9680. $nameKey => trim((string)getProp($item, $nameKey)),
  9681. 'description' => trim((string)getProp($item, 'description')),
  9682. ];
  9683. // 如果有 pic_prompt,添加到合并项中
  9684. $picPrompt = getProp($item, 'pic_prompt');
  9685. if (!empty($picPrompt)) {
  9686. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9687. }
  9688. // 保留生成项的音色字段
  9689. $voiceName = getProp($item, 'voice_name');
  9690. if (!empty($voiceName)) {
  9691. $mergedItem['voice_name'] = $voiceName;
  9692. }
  9693. $voiceType = getProp($item, 'voice_type');
  9694. if (!empty($voiceType)) {
  9695. $mergedItem['voice_type'] = $voiceType;
  9696. }
  9697. $audioUrl = getProp($item, 'voice_audio_url');
  9698. if (!empty($audioUrl)) {
  9699. $mergedItem['voice_audio_url'] = $audioUrl;
  9700. }
  9701. // 不继承 URL、task_id 和 task_status(重置状态)
  9702. $merged[] = $mergedItem;
  9703. }
  9704. } else {
  9705. // 新增项,保留生成项的所有字段
  9706. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9707. }
  9708. }
  9709. return $merged ?: array_values($existingItems);
  9710. }
  9711. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9712. {
  9713. $resetItem = [
  9714. $nameKey => trim((string)getProp($item, $nameKey)),
  9715. 'description' => trim((string)getProp($item, 'description')),
  9716. ];
  9717. // 保留指定的字段
  9718. foreach ($preserveFields as $field) {
  9719. $value = getProp($item, $field);
  9720. if (!empty($value)) {
  9721. $resetItem[$field] = $value;
  9722. }
  9723. }
  9724. return $resetItem;
  9725. }
  9726. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9727. {
  9728. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9729. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9730. if ($existingKey !== $generatedKey) {
  9731. return true;
  9732. }
  9733. // 比较 description 是否变化
  9734. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9735. return true;
  9736. }
  9737. // 比较 pic_prompt 是否变化
  9738. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9739. }
  9740. private function normalizeEpisodeResourceKey($value): string
  9741. {
  9742. $value = trim((string)$value);
  9743. if ($value === '') {
  9744. return '';
  9745. }
  9746. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9747. }
  9748. // 生成全局角色图片
  9749. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9750. $anime_id = getProp($data, 'anime_id');
  9751. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9752. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9753. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9754. $art_style = getProp($anime, 'art_style');
  9755. $update_flag = false;
  9756. foreach ($roles as &$role) {
  9757. $role_name = getProp($role, 'role');
  9758. if ($role_name == '旁白') continue;
  9759. // 优先使用 pic_prompt,如果没有则使用 description
  9760. $pic_prompt = getProp($role, 'pic_prompt');
  9761. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9762. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9763. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9764. // 参考图地址
  9765. $ref_img_url = getProp($role, 'url');
  9766. if (!$is_force && $ref_img_url) continue;
  9767. $update_flag = true;
  9768. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9769. try {
  9770. $params = [
  9771. 'prompt' => $description,
  9772. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9773. 'ref_img_urls' => []
  9774. ];
  9775. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9776. $task_id = $task->id;
  9777. if (!$task_id) {
  9778. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9779. }
  9780. $role['task_id'] = $task_id;
  9781. $role['task_status'] = 'processing';
  9782. } catch (\Exception $e) {
  9783. Utils::throwError("20003:" . $e->getMessage());
  9784. }
  9785. }
  9786. if (!$update_flag) return true;
  9787. // 保存角色信息
  9788. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9789. 'roles' => json_encode($roles, 256),
  9790. 'generate_status' => '执行中',
  9791. 'generate_at' => date('Y-m-d H:i:s'),
  9792. 'updated_at' => date('Y-m-d H:i:s')
  9793. ]);
  9794. if (!$boolen) {
  9795. Utils::throwError('20003:保存角色信息失败');
  9796. }
  9797. return $boolen;
  9798. }
  9799. // 生成全局场景图片
  9800. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9801. $anime_id = getProp($data, 'anime_id');
  9802. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9803. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9804. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9805. $art_style = getProp($anime, 'art_style');
  9806. $update_flag = false;
  9807. foreach ($scenes as &$scene) {
  9808. $scene_name = getProp($scene, 'scene');
  9809. // 优先使用 pic_prompt,如果没有则使用 description
  9810. $pic_prompt = getProp($scene, 'pic_prompt');
  9811. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9812. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9813. // 参考图地址
  9814. $ref_img_url = getProp($scene, 'url');
  9815. if (!$is_force && $ref_img_url) continue;
  9816. $update_flag = true;
  9817. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9818. try {
  9819. $params = [
  9820. 'prompt' => $description,
  9821. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9822. 'ref_img_urls' => []
  9823. ];
  9824. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9825. $task_id = $task->id;
  9826. if (!$task_id) {
  9827. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9828. }
  9829. $scene['task_id'] = $task_id;
  9830. $scene['task_status'] = 'processing';
  9831. } catch (\Exception $e) {
  9832. Utils::throwError("20003:" . $e->getMessage());
  9833. }
  9834. }
  9835. if (!$update_flag) return true;
  9836. // 保存角色信息
  9837. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9838. 'scenes' => json_encode($scenes, 256),
  9839. 'generate_status' => '执行中',
  9840. 'generate_at' => date('Y-m-d H:i:s'),
  9841. 'updated_at' => date('Y-m-d H:i:s')
  9842. ]);
  9843. if (!$boolen) {
  9844. Utils::throwError('20003:保存角色信息失败');
  9845. }
  9846. return $boolen;
  9847. }
  9848. // 生成分镜主体、场景和道具图片
  9849. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9850. $character_prefix = '';
  9851. $scene_prefix = '';
  9852. $prop_prefix = '';
  9853. if ($art_style_type) {
  9854. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9855. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9856. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9857. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9858. }
  9859. $update_flag = false;
  9860. // 获取上一集的roles、scenes和props数据
  9861. $prev_roles = [];
  9862. $prev_scenes = [];
  9863. $prev_props = [];
  9864. if ($episode_number > 1) {
  9865. $prev_episode = DB::table('mp_anime_episodes')
  9866. ->where('anime_id', $anime_id)
  9867. ->where('episode_number', $episode_number - 1)
  9868. ->where('is_default', 1)
  9869. ->first();
  9870. if ($prev_episode) {
  9871. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9872. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9873. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9874. dLog('deepseek')->info("获取上一集数据成功", [
  9875. 'anime_id' => $anime_id,
  9876. 'prev_episode_number' => $episode_number - 1,
  9877. 'prev_roles_count' => count($prev_roles),
  9878. 'prev_scenes_count' => count($prev_scenes),
  9879. 'prev_props_count' => count($prev_props)
  9880. ]);
  9881. }
  9882. }
  9883. // 处理角色图片生成
  9884. foreach ($roles as &$role) {
  9885. $role_name = getProp($role, 'role');
  9886. if ($role_name == '旁白') continue;
  9887. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9888. if (isset($ref_products[$role_name])) {
  9889. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9890. if ($role['url']) continue;
  9891. }
  9892. $role_description = getProp($role, 'description');
  9893. $role_pic_prompt = getProp($role, 'pic_prompt');
  9894. $role_url = getProp($role, 'url');
  9895. // 检查是否可以从上一集继承
  9896. $inherited = false;
  9897. if (!$is_force && !empty($prev_roles)) {
  9898. foreach ($prev_roles as $prev_role) {
  9899. $prev_role_name = getProp($prev_role, 'role');
  9900. $prev_description = getProp($prev_role, 'description');
  9901. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9902. $prev_url = getProp($prev_role, 'url');
  9903. $prev_task_id = getProp($prev_role, 'task_id');
  9904. $prev_task_status = getProp($prev_role, 'task_status');
  9905. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9906. if ($role_name == $prev_role_name
  9907. && $role_description == $prev_description
  9908. && $role_pic_prompt == $prev_pic_prompt
  9909. && !empty($prev_url)) {
  9910. $role['task_id'] = $prev_task_id;
  9911. $role['task_status'] = $prev_task_status;
  9912. $role['url'] = $prev_url;
  9913. $inherited = true;
  9914. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9915. 'anime_id' => $anime_id,
  9916. 'episode_number' => $episode_number,
  9917. 'task_id' => $prev_task_id,
  9918. 'url' => $prev_url
  9919. ]);
  9920. break;
  9921. }
  9922. }
  9923. }
  9924. // 如果已继承或已有url,跳过生成
  9925. if ($inherited || (!$is_force && $role_url)) {
  9926. continue;
  9927. }
  9928. // 优先使用 pic_prompt,如果没有则使用 description
  9929. $pic_prompt = getProp($role, 'pic_prompt');
  9930. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9931. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9932. $update_flag = true;
  9933. // 调用AIImageGenerationService的生成图片任务接口
  9934. try {
  9935. $params = [
  9936. 'prompt' => $description,
  9937. 'ref_img_urls' => []
  9938. ];
  9939. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9940. $task_id = $task->id;
  9941. if (!$task_id) {
  9942. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  9943. continue; // 不中断,继续处理其他角色
  9944. }
  9945. $role['task_id'] = $task_id;
  9946. $role['task_status'] = 'processing';
  9947. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  9948. 'anime_id' => $anime_id,
  9949. 'episode_number' => $episode_number,
  9950. 'task_id' => $task_id
  9951. ]);
  9952. } catch (\Exception $e) {
  9953. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  9954. // 不抛出异常,继续处理其他角色
  9955. }
  9956. }
  9957. // 处理场景图片生成
  9958. foreach ($scenes as &$scene) {
  9959. $scene_name = getProp($scene, 'scene');
  9960. $scene_description = getProp($scene, 'description');
  9961. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  9962. $scene_url = getProp($scene, 'url');
  9963. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  9964. if (isset($ref_products[$scene_name])) {
  9965. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  9966. if ($scene['url']) continue;
  9967. }
  9968. // 检查是否可以从上一集继承
  9969. $inherited = false;
  9970. if (!$is_force && !empty($prev_scenes)) {
  9971. foreach ($prev_scenes as $prev_scene) {
  9972. $prev_scene_name = getProp($prev_scene, 'scene');
  9973. $prev_description = getProp($prev_scene, 'description');
  9974. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  9975. $prev_url = getProp($prev_scene, 'url');
  9976. $prev_task_id = getProp($prev_scene, 'task_id');
  9977. $prev_task_status = getProp($prev_scene, 'task_status');
  9978. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  9979. if ($scene_name == $prev_scene_name
  9980. && $scene_description == $prev_description
  9981. && $scene_pic_prompt == $prev_pic_prompt
  9982. && !empty($prev_url)) {
  9983. $scene['task_id'] = $prev_task_id;
  9984. $scene['task_status'] = $prev_task_status;
  9985. $scene['url'] = $prev_url;
  9986. $inherited = true;
  9987. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  9988. 'anime_id' => $anime_id,
  9989. 'episode_number' => $episode_number,
  9990. 'task_id' => $prev_task_id,
  9991. 'url' => $prev_url
  9992. ]);
  9993. break;
  9994. }
  9995. }
  9996. }
  9997. // 如果已继承或已有url,跳过生成
  9998. if ($inherited || (!$is_force && $scene_url)) {
  9999. continue;
  10000. }
  10001. // 优先使用 pic_prompt,如果没有则使用 description
  10002. $pic_prompt = getProp($scene, 'pic_prompt');
  10003. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10004. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10005. $update_flag = true;
  10006. // 调用AIImageGenerationService的生成图片任务接口
  10007. try {
  10008. $params = [
  10009. 'prompt' => $description,
  10010. 'ref_img_urls' => []
  10011. ];
  10012. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10013. $task_id = $task->id;
  10014. if (!$task_id) {
  10015. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10016. continue; // 不中断,继续处理其他场景
  10017. }
  10018. $scene['task_id'] = $task_id;
  10019. $scene['task_status'] = 'processing';
  10020. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10021. 'anime_id' => $anime_id,
  10022. 'episode_number' => $episode_number,
  10023. 'task_id' => $task_id
  10024. ]);
  10025. } catch (\Exception $e) {
  10026. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10027. // 不抛出异常,继续处理其他场景
  10028. }
  10029. }
  10030. // 处理道具图片生成(逻辑与场景一致)
  10031. foreach ($props as &$prop) {
  10032. $prop_name = getProp($prop, 'prop');
  10033. $prop_description = getProp($prop, 'description');
  10034. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10035. $prop_url = getProp($prop, 'url');
  10036. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10037. if (isset($ref_products[$prop_name])) {
  10038. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10039. if ($prop['url']) continue;
  10040. }
  10041. // 检查是否可以从上一集继承
  10042. $inherited = false;
  10043. if (!$is_force && !empty($prev_props)) {
  10044. foreach ($prev_props as $prev_prop) {
  10045. $prev_prop_name = getProp($prev_prop, 'prop');
  10046. $prev_description = getProp($prev_prop, 'description');
  10047. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10048. $prev_url = getProp($prev_prop, 'url');
  10049. $prev_task_id = getProp($prev_prop, 'task_id');
  10050. $prev_task_status = getProp($prev_prop, 'task_status');
  10051. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10052. if ($prop_name == $prev_prop_name
  10053. && $prop_description == $prev_description
  10054. && $prop_pic_prompt == $prev_pic_prompt
  10055. && !empty($prev_url)) {
  10056. $prop['task_id'] = $prev_task_id;
  10057. $prop['task_status'] = $prev_task_status;
  10058. $prop['url'] = $prev_url;
  10059. $inherited = true;
  10060. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10061. 'anime_id' => $anime_id,
  10062. 'episode_number' => $episode_number,
  10063. 'task_id' => $prev_task_id,
  10064. 'url' => $prev_url
  10065. ]);
  10066. break;
  10067. }
  10068. }
  10069. }
  10070. // 如果已继承或已有url,跳过生成
  10071. if ($inherited || (!$is_force && $prop_url)) {
  10072. continue;
  10073. }
  10074. // 优先使用 pic_prompt,如果没有则使用 description
  10075. $pic_prompt = getProp($prop, 'pic_prompt');
  10076. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10077. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10078. $update_flag = true;
  10079. // 调用AIImageGenerationService的生成图片任务接口
  10080. try {
  10081. $params = [
  10082. 'prompt' => $description,
  10083. 'ref_img_urls' => []
  10084. ];
  10085. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10086. $task_id = $task->id;
  10087. if (!$task_id) {
  10088. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10089. continue; // 不中断,继续处理其他道具
  10090. }
  10091. $prop['task_id'] = $task_id;
  10092. $prop['task_status'] = 'processing';
  10093. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10094. 'anime_id' => $anime_id,
  10095. 'episode_number' => $episode_number,
  10096. 'task_id' => $task_id
  10097. ]);
  10098. } catch (\Exception $e) {
  10099. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10100. // 不抛出异常,继续处理其他道具
  10101. }
  10102. }
  10103. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10104. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10105. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10106. // // 保存剧集的角色和场景信息
  10107. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10108. // 'roles' => json_encode($roles, 256),
  10109. // 'scenes' => json_encode($scenes, 256),
  10110. // 'generate_status' => '执行中',
  10111. // 'generate_at' => date('Y-m-d H:i:s'),
  10112. // 'updated_at' => date('Y-m-d H:i:s')
  10113. // ]);
  10114. // if (!$boolen) {
  10115. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10116. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10117. // }
  10118. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10119. // 'episode_id' => $episode_id,
  10120. 'roles_count' => count($roles),
  10121. 'scenes_count' => count($scenes),
  10122. 'props_count' => count($props)
  10123. ]);
  10124. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10125. }
  10126. /**
  10127. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10128. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10129. *
  10130. * @param int $anime_id 动漫对话ID
  10131. * @param array $episode_roles 剧集角色数据
  10132. * @param array $episode_scenes 剧集场景数据
  10133. * @param array $episode_props 剧集道具数据
  10134. * @return bool
  10135. */
  10136. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10137. // 获取全局数据
  10138. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10139. if (!$anime) {
  10140. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10141. return false;
  10142. }
  10143. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10144. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10145. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10146. $roles_added = false;
  10147. $roles_updated = false;
  10148. $scenes_added = false;
  10149. $props_added = false;
  10150. // 处理角色同步
  10151. foreach ($episode_roles as $episode_role) {
  10152. $episode_role_name = getProp($episode_role, 'role');
  10153. $episode_description = getProp($episode_role, 'description');
  10154. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10155. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10156. // 跳过旁白
  10157. if ($episode_role_name == '旁白') {
  10158. continue;
  10159. }
  10160. // 检查全局中是否已存在相同的角色
  10161. $exists = false;
  10162. $global_role_index = -1;
  10163. foreach ($global_roles as $index => $global_role) {
  10164. $global_role_name = getProp($global_role, 'role');
  10165. $global_description = getProp($global_role, 'description');
  10166. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10167. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10168. if ($episode_role_name == $global_role_name
  10169. && $episode_description == $global_description
  10170. && $episode_pic_prompt == $global_pic_prompt) {
  10171. $exists = true;
  10172. $global_role_index = $index;
  10173. break;
  10174. }
  10175. }
  10176. // 如果不存在,则添加到全局
  10177. if (!$exists) {
  10178. $global_roles[] = $episode_role;
  10179. $roles_added = true;
  10180. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10181. 'anime_id' => $anime_id,
  10182. 'role' => $episode_role_name
  10183. ]);
  10184. } else {
  10185. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10186. if (!empty($episode_voice_prompt)) {
  10187. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10188. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10189. if ($global_voice_prompt !== $episode_voice_prompt) {
  10190. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10191. $roles_updated = true;
  10192. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10193. 'anime_id' => $anime_id,
  10194. 'role' => $episode_role_name,
  10195. 'voice_prompt' => $episode_voice_prompt
  10196. ]);
  10197. }
  10198. }
  10199. }
  10200. }
  10201. // 处理场景同步
  10202. foreach ($episode_scenes as $episode_scene) {
  10203. $episode_scene_name = getProp($episode_scene, 'scene');
  10204. $episode_description = getProp($episode_scene, 'description');
  10205. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10206. // 检查全局中是否已存在相同的场景
  10207. $exists = false;
  10208. foreach ($global_scenes as $global_scene) {
  10209. $global_scene_name = getProp($global_scene, 'scene');
  10210. $global_description = getProp($global_scene, 'description');
  10211. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10212. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10213. if ($episode_scene_name == $global_scene_name
  10214. && $episode_description == $global_description
  10215. && $episode_pic_prompt == $global_pic_prompt) {
  10216. $exists = true;
  10217. break;
  10218. }
  10219. }
  10220. // 如果不存在,则添加到全局
  10221. if (!$exists) {
  10222. $global_scenes[] = $episode_scene;
  10223. $scenes_added = true;
  10224. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10225. 'anime_id' => $anime_id,
  10226. 'scene' => $episode_scene_name
  10227. ]);
  10228. }
  10229. }
  10230. // 处理道具同步(逻辑与场景一致)
  10231. foreach ($episode_props as $episode_prop) {
  10232. $episode_prop_name = getProp($episode_prop, 'prop');
  10233. $episode_description = getProp($episode_prop, 'description');
  10234. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10235. // 检查全局中是否已存在相同的道具
  10236. $exists = false;
  10237. foreach ($global_props as $global_prop) {
  10238. $global_prop_name = getProp($global_prop, 'prop');
  10239. $global_description = getProp($global_prop, 'description');
  10240. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10241. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10242. if ($episode_prop_name == $global_prop_name
  10243. && $episode_description == $global_description
  10244. && $episode_pic_prompt == $global_pic_prompt) {
  10245. $exists = true;
  10246. break;
  10247. }
  10248. }
  10249. // 如果不存在,则添加到全局
  10250. if (!$exists) {
  10251. $global_props[] = $episode_prop;
  10252. $props_added = true;
  10253. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10254. 'anime_id' => $anime_id,
  10255. 'prop' => $episode_prop_name
  10256. ]);
  10257. }
  10258. }
  10259. // 如果有新增或更新,则更新全局数据
  10260. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10261. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10262. if ($roles_added || $roles_updated) {
  10263. $update_data['roles'] = json_encode($global_roles, 256);
  10264. }
  10265. if ($scenes_added) {
  10266. $update_data['scenes'] = json_encode($global_scenes, 256);
  10267. }
  10268. if ($props_added) {
  10269. $update_data['props'] = json_encode($global_props, 256);
  10270. }
  10271. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10272. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10273. 'anime_id' => $anime_id,
  10274. 'roles_added' => $roles_added,
  10275. 'roles_updated' => $roles_updated,
  10276. 'scenes_added' => $scenes_added,
  10277. 'props_added' => $props_added,
  10278. 'global_roles_count' => count($global_roles),
  10279. 'global_scenes_count' => count($global_scenes),
  10280. 'global_props_count' => count($global_props)
  10281. ]);
  10282. }
  10283. return true;
  10284. }
  10285. /**
  10286. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10287. *
  10288. * @param int $anime_id 动漫对话ID
  10289. * @param int $episode_id 分集ID
  10290. * @return bool
  10291. */
  10292. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10293. // 获取全局角色和场景数据
  10294. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10295. if (!$anime) {
  10296. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10297. return false;
  10298. }
  10299. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10300. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10301. // 获取指定的分集
  10302. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10303. if (!$episode) {
  10304. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10305. return false;
  10306. }
  10307. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10308. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10309. $roles_updated = false;
  10310. $scenes_updated = false;
  10311. // 继承角色的task_id、task_status和url
  10312. foreach ($episode_roles as &$episode_role) {
  10313. $episode_role_name = getProp($episode_role, 'role');
  10314. $episode_description = getProp($episode_role, 'description');
  10315. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10316. $episode_url = getProp($episode_role, 'url');
  10317. // 跳过旁白角色
  10318. if ($episode_role_name == '旁白') {
  10319. continue;
  10320. }
  10321. // 如果剧集中已有URL,跳过
  10322. if (!empty($episode_url)) {
  10323. continue;
  10324. }
  10325. // 遍历全局角色数据,查找匹配的角色
  10326. foreach ($global_roles as $global_role) {
  10327. $global_role_name = getProp($global_role, 'role');
  10328. $global_description = getProp($global_role, 'description');
  10329. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10330. $global_url = getProp($global_role, 'url');
  10331. $global_task_id = getProp($global_role, 'task_id');
  10332. $global_task_status = getProp($global_role, 'task_status');
  10333. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10334. if ($episode_role_name == $global_role_name
  10335. && $episode_description == $global_description
  10336. && $episode_pic_prompt == $global_pic_prompt) {
  10337. // 继承 task_id、task_status 和 url
  10338. if (!empty($global_task_id)) {
  10339. $episode_role['task_id'] = $global_task_id;
  10340. $episode_role['task_status'] = $global_task_status;
  10341. $roles_updated = true;
  10342. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10343. 'episode_id' => $episode_id,
  10344. 'role' => $episode_role_name,
  10345. 'task_id' => $global_task_id,
  10346. 'task_status' => $global_task_status
  10347. ]);
  10348. }
  10349. if (!empty($global_url)) {
  10350. $episode_role['url'] = $global_url;
  10351. $roles_updated = true;
  10352. dLog('deepseek')->info('剧集角色继承全局url', [
  10353. 'episode_id' => $episode_id,
  10354. 'role' => $episode_role_name,
  10355. 'url' => $global_url
  10356. ]);
  10357. }
  10358. break;
  10359. }
  10360. }
  10361. }
  10362. // 继承场景的task_id、task_status和url
  10363. foreach ($episode_scenes as &$episode_scene) {
  10364. $episode_scene_name = getProp($episode_scene, 'scene');
  10365. $episode_description = getProp($episode_scene, 'description');
  10366. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10367. $episode_url = getProp($episode_scene, 'url');
  10368. // 如果剧集中已有URL,跳过
  10369. if (!empty($episode_url)) {
  10370. continue;
  10371. }
  10372. // 遍历全局场景数据,查找匹配的场景
  10373. foreach ($global_scenes as $global_scene) {
  10374. $global_scene_name = getProp($global_scene, 'scene');
  10375. $global_description = getProp($global_scene, 'description');
  10376. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10377. $global_url = getProp($global_scene, 'url');
  10378. $global_task_id = getProp($global_scene, 'task_id');
  10379. $global_task_status = getProp($global_scene, 'task_status');
  10380. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10381. if ($episode_scene_name == $global_scene_name
  10382. && $episode_description == $global_description
  10383. && $episode_pic_prompt == $global_pic_prompt) {
  10384. // 继承 task_id、task_status 和 url
  10385. if (!empty($global_task_id)) {
  10386. $episode_scene['task_id'] = $global_task_id;
  10387. $episode_scene['task_status'] = $global_task_status;
  10388. $scenes_updated = true;
  10389. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10390. 'episode_id' => $episode_id,
  10391. 'scene' => $episode_scene_name,
  10392. 'task_id' => $global_task_id,
  10393. 'task_status' => $global_task_status
  10394. ]);
  10395. }
  10396. if (!empty($global_url)) {
  10397. $episode_scene['url'] = $global_url;
  10398. $scenes_updated = true;
  10399. dLog('deepseek')->info('剧集场景继承全局url', [
  10400. 'episode_id' => $episode_id,
  10401. 'scene' => $episode_scene_name,
  10402. 'url' => $global_url
  10403. ]);
  10404. }
  10405. break;
  10406. }
  10407. }
  10408. }
  10409. // 如果有更新,则保存到数据库
  10410. if ($roles_updated || $scenes_updated) {
  10411. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10412. if ($roles_updated) {
  10413. $update_data['roles'] = json_encode($episode_roles, 256);
  10414. }
  10415. if ($scenes_updated) {
  10416. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10417. }
  10418. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10419. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10420. 'episode_id' => $episode_id,
  10421. 'roles_updated' => $roles_updated,
  10422. 'scenes_updated' => $scenes_updated
  10423. ]);
  10424. }
  10425. return true;
  10426. }
  10427. public function chatChangeImg($data) {
  10428. $segment = getProp($data, 'segment');
  10429. $segment_content = getProp($segment, 'segment_content');
  10430. $prompt = getProp($data, 'prompt');
  10431. $ref_img = getProp($data, 'ref_img');
  10432. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10433. // 处理文本模型
  10434. $model = getProp($data, 'model');
  10435. if (!$model) {
  10436. // 用户没有输入,从anime表获取
  10437. $segment_id = getProp($segment, 'segment_id');
  10438. if ($segment_id) {
  10439. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10440. if ($episode_id) {
  10441. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10442. if ($anime_id) {
  10443. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10444. }
  10445. }
  10446. }
  10447. if (!$model) {
  10448. // anime表也没有,使用默认值
  10449. $model = 'doubao-seed-2-0-mini-260215';
  10450. }
  10451. }
  10452. // 验证模型是否在可用模型表中
  10453. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10454. $model = 'doubao-seed-2-0-mini-260215';
  10455. }
  10456. $messages[] =
  10457. [
  10458. 'role' => 'user',
  10459. 'content' => $question
  10460. ];
  10461. $post_data = [
  10462. 'model' => $model,
  10463. 'messages' => $messages,
  10464. // 'max_tokens' => 8192,
  10465. 'temperature' => 0.7,
  10466. 'frequency_penalty' => 0,
  10467. 'presence_penalty' => 0,
  10468. 'response_format' => ['type' => 'text'],
  10469. 'stream' => false // 是否启用流式输出
  10470. ];
  10471. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10472. // DeepSeek 官方模型使用 DeepSeek API
  10473. $chatResult = $this->chatOnly($post_data);
  10474. } else if (in_array($model, $this->gpt_text_models)) {
  10475. // GPT-5.4 模型使用 TokenRouter API
  10476. $chatResult = $this->gpt54ChatOnly($post_data);
  10477. } else {
  10478. // 其他模型使用火山引擎API
  10479. $chatResult = $this->volcEngineChatCompletion($post_data);
  10480. }
  10481. if (is_array($chatResult)) {
  10482. extract($chatResult);
  10483. }else {
  10484. Utils::throwError('20003: 接口调用失败!');
  10485. }
  10486. return [
  10487. 'type' => 'done',
  10488. // 'episode' => $episode,
  10489. 'answer' => $fullContent,
  10490. 'reasoning' => $fullReasoningContent,
  10491. 'usage' => $usage
  10492. ];
  10493. }
  10494. // 仅调用deepseek对话接口
  10495. private function chatOnly($post_data) {
  10496. $post_data['max_tokens'] = 300000;
  10497. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10498. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10499. $response = $result->getBody()->getContents();
  10500. $response_arr = json_decode($response, true);
  10501. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10502. $fullContent = '';
  10503. $fullReasoningContent = [];
  10504. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10505. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10506. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10507. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10508. }
  10509. return [
  10510. 'fullContent' => $fullContent,
  10511. 'fullReasoningContent' => $fullReasoningContent,
  10512. 'usage' => $usage
  10513. ];
  10514. }
  10515. // 仅调用 GPT-5.4 对话接口(非流式)
  10516. private function gpt54ChatOnly($post_data) {
  10517. $apiKey = env('GPT_54_API_KEY');
  10518. if (empty($apiKey)) {
  10519. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10520. }
  10521. // 先探活,服务不可用时自动重试
  10522. $this->ensureGptServiceAvailable();
  10523. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10524. $headers = [
  10525. 'Authorization' => 'Bearer ' . $apiKey,
  10526. 'Content-Type' => 'application/json'
  10527. ];
  10528. // 移除 thinking 参数,GPT-5.4 不支持
  10529. if (isset($post_data['thinking'])) {
  10530. unset($post_data['thinking']);
  10531. }
  10532. if (isset($post_data['reasoning_effort'])) {
  10533. unset($post_data['reasoning_effort']);
  10534. }
  10535. $post_data['max_completion_tokens'] = 100000;
  10536. // 确保 stream 为 false
  10537. $post_data['stream'] = false;
  10538. $maxRetries = $this->gptRetryTimes();
  10539. $interval = $this->gptRetryInterval();
  10540. $attempt = 0;
  10541. while (true) {
  10542. try {
  10543. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10544. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10545. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10546. 'json' => $post_data,
  10547. 'headers' => $headers
  10548. ]);
  10549. $response = $result->getBody()->getContents();
  10550. $response_arr = json_decode($response, true);
  10551. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10552. $fullContent = '';
  10553. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10554. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10555. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10556. }
  10557. return [
  10558. 'fullContent' => $fullContent,
  10559. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10560. 'usage' => $usage
  10561. ];
  10562. } catch (\Exception $e) {
  10563. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10564. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10565. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10566. throw $e;
  10567. }
  10568. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10569. 'retry' => $attempt + 1,
  10570. 'max_retries' => $maxRetries,
  10571. 'error' => $e->getMessage()
  10572. ]);
  10573. sleep($interval);
  10574. $attempt++;
  10575. }
  10576. }
  10577. }
  10578. private function splitContent($content) {
  10579. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10580. $chapters = [];
  10581. // 匹配章节标题格式:
  10582. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10583. // 2. 格式支持:
  10584. // - **第一集**
  10585. // - 第一集:
  10586. // - ###第1章 重生
  10587. // - ##第2章 相救
  10588. // - 第三章 共处一室
  10589. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10590. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10591. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10592. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10593. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10594. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10595. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10596. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10597. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10598. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10599. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10600. // 用正则找出所有章节标题的位置
  10601. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10602. $titleCount = count($matches[0]);
  10603. for ($i = 0; $i < $titleCount; $i++) {
  10604. // 获取当前章节标题
  10605. $titleLine = trim($matches[0][$i][0]);
  10606. // 去除标题开头的特殊符号
  10607. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10608. // 去除标题结尾的冒号和特殊符号
  10609. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10610. $cleanTitle = trim($cleanTitle);
  10611. // 获取当前标题的结束位置
  10612. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10613. // 获取下一个章节标题的开始位置(如果存在)
  10614. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10615. // 提取章节内容(从标题结束到下一个标题开始)
  10616. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10617. // 清理内容:去除前后空白和分隔线
  10618. $chapterContent = trim($chapterContent);
  10619. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10620. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10621. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10622. $chapters[] = [
  10623. 'title' => $cleanTitle,
  10624. 'content' => $chapterContent
  10625. ];
  10626. }
  10627. }
  10628. } else {
  10629. // 如果没有匹配到章节,返回整个内容
  10630. $chapters[] = [
  10631. 'title' => '',
  10632. 'content' => $content
  10633. ];
  10634. }
  10635. return $chapters;
  10636. }
  10637. public function getContentByBid($bid) {
  10638. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10639. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10640. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10641. $content = '';
  10642. foreach ($chapters as $chapter) {
  10643. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10644. }
  10645. return $content;
  10646. }
  10647. public function getContentByScriptId($script_id) {
  10648. $content = '';
  10649. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10650. if ($contents) {
  10651. $content = implode(PHP_EOL, $contents);
  10652. }else {
  10653. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10654. }
  10655. return $content;
  10656. }
  10657. /**
  10658. * 根据文件类型提取文本内容
  10659. *
  10660. * @param mixed $file 文件对象或文件路径
  10661. * @return string
  10662. */
  10663. public function extractFileContent($file) {
  10664. // 获取文件路径和扩展名
  10665. if (is_string($file)) {
  10666. $filePath = $file;
  10667. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10668. } else {
  10669. // Laravel UploadedFile 对象
  10670. $filePath = $file->getRealPath();
  10671. $extension = strtolower($file->getClientOriginalExtension());
  10672. }
  10673. $content = '';
  10674. switch ($extension) {
  10675. case 'txt':
  10676. $content = $this->extractTxtContent($filePath);
  10677. break;
  10678. case 'pdf':
  10679. $content = $this->extractPdfContent($filePath);
  10680. break;
  10681. case 'doc':
  10682. case 'docx':
  10683. $content = $this->extractWordContent($filePath);
  10684. break;
  10685. // case 'jpg':
  10686. // case 'jpeg':
  10687. // case 'png':
  10688. // case 'gif':
  10689. // case 'bmp':
  10690. // case 'webp':
  10691. // $content = $this->extractImageContent($filePath);
  10692. // break;
  10693. default:
  10694. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10695. }
  10696. return $content;
  10697. }
  10698. /**
  10699. * 提取 TXT 文件内容
  10700. */
  10701. private function extractTxtContent($filePath) {
  10702. if (!file_exists($filePath)) {
  10703. Utils::throwError('20003:文件不存在');
  10704. }
  10705. $content = file_get_contents($filePath);
  10706. // 尝试检测并转换编码
  10707. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10708. if ($encoding && $encoding !== 'UTF-8') {
  10709. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10710. }
  10711. return trim($content);
  10712. }
  10713. /**
  10714. * 提取 PDF 文件内容
  10715. */
  10716. private function extractPdfContent($filePath) {
  10717. if (!file_exists($filePath)) {
  10718. Utils::throwError('20003:文件不存在');
  10719. }
  10720. try {
  10721. $parser = new PdfParser();
  10722. $pdf = $parser->parseFile($filePath);
  10723. $content = $pdf->getText();
  10724. return trim($content);
  10725. } catch (\Exception $e) {
  10726. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10727. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10728. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10729. }
  10730. }
  10731. /**
  10732. * 提取 Word 文件内容(支持 doc 和 docx)
  10733. */
  10734. private function extractWordContent($filePath) {
  10735. if (!file_exists($filePath)) {
  10736. Utils::throwError('20003:文件不存在');
  10737. }
  10738. try {
  10739. $phpWord = WordIOFactory::load($filePath);
  10740. $content = '';
  10741. foreach ($phpWord->getSections() as $section) {
  10742. foreach ($section->getElements() as $element) {
  10743. $content .= $this->extractWordElementText($element);
  10744. }
  10745. }
  10746. return trim($content);
  10747. } catch (\Exception $e) {
  10748. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10749. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10750. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10751. }
  10752. }
  10753. /**
  10754. * 递归提取 Word 元素中的文本
  10755. */
  10756. private function extractWordElementText($element) {
  10757. $text = '';
  10758. if (method_exists($element, 'getText')) {
  10759. $text .= $element->getText() . "\n";
  10760. } elseif (method_exists($element, 'getElements')) {
  10761. foreach ($element->getElements() as $childElement) {
  10762. $text .= $this->extractWordElementText($childElement);
  10763. }
  10764. }
  10765. return $text;
  10766. }
  10767. /**
  10768. * 提取图片内容(使用火山引擎 OCR)
  10769. */
  10770. private function extractImageContent($filePath) {
  10771. if (!file_exists($filePath)) {
  10772. Utils::throwError('20003:文件不存在');
  10773. }
  10774. try {
  10775. // 读取图片并转换为 base64
  10776. $imageData = file_get_contents($filePath);
  10777. $base64Image = base64_encode($imageData);
  10778. // 调用火山引擎 OCR 服务
  10779. $content = $this->callVolcEngineOCR($base64Image);
  10780. return trim($content);
  10781. } catch (\Exception $e) {
  10782. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10783. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10784. Utils::throwError('20003:图片识别失败');
  10785. }
  10786. }
  10787. /**
  10788. * 调用火山引擎 OCR 服务识别图片文字
  10789. *
  10790. * @param string $base64Image base64 编码的图片数据
  10791. * @return string 识别的文字内容
  10792. */
  10793. private function callVolcEngineOCR($base64Image) {
  10794. $method = 'POST';
  10795. $service = 'cv';
  10796. $host = 'visual.volcengineapi.com';
  10797. $region = env('VOLC_REGION', 'cn-north-1');
  10798. $access_key = env('VOLC_AK');
  10799. $secret_key = env('VOLC_SK');
  10800. $action = 'OCRNormal';
  10801. $version = '2020-08-26';
  10802. if (!$access_key || !$secret_key) {
  10803. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10804. }
  10805. // 请求体
  10806. $body = json_encode([
  10807. 'image_base64' => $base64Image
  10808. ]);
  10809. // 生成签名
  10810. $headers = $this->getVolcEngineSignHeaders(
  10811. $method, $service, $host, $region,
  10812. "Action={$action}&Version={$version}",
  10813. $access_key, $secret_key, $body
  10814. );
  10815. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10816. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10817. 'headers' => $headers,
  10818. 'body' => $body
  10819. ]);
  10820. $response_arr = json_decode($response->getBody()->getContents(), true);
  10821. // 提取识别的文字
  10822. $textLines = [];
  10823. if (isset($response_arr['data']['line_texts'])) {
  10824. $textLines = $response_arr['data']['line_texts'];
  10825. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10826. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10827. if (isset($info['text'])) {
  10828. $textLines[] = $info['text'];
  10829. }
  10830. }
  10831. }
  10832. if (empty($textLines)) {
  10833. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10834. return '';
  10835. }
  10836. return implode("\n", $textLines);
  10837. }
  10838. /**
  10839. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10840. */
  10841. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10842. $contentType = 'application/json';
  10843. $accept = 'application/json';
  10844. // 获取当前UTC时间
  10845. $t = new DateTime('now', new DateTimeZone('UTC'));
  10846. $xDate = $t->format('Ymd\THis\Z');
  10847. $dateStamp = $t->format('Ymd');
  10848. // 计算 body 的 sha256 哈希
  10849. $payloadHash = hash('sha256', $body);
  10850. // 1. 拼接规范请求串
  10851. $canonicalUri = '/';
  10852. $canonicalQueryString = $queryString;
  10853. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10854. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10855. $canonicalRequest = implode("\n", [
  10856. $method,
  10857. $canonicalUri,
  10858. $canonicalQueryString,
  10859. $canonicalHeaders,
  10860. $signedHeaders,
  10861. $payloadHash
  10862. ]);
  10863. // 2. 拼接待签名字符串
  10864. $algorithm = 'HMAC-SHA256';
  10865. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10866. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10867. $stringToSign = implode("\n", [
  10868. $algorithm,
  10869. $xDate,
  10870. $credentialScope,
  10871. $hashedCanonicalRequest
  10872. ]);
  10873. // 3. 计算签名
  10874. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10875. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10876. // 4. 添加签名到请求头
  10877. $authorizationHeader = sprintf(
  10878. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10879. $algorithm,
  10880. $access_key,
  10881. $credentialScope,
  10882. $signedHeaders,
  10883. $signature
  10884. );
  10885. return [
  10886. 'Accept' => $accept,
  10887. 'Content-Type' => $contentType,
  10888. 'Host' => $host,
  10889. 'X-Date' => $xDate,
  10890. 'X-Content-Sha256'=> $payloadHash,
  10891. 'Authorization' => $authorizationHeader
  10892. ];
  10893. }
  10894. public function generateScriptWords($cid, $model = 'r1') {
  10895. ini_set('max_execution_time', 0);
  10896. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10897. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10898. // 模型兼容性处理和思考模式设置
  10899. $thinkingMode = 'disabled';
  10900. $reasoningEffort = 'high';
  10901. if ($model == 'r1') {
  10902. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10903. $thinkingMode = 'enabled';
  10904. } else {
  10905. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10906. $thinkingMode = 'disabled';
  10907. }
  10908. $messages = [
  10909. [
  10910. 'role' => 'system',
  10911. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10912. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10913. 2.非对话部分请全部用旁白角色代替
  10914. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10915. ],
  10916. [
  10917. 'role' => 'user',
  10918. 'content' => $content
  10919. ]
  10920. ];
  10921. $post_data = [
  10922. 'model' => $model,
  10923. 'messages' => $messages,
  10924. // 'max_tokens' => 8192,
  10925. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10926. 'frequency_penalty' => 0,
  10927. 'presence_penalty' => 0,
  10928. 'thinking' => ['type' => $thinkingMode],
  10929. 'response_format' => [
  10930. 'type' => 'text'
  10931. ],
  10932. 'stream' => false
  10933. ];
  10934. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10935. // 根据模型类型选择调用方法
  10936. $fullContent = '';
  10937. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10938. // DeepSeek 官方模型使用 DeepSeek API
  10939. $chatResult = $this->chatOnly($post_data);
  10940. } else if (in_array($model, $this->gpt_text_models)) {
  10941. // GPT-5.4 模型使用 TokenRouter API
  10942. $chatResult = $this->gpt54ChatOnly($post_data);
  10943. } else {
  10944. // 其他模型使用火山引擎API
  10945. $chatResult = $this->volcEngineChatCompletion($post_data);
  10946. }
  10947. if (is_array($chatResult)) {
  10948. $fullContent = $chatResult['fullContent'];
  10949. }
  10950. return $fullContent;
  10951. }
  10952. /**
  10953. * 智能化解析集数信息
  10954. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  10955. *
  10956. * @param string $prompt 用户输入的提示词
  10957. * @return int|null 解析出的集数,如果没有找到则返回null
  10958. */
  10959. private function extractEpisodeNumber($prompt)
  10960. {
  10961. if (empty($prompt)) {
  10962. return null;
  10963. }
  10964. // 定义各种可能的表达模式
  10965. $patterns = [
  10966. // 基本模式:改成N集、调整成N集、修改成N集
  10967. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  10968. // 扩展模式:分成N集、拆分成N集、分割成N集
  10969. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  10970. // 数量模式:N集、共N集、总共N集
  10971. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  10972. // 制作模式:制作N集、生成N集、创建N集
  10973. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  10974. // 计划模式:计划N集、预计N集、打算N集
  10975. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  10976. // 需要模式:需要N集、要N集
  10977. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  10978. // 中文数字模式:改成三集、调整成五集等
  10979. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  10980. // 英文数字模式
  10981. '/(?: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',
  10982. ];
  10983. // 中文数字转阿拉伯数字的映射
  10984. $chineseNumbers = [
  10985. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  10986. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  10987. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  10988. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  10989. ];
  10990. // 逐个尝试匹配模式
  10991. foreach ($patterns as $pattern) {
  10992. if (preg_match($pattern, $prompt, $matches)) {
  10993. $number = trim($matches[1]);
  10994. // 如果是中文数字,转换为阿拉伯数字
  10995. if (isset($chineseNumbers[$number])) {
  10996. return $chineseNumbers[$number];
  10997. }
  10998. // 如果是阿拉伯数字,直接返回
  10999. if (is_numeric($number)) {
  11000. $episodeNum = intval($number);
  11001. // 合理性检查:集数应该在1-100之间
  11002. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11003. return $episodeNum;
  11004. }
  11005. }
  11006. }
  11007. }
  11008. return null;
  11009. }
  11010. /**
  11011. * 调用火山引擎对话(Chat) API
  11012. *
  11013. * @param array $params 包含以下参数:
  11014. * - model: 模型ID(必填)
  11015. * - messages: 消息列表(必填)
  11016. * - stream: 是否流式输出(可选,默认false)
  11017. * - max_tokens: 最大输出token数(可选)
  11018. * - temperature: 采样温度(可选,默认1)
  11019. * - top_p: 核采样概率(可选,默认0.7)
  11020. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11021. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11022. * - stop: 停止词(可选)
  11023. * - tools: 工具列表(可选)
  11024. * @return array|Generator 非流式返回数组,流式返回生成器
  11025. */
  11026. public function volcEngineChatCompletion(array $params)
  11027. {
  11028. $apiKey = env('VOLC_AI_API_KEY');
  11029. if (empty($apiKey)) {
  11030. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11031. }
  11032. // 构建请求参数
  11033. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11034. $requestData = [
  11035. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11036. 'messages' => $params['messages'] ?? [],
  11037. ];
  11038. if (!in_array($originalModel, $this->valid_text_models)) {
  11039. Utils::throwError('20003:该模型不支持!');
  11040. }
  11041. // 添加可选参数
  11042. if (isset($params['stream'])) {
  11043. $requestData['stream'] = $params['stream'];
  11044. }
  11045. if (isset($params['stream_options'])) {
  11046. $requestData['stream_options'] = $params['stream_options'];
  11047. }
  11048. if (isset($params['max_tokens'])) {
  11049. $requestData['max_tokens'] = $params['max_tokens'];
  11050. }else if (isset($params['max_completion_tokens'])) {
  11051. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11052. }else {
  11053. $requestData['max_completion_tokens'] = 100000;
  11054. }
  11055. if (isset($params['temperature'])) {
  11056. $requestData['temperature'] = $params['temperature'];
  11057. }
  11058. if (isset($params['top_p'])) {
  11059. $requestData['top_p'] = $params['top_p'];
  11060. }
  11061. if (isset($params['frequency_penalty'])) {
  11062. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11063. }
  11064. if (isset($params['presence_penalty'])) {
  11065. $requestData['presence_penalty'] = $params['presence_penalty'];
  11066. }
  11067. if (isset($params['stop'])) {
  11068. $requestData['stop'] = $params['stop'];
  11069. }
  11070. if (isset($params['tools'])) {
  11071. $requestData['tools'] = $params['tools'];
  11072. }
  11073. if (isset($params['tool_choice'])) {
  11074. $requestData['tool_choice'] = $params['tool_choice'];
  11075. }
  11076. if (isset($params['response_format'])) {
  11077. $requestData['response_format'] = $params['response_format'];
  11078. }
  11079. if (isset($params['thinking'])) {
  11080. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11081. if (is_array($params['thinking'])) {
  11082. $requestData['thinking'] = $params['thinking'];
  11083. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11084. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11085. }
  11086. } else {
  11087. $requestData['thinking'] = ['type' => $params['thinking']];
  11088. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11089. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11090. }
  11091. }
  11092. } else {
  11093. $requestData['thinking'] = ['type' => 'disabled'];
  11094. }
  11095. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11096. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11097. try {
  11098. // 判断是否为流式输出
  11099. $isStream = isset($params['stream']) && $params['stream'] === true;
  11100. if ($isStream) {
  11101. // 流式输出
  11102. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11103. } else {
  11104. // 非流式输出
  11105. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11106. 'headers' => [
  11107. 'Authorization' => 'Bearer ' . $apiKey,
  11108. 'Content-Type' => 'application/json',
  11109. ],
  11110. 'json' => $requestData
  11111. ]);
  11112. $responseData = json_decode($response->getBody(), true);
  11113. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11114. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11115. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11116. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11117. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11118. }
  11119. return [
  11120. 'fullContent' => $fullContent,
  11121. 'fullReasoningContent' => $fullReasoningContent,
  11122. 'usage' => $usage
  11123. ];
  11124. }
  11125. } catch (\Exception $e) {
  11126. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11127. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11128. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11129. }
  11130. }
  11131. /**
  11132. * 火山引擎对话API流式输出
  11133. *
  11134. * @param Client $client HTTP客户端
  11135. * @param string $apiKey API密钥
  11136. * @param array $requestData 请求数据
  11137. * @return Generator
  11138. */
  11139. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11140. {
  11141. try {
  11142. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11143. 'headers' => [
  11144. 'Authorization' => 'Bearer ' . $apiKey,
  11145. 'Content-Type' => 'application/json',
  11146. ],
  11147. 'json' => $requestData,
  11148. 'stream' => true
  11149. ]);
  11150. $body = $response->getBody();
  11151. $buffer = '';
  11152. $fullContent = '';
  11153. $fullReasoningContent = '';
  11154. $usage = [];
  11155. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11156. // 逐行读取流式响应
  11157. while (!$body->eof()) {
  11158. $chunk = $body->read(1024);
  11159. $buffer .= $chunk;
  11160. // 按行分割
  11161. $lines = explode("\n", $buffer);
  11162. $buffer = array_pop($lines);
  11163. foreach ($lines as $line) {
  11164. $line = trim($line);
  11165. if (empty($line)) {
  11166. continue;
  11167. }
  11168. // 检查是否是SSE数据行
  11169. if (strpos($line, 'data: ') !== 0) {
  11170. continue;
  11171. }
  11172. $data = substr($line, 6);
  11173. if ($data === '[DONE]') {
  11174. dLog('deepseek')->info('收到结束标记');
  11175. break 2;
  11176. }
  11177. try {
  11178. $json = json_decode($data, true);
  11179. if (json_last_error() !== JSON_ERROR_NONE) {
  11180. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11181. continue;
  11182. }
  11183. if (isset($json['choices'][0]['delta'])) {
  11184. $delta = $json['choices'][0]['delta'];
  11185. // 处理思维链内容
  11186. if (isset($delta['reasoning_content'])) {
  11187. $fullReasoningContent .= $delta['reasoning_content'];
  11188. yield [
  11189. 'type' => 'reasoning',
  11190. 'content' => $delta['reasoning_content'],
  11191. 'full_reasoning' => $fullReasoningContent
  11192. ];
  11193. }
  11194. // 处理回答内容
  11195. if (isset($delta['content'])) {
  11196. $fullContent .= $delta['content'];
  11197. yield [
  11198. 'type' => 'content',
  11199. 'content' => $delta['content'],
  11200. ];
  11201. }
  11202. }
  11203. // 获取使用统计信息
  11204. if (isset($json['usage'])) {
  11205. $usage = $json['usage'];
  11206. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11207. }
  11208. } catch (\Exception $e) {
  11209. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11210. continue;
  11211. }
  11212. }
  11213. }
  11214. dLog('deepseek')->info('流式读取完成', [
  11215. 'content_length' => strlen($fullContent),
  11216. 'reasoning_length' => strlen($fullReasoningContent)
  11217. ]);
  11218. yield [
  11219. 'type' => 'done',
  11220. 'full_content' => $fullContent,
  11221. 'full_reasoning' => $fullReasoningContent,
  11222. 'usage' => $usage
  11223. ];
  11224. } catch (\Exception $e) {
  11225. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11226. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11227. throw $e;
  11228. }
  11229. }
  11230. /**
  11231. * 检查并创建图片生成任务
  11232. *
  11233. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11234. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11235. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11236. * @param string $art_style 美术风格
  11237. * @return array 更新后的资源列表
  11238. */
  11239. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11240. {
  11241. // 确保参数为数组
  11242. $merged_items = is_array($merged_items) ? $merged_items : [];
  11243. $global_items = is_array($global_items) ? $global_items : [];
  11244. // 构建全局资源映射表,用于快速查找
  11245. $global_map = [];
  11246. foreach ($global_items as $item) {
  11247. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11248. if ($itemKey === '') {
  11249. continue;
  11250. }
  11251. $global_map[$itemKey] = $item;
  11252. }
  11253. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11254. foreach ($merged_items as &$item) {
  11255. $item_name = getProp($item, $nameKey);
  11256. $item_description = getProp($item, 'description');
  11257. // $item_url = getProp($item, 'url');
  11258. // // 如果已有图片URL,跳过
  11259. // if (!empty($item_url)) {
  11260. // continue;
  11261. // }
  11262. // 如果是旁白角色,跳过
  11263. if ($nameKey === 'role' && $item_name === '旁白') {
  11264. continue;
  11265. }
  11266. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11267. if ($itemKey === '') {
  11268. continue;
  11269. }
  11270. $need_create_task = false;
  11271. // 条件1:在全局资源中找不到匹配的名称
  11272. if (!isset($global_map[$itemKey])) {
  11273. $need_create_task = true;
  11274. } else {
  11275. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11276. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11277. $current_description = trim((string)$item_description);
  11278. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11279. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11280. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11281. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11282. $need_create_task = true;
  11283. }
  11284. }
  11285. // 如果需要创建任务,调用图片生成服务
  11286. if ($need_create_task) {
  11287. try {
  11288. // 优先使用 pic_prompt,如果没有则使用 description
  11289. $pic_prompt = getProp($item, 'pic_prompt');
  11290. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11291. // 添加美术风格前缀
  11292. if ($art_style) {
  11293. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11294. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11295. $description = "{$prefix}:{$description}";
  11296. }
  11297. $params = [
  11298. 'prompt' => $description,
  11299. 'ref_img_urls' => []
  11300. ];
  11301. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11302. $task_id = $task->id;
  11303. if ($task_id) {
  11304. $item['task_id'] = $task_id;
  11305. $item['task_status'] = 'processing';
  11306. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11307. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11308. }
  11309. } catch (\Exception $e) {
  11310. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11311. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11312. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11313. // 不抛出异常,继续处理其他资源
  11314. }
  11315. }
  11316. }
  11317. return $merged_items;
  11318. }
  11319. /**
  11320. * 同步新出现的主体和场景到全局
  11321. *
  11322. * @param int $anime_id 动漫ID
  11323. * @param array $merged_roles 合并后的角色列表
  11324. * @param array $merged_scenes 合并后的场景列表
  11325. * @param array $global_roles 全局角色列表
  11326. * @param array $global_scenes 全局场景列表
  11327. * @return void
  11328. */
  11329. private function syncNewResourcesToGlobal(
  11330. int $anime_id,
  11331. array $merged_roles,
  11332. array $merged_scenes,
  11333. array $global_roles,
  11334. array $global_scenes
  11335. ): void {
  11336. // 构建全局角色映射表
  11337. $global_role_map = [];
  11338. foreach ($global_roles as $role) {
  11339. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11340. if ($roleKey !== '') {
  11341. $global_role_map[$roleKey] = $role;
  11342. }
  11343. }
  11344. // 构建全局场景映射表
  11345. $global_scene_map = [];
  11346. foreach ($global_scenes as $scene) {
  11347. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11348. if ($sceneKey !== '') {
  11349. $global_scene_map[$sceneKey] = $scene;
  11350. }
  11351. }
  11352. $need_update = false;
  11353. $new_global_roles = $global_roles;
  11354. $new_global_scenes = $global_scenes;
  11355. // 检查并添加新角色到全局
  11356. foreach ($merged_roles as $role) {
  11357. $role_name = getProp($role, 'role');
  11358. // 跳过旁白
  11359. if ($role_name === '旁白') {
  11360. continue;
  11361. }
  11362. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11363. if ($roleKey === '') {
  11364. continue;
  11365. }
  11366. // 如果全局中不存在该角色,添加到全局
  11367. if (!isset($global_role_map[$roleKey])) {
  11368. $new_global_roles[] = [
  11369. 'role' => $role_name,
  11370. 'description' => getProp($role, 'description', ''),
  11371. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11372. 'voice_name' => getProp($role, 'voice_name', ''),
  11373. 'voice_type' => getProp($role, 'voice_type', ''),
  11374. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11375. 'url' => getProp($role, 'url', ''),
  11376. 'task_id' => getProp($role, 'task_id', ''),
  11377. 'task_status' => getProp($role, 'task_status', ''),
  11378. ];
  11379. $global_role_map[$roleKey] = true; // 标记已添加
  11380. $need_update = true;
  11381. dLog('deepseek')->info("新角色同步到全局", [
  11382. 'anime_id' => $anime_id,
  11383. 'role' => $role_name,
  11384. 'task_id' => getProp($role, 'task_id', ''),
  11385. ]);
  11386. }
  11387. // else {
  11388. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11389. // $global_role = $global_role_map[$roleKey];
  11390. // if (is_array($global_role)) {
  11391. // $updated = false;
  11392. // $update_fields = [];
  11393. // // 检查描述是否更新
  11394. // $current_description = trim((string)getProp($role, 'description'));
  11395. // $global_description = trim((string)getProp($global_role, 'description'));
  11396. // if ($current_description !== '' && $current_description !== $global_description) {
  11397. // $updated = true;
  11398. // $update_fields[] = 'description';
  11399. // }
  11400. // // 检查pic_prompt是否更新
  11401. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11402. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11403. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11404. // $updated = true;
  11405. // $update_fields[] = 'pic_prompt';
  11406. // }
  11407. // // 检查图片任务信息是否更新
  11408. // $current_task_id = getProp($role, 'task_id');
  11409. // $global_task_id = getProp($global_role, 'task_id');
  11410. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11411. // $updated = true;
  11412. // $update_fields[] = 'task_id';
  11413. // }
  11414. // // 如果有更新,同步到全局
  11415. // if ($updated) {
  11416. // foreach ($new_global_roles as &$global_role_item) {
  11417. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11418. // if ($global_role_key === $roleKey) {
  11419. // if (in_array('description', $update_fields)) {
  11420. // $global_role_item['description'] = $current_description;
  11421. // }
  11422. // if (in_array('pic_prompt', $update_fields)) {
  11423. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11424. // }
  11425. // if (in_array('task_id', $update_fields)) {
  11426. // $global_role_item['task_id'] = $current_task_id;
  11427. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11428. // $global_role_item['url'] = getProp($role, 'url', '');
  11429. // }
  11430. // break;
  11431. // }
  11432. // }
  11433. // $need_update = true;
  11434. // dLog('deepseek')->info("角色信息更新到全局", [
  11435. // 'anime_id' => $anime_id,
  11436. // 'role' => $role_name,
  11437. // 'update_fields' => implode(',', $update_fields),
  11438. // ]);
  11439. // }
  11440. // }
  11441. // }
  11442. }
  11443. // 检查并添加新场景到全局
  11444. foreach ($merged_scenes as $scene) {
  11445. $scene_name = getProp($scene, 'scene');
  11446. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11447. if ($sceneKey === '') {
  11448. continue;
  11449. }
  11450. // 如果全局中不存在该场景,添加到全局
  11451. if (!isset($global_scene_map[$sceneKey])) {
  11452. $new_global_scenes[] = [
  11453. 'scene' => $scene_name,
  11454. 'description' => getProp($scene, 'description', ''),
  11455. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11456. 'url' => getProp($scene, 'url', ''),
  11457. 'task_id' => getProp($scene, 'task_id', ''),
  11458. 'task_status' => getProp($scene, 'task_status', ''),
  11459. ];
  11460. $global_scene_map[$sceneKey] = true; // 标记已添加
  11461. $need_update = true;
  11462. dLog('deepseek')->info("新场景同步到全局", [
  11463. 'anime_id' => $anime_id,
  11464. 'scene' => $scene_name,
  11465. 'task_id' => getProp($scene, 'task_id', ''),
  11466. ]);
  11467. }
  11468. // else {
  11469. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11470. // $global_scene = $global_scene_map[$sceneKey];
  11471. // if (is_array($global_scene)) {
  11472. // $updated = false;
  11473. // $update_fields = [];
  11474. // // 检查描述是否更新
  11475. // $current_description = trim((string)getProp($scene, 'description'));
  11476. // $global_description = trim((string)getProp($global_scene, 'description'));
  11477. // if ($current_description !== '' && $current_description !== $global_description) {
  11478. // $updated = true;
  11479. // $update_fields[] = 'description';
  11480. // }
  11481. // // 检查pic_prompt是否更新
  11482. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11483. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11484. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11485. // $updated = true;
  11486. // $update_fields[] = 'pic_prompt';
  11487. // }
  11488. // // 检查图片任务信息是否更新
  11489. // $current_task_id = getProp($scene, 'task_id');
  11490. // $global_task_id = getProp($global_scene, 'task_id');
  11491. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11492. // $updated = true;
  11493. // $update_fields[] = 'task_id';
  11494. // }
  11495. // // 如果有更新,同步到全局
  11496. // if ($updated) {
  11497. // foreach ($new_global_scenes as &$global_scene_item) {
  11498. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11499. // if ($global_scene_key === $sceneKey) {
  11500. // if (in_array('description', $update_fields)) {
  11501. // $global_scene_item['description'] = $current_description;
  11502. // }
  11503. // if (in_array('pic_prompt', $update_fields)) {
  11504. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11505. // }
  11506. // if (in_array('task_id', $update_fields)) {
  11507. // $global_scene_item['task_id'] = $current_task_id;
  11508. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11509. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11510. // }
  11511. // break;
  11512. // }
  11513. // }
  11514. // $need_update = true;
  11515. // dLog('deepseek')->info("场景信息更新到全局", [
  11516. // 'anime_id' => $anime_id,
  11517. // 'scene' => $scene_name,
  11518. // 'update_fields' => implode(',', $update_fields),
  11519. // ]);
  11520. // }
  11521. // }
  11522. // }
  11523. }
  11524. // 如果有新增或更新,更新数据库
  11525. if ($need_update) {
  11526. $update_data = [
  11527. 'roles' => json_encode($new_global_roles, 256),
  11528. 'scenes' => json_encode($new_global_scenes, 256),
  11529. 'updated_at' => date('Y-m-d H:i:s'),
  11530. ];
  11531. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11532. if ($result !== false) {
  11533. dLog('deepseek')->info("全局角色和场景更新成功", [
  11534. 'anime_id' => $anime_id,
  11535. 'roles_count' => count($new_global_roles),
  11536. 'scenes_count' => count($new_global_scenes),
  11537. ]);
  11538. } else {
  11539. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11540. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11541. }
  11542. }
  11543. }
  11544. }