DeepSeekService.php 279 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Facade\Site;
  5. use App\Libs\Utils;
  6. use GuzzleHttp\Client;
  7. use DateTime;
  8. use DateTimeZone;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Redis;
  13. use OSS\Core\OssException;
  14. use OSS\OssClient;
  15. use Smalot\PdfParser\Parser as PdfParser;
  16. use TCPDF;
  17. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  18. use Predis\Command\Traits\Get\Get;
  19. class DeepSeekService
  20. {
  21. private $url;
  22. private $api_key;
  23. private $sys_message;
  24. private $headers;
  25. private $valid_text_models;
  26. protected $aiImageGenerationService;
  27. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  28. $this->aiImageGenerationService = $aiImageGenerationService;
  29. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  30. $this->api_key = env('DEEPSEEK_API_KEY');
  31. $this->headers = [
  32. 'Authorization' => 'Bearer '.$this->api_key,
  33. 'Content-Type' => 'application/json; charset=UTF-8'
  34. ];
  35. // 火山引擎模型列表
  36. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  37. $this->sys_message = [
  38. 'role' => 'system',
  39. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  40. 强制要求:\n
  41. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  42. 2.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  43. 普通要求:\n
  44. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  45. 2.<分集剧本>要求包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。\n\n
  46. 示例如下:\n
  47. ###剧本名:西昆仑
  48. ###故事梗概
  49. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  50. ###剧本亮点
  51. 亮点1:绝境奇药,生死一线
  52. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  53. 亮点2:结拜兄妹,化解尴尬
  54. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  55. 亮点3:纤发夺命,情愫暗涌
  56. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  57. ###人物关系
  58. 阿雪与梁萧之间存在兄妹之情。
  59. ###核心矛盾
  60. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  61. ###主体列表
  62. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  63. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  64. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  65. 阴阳球:天地异宝,能化生精气,救人于危难。
  66. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  67. ###美术风格
  68. 基础画风风格词:厚涂古风
  69. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  70. ###场景列表
  71. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  72. ###分集剧本
  73. ##分集01
  74. 第1集: 第一集的标题
  75. 场景描述:地点、时间、场景
  76. 运镜:固定近距离
  77. 出场角色:男主、女主
  78. 台词内容:
  79. 女主: 女主对话
  80. 男主:男主对话
  81. 女主: 女主对话
  82. 男主: 男主对话
  83. ##分集02
  84. 第2集: 第二集的标题
  85. 场景描述:地点、时间、场景
  86. 运镜:固定近距离
  87. 出场角色:男主、女主
  88. 台词内容:
  89. 女主: 女主对话
  90. 男主:男主对话
  91. 女主: 女主对话
  92. 男主: 男主对话"
  93. ];
  94. }
  95. /**
  96. * 通用文生文方法 - 支持多模型流式输出和图片输入
  97. *
  98. * @param array $data 请求参数
  99. * @return \Generator 返回生成器,用于流式输出
  100. */
  101. public function generateText($data) {
  102. // 获取请求参数
  103. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  104. $messages = getProp($data, 'messages', []);
  105. $systemPrompt = getProp($data, 'system_prompt', '');
  106. $prompt = getProp($data, 'prompt', '');
  107. $images = getProp($data, 'images', []); // 支持多张图片
  108. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  109. // 如果没有提供messages,则根据system_prompt、content和images构建
  110. if (empty($messages)) {
  111. $messages = [];
  112. // 添加系统提示词
  113. if (!empty($systemPrompt)) {
  114. $messages[] = [
  115. 'role' => 'system',
  116. 'content' => $systemPrompt
  117. ];
  118. }
  119. // 构建用户消息内容(支持文本+图片)
  120. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  121. $userMessage = [
  122. 'role' => 'user',
  123. 'content' => []
  124. ];
  125. // 添加文本内容
  126. if (!empty($prompt)) {
  127. $userMessage['content'][] = [
  128. 'type' => 'text',
  129. 'text' => $prompt
  130. ];
  131. }
  132. // 处理上传的图片文件
  133. if (!empty($images)) {
  134. if (!is_array($images)) {
  135. $images = [$images];
  136. }
  137. foreach ($images as $image) {
  138. $imageBase64 = $this->processImageToBase64($image);
  139. if ($imageBase64) {
  140. $userMessage['content'][] = [
  141. 'type' => 'image_url',
  142. 'image_url' => [
  143. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  144. ]
  145. ];
  146. }
  147. }
  148. }
  149. // 处理图片URL
  150. if (!empty($imageUrls)) {
  151. if (!is_array($imageUrls)) {
  152. $imageUrls = [$imageUrls];
  153. }
  154. foreach ($imageUrls as $url) {
  155. if (!empty($url)) {
  156. $userMessage['content'][] = [
  157. 'type' => 'image_url',
  158. 'image_url' => [
  159. 'url' => $url
  160. ]
  161. ];
  162. }
  163. }
  164. }
  165. // 如果只有文本内容,简化为字符串格式
  166. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  167. $userMessage['content'] = $userMessage['content'][0]['text'];
  168. }
  169. $messages[] = $userMessage;
  170. }
  171. }
  172. // 验证messages不为空
  173. if (empty($messages)) {
  174. Utils::throwError('20003:请提供有效的对话内容');
  175. }
  176. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  177. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  178. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  179. if ($model === 'deepseek-chat') {
  180. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  181. $model = 'deepseek-v4-flash';
  182. $thinkingMode = 'disabled';
  183. } elseif ($model === 'deepseek-reasoner') {
  184. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  185. $model = 'deepseek-v4-flash';
  186. $thinkingMode = 'enabled';
  187. }
  188. // 构建请求参数
  189. $post_data = [
  190. 'model' => $model,
  191. 'messages' => $messages,
  192. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  193. 'temperature' => getProp($data, 'temperature', 1),
  194. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  195. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  196. 'thinking' => ['type' => $thinkingMode],
  197. 'stream' => true // 启用流式输出
  198. ];
  199. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  200. // 添加可选参数
  201. if (isset($data['top_p'])) {
  202. $post_data['top_p'] = $data['top_p'];
  203. }
  204. if (isset($data['response_format'])) {
  205. $post_data['response_format'] = $data['response_format'];
  206. }
  207. dLog('deepseek')->info('通用文生文请求参数', ['model' => $model, 'thinking' => $thinkingMode, 'messages_count' => count($messages)]);
  208. // 根据模型类型选择调用方法
  209. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  210. // DeepSeek 官方模型使用 DeepSeek API
  211. return $this->deepSeekStreamResponse($post_data);
  212. } else if (in_array($model, $this->valid_text_models)) {
  213. // 火山引擎支持的模型使用火山引擎 API
  214. return $this->volcEngineChatCompletion($post_data);
  215. } else {
  216. Utils::throwError('20003:不支持的模型: ' . $model);
  217. }
  218. }
  219. /**
  220. * 处理图片转换为base64
  221. *
  222. * @param mixed $image 图片文件对象或文件路径
  223. * @return string|null base64编码的图片数据
  224. */
  225. private function processImageToBase64($image) {
  226. try {
  227. // 获取文件路径
  228. if (is_string($image)) {
  229. $filePath = $image;
  230. } else {
  231. // Laravel UploadedFile 对象
  232. $filePath = $image->getRealPath();
  233. }
  234. if (!file_exists($filePath)) {
  235. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  236. return null;
  237. }
  238. // 验证是否为图片文件
  239. $imageInfo = @getimagesize($filePath);
  240. if ($imageInfo === false) {
  241. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  242. return null;
  243. }
  244. // 读取图片并转换为base64
  245. $imageData = file_get_contents($filePath);
  246. $base64Image = base64_encode($imageData);
  247. dLog('deepseek')->info('图片转换成功', [
  248. 'size' => strlen($imageData),
  249. 'type' => $imageInfo['mime']
  250. ]);
  251. return $base64Image;
  252. } catch (\Exception $e) {
  253. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  254. return null;
  255. }
  256. }
  257. private function getArtStylePromptMappings(): array
  258. {
  259. return [
  260. '日系动漫风格' => [
  261. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  262. 'prompt' => "日系动漫风格,线条干净流畅,色彩明亮柔和,人物精致,光影细腻,画面统一稳定"
  263. ],
  264. '国漫风格' => [
  265. 'aliases' => ['国漫风格', '国漫'],
  266. 'prompt' => "国漫风格,线条硬朗,人物成熟大气,色彩浓郁,光影对比强烈,整体画风统一,适合漫剧叙事"
  267. ],
  268. 'Q版卡通风格' => [
  269. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  270. 'prompt' => "Q版卡通风格,头大身小造型可爱,线条简洁,色彩明快,无复杂阴影,整体萌系干净统一"
  271. ],
  272. '简约扁平风格' => [
  273. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  274. 'prompt' => "简约扁平风格,大块纯色无渐变,线条简洁现代,画面干净清爽,不出现复杂纹理与光影"
  275. ],
  276. '古风仙侠风格' => [
  277. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  278. 'prompt' => "古风仙侠风格,汉服飘逸,云雾缭绕仙气空灵,色调清雅,光影柔和,国风氛围统一"
  279. ],
  280. '武侠风格' => [
  281. 'aliases' => ['武侠风格', '武侠'],
  282. 'prompt' => "武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态自然,色调沉稳大气"
  283. ],
  284. '新中式水墨风格' => [
  285. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  286. 'prompt' => "新中式水墨风格,淡墨渲染笔触自然,留白有意境,色调清雅,国风质感统一不杂乱"
  287. ],
  288. '写实插画风格' => [
  289. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  290. 'prompt' => "写实插画风格,真实人体比例,光影自然细腻,画面质感真实,不卡通不崩坏"
  291. ],
  292. '3D卡通风格' => [
  293. 'aliases' => ['3D卡通风格', '3D卡通'],
  294. 'prompt' => "3D卡通风格,立体建模质感柔和,造型圆润光滑,光影干净,整体风格统一不穿模"
  295. ],
  296. '条漫风格' => [
  297. 'aliases' => ['条漫风格', '条漫'],
  298. 'prompt' => "条漫风格,纵向分镜简洁,色彩清淡,适合上下滑动阅读,画面轻量化且整体统一"
  299. ],
  300. '赛博朋克风格' => [
  301. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  302. 'prompt' => "赛博朋克风格,霓虹灯光未来都市,暗色调科技感强,高对比光影,风格统一强烈"
  303. ],
  304. '暗黑悬疑风格' => [
  305. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  306. 'prompt' => "暗黑悬疑风格,低饱和冷色调,强阴影光线昏暗,氛围神秘压抑,整体色调统一"
  307. ],
  308. '治愈清新风格' => [
  309. 'aliases' => ['治愈清新风格', '治愈清新'],
  310. 'prompt' => "治愈清新风格,马卡龙柔和色系,柔光暖调,画面干净舒适,氛围温暖不杂乱"
  311. ],
  312. ];
  313. }
  314. public function getArtStylePromptByInput($inputArtStyle): string
  315. {
  316. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  317. if ($normalizedInput === '') {
  318. return '';
  319. }
  320. foreach ($this->getArtStylePromptMappings() as $mapping) {
  321. foreach ($mapping['aliases'] as $alias) {
  322. $normalizedAlias = $this->normalizeArtStyleInput($alias);
  323. if ($normalizedAlias === '') {
  324. continue;
  325. }
  326. if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  327. return $mapping['prompt'];
  328. }
  329. }
  330. }
  331. return '';
  332. }
  333. private function normalizeArtStyleInput($value): string
  334. {
  335. $value = trim((string)$value);
  336. if ($value === '') {
  337. return '';
  338. }
  339. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  340. return mb_strtolower($value, 'UTF-8');
  341. }
  342. private function replaceArtStyleSection(string $content, string $artStyle): string
  343. {
  344. if ($content === '' || $artStyle === '') {
  345. return $content;
  346. }
  347. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  348. if (!preg_match($pattern, $content)) {
  349. return $content;
  350. }
  351. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  352. }
  353. /**
  354. * DeepSeek流式输出处理方法
  355. *
  356. * @param array $post_data DeepSeek API请求参数
  357. * @return \Generator 返回生成器,用于流式输出
  358. */
  359. private function deepSeekStreamResponse($post_data) {
  360. $client = new Client(['timeout' => 1200, 'verify' => false]);
  361. $response = $client->post($this->url, [
  362. 'json' => $post_data,
  363. 'headers' => $this->headers,
  364. 'stream' => true // 启用流式响应
  365. ]);
  366. $body = $response->getBody();
  367. $fullContent = '';
  368. $fullReasoningContent = '';
  369. $usage = [];
  370. $buffer = '';
  371. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  372. // 逐行读取流式响应
  373. while (!$body->eof()) {
  374. $chunk = $body->read(1024); // 每次读取 1KB
  375. $buffer .= $chunk;
  376. // 按行分割
  377. $lines = explode("\n", $buffer);
  378. // 保留最后一个不完整的行
  379. $buffer = array_pop($lines);
  380. foreach ($lines as $line) {
  381. $line = trim($line);
  382. // 跳过空行
  383. if (empty($line)) {
  384. continue;
  385. }
  386. // 检查是否是 SSE 数据行
  387. if (strpos($line, 'data: ') !== 0) {
  388. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  389. continue;
  390. }
  391. $data = substr($line, 6); // 移除 "data: " 前缀
  392. if ($data === '[DONE]') {
  393. dLog('deepseek')->info('收到结束标记');
  394. break 2; // 跳出两层循环
  395. }
  396. try {
  397. $json = json_decode($data, true);
  398. if (json_last_error() !== JSON_ERROR_NONE) {
  399. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  400. continue;
  401. }
  402. if (isset($json['choices'][0]['delta'])) {
  403. $delta = $json['choices'][0]['delta'];
  404. // 处理思维链内容(仅 deepseek-reasoner 模型)
  405. if (isset($delta['reasoning_content'])) {
  406. $fullReasoningContent .= $delta['reasoning_content'];
  407. yield [
  408. 'type' => 'reasoning',
  409. 'content' => $delta['reasoning_content'],
  410. 'full_reasoning' => $fullReasoningContent
  411. ];
  412. }
  413. // 处理最终回答内容
  414. if (isset($delta['content'])) {
  415. $fullContent .= $delta['content'];
  416. yield [
  417. 'type' => 'content',
  418. 'content' => $delta['content'],
  419. ];
  420. }
  421. }
  422. // 获取使用统计信息
  423. if (isset($json['usage'])) {
  424. $usage = $json['usage'];
  425. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  426. }
  427. } catch (\Exception $e) {
  428. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  429. continue;
  430. }
  431. }
  432. }
  433. dLog('deepseek')->info('流式读取完成', [
  434. 'content_length' => strlen($fullContent),
  435. 'reasoning_length' => strlen($fullReasoningContent)
  436. ]);
  437. yield [
  438. 'type' => 'done',
  439. 'full_content' => $fullContent,
  440. 'full_reasoning' => $fullReasoningContent,
  441. 'usage' => $usage
  442. ];
  443. }
  444. // 与推理模型对话
  445. public function chatWithReasoner($data) {
  446. $content = getProp($data, 'content');
  447. $model = getProp($data, 'model', 'r1');
  448. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  449. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  450. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  451. if ($model == 'r1') {
  452. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  453. $thinkingMode = 'disabled';
  454. } else {
  455. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  456. $thinkingMode = 'disabled';
  457. }
  458. // 获取可选情感(根据音色可支持情感选)
  459. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  460. $emotion_list = [];
  461. foreach ($timbre_emotion as $emotion) {
  462. $tmp = explode(',', $emotion);
  463. $emotion_list = array_merge($emotion_list, $tmp);
  464. }
  465. $emotion_list = array_unique($emotion_list);
  466. $emotion_str = implode('、', $emotion_list);
  467. // // 获取可选情感
  468. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  469. // $emotion_str = implode('、', $emotion_list);
  470. // 是否启用情感
  471. $enable_emotion = getProp($data, 'enable_emotion', 0);
  472. if ($enable_emotion) {
  473. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  474. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  475. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  476. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  477. }else {
  478. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  479. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  480. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  481. }
  482. $messages = [
  483. [
  484. 'role' => 'system',
  485. 'content' => $sys_content
  486. ],
  487. [
  488. 'role' => 'user',
  489. 'content' => $content
  490. ]
  491. ];
  492. $post_data = [
  493. 'model' => $model,
  494. 'messages' => $messages,
  495. // 'max_tokens' => 8192,
  496. 'temperature' => 1,
  497. 'frequency_penalty' => 0,
  498. 'presence_penalty' => 0,
  499. 'thinking' => ['type' => $thinkingMode],
  500. 'response_format' => [
  501. 'type' => 'text'
  502. ],
  503. 'stream' => false
  504. ];
  505. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  506. // 根据模型类型选择调用方法
  507. $fullContent = '';
  508. $usage = [];
  509. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  510. // DeepSeek 官方模型使用 DeepSeek API
  511. $chatResult = $this->chatOnly($post_data);
  512. } else {
  513. // 其他模型使用火山引擎API
  514. $chatResult = $this->volcEngineChatCompletion($post_data);
  515. }
  516. if (is_array($chatResult)) {
  517. $fullContent = $chatResult['fullContent'];
  518. $usage = $chatResult['usage'];
  519. }
  520. // 处理获取到的剧本数据
  521. $script_content = handleScriptWords($fullContent, $enable_emotion);
  522. $result = [
  523. 'origin_content' => $fullContent,
  524. 'roles' => getProp($script_content, 'roles'),
  525. 'words' => getProp($script_content, 'words'),
  526. ];
  527. return $result;
  528. }
  529. public function resetParagraphAudio($data) {
  530. $bid = getProp($data, 'bid');
  531. $cid = getProp($data, 'cid');
  532. $version_id = getProp($data, 'version_id');
  533. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  534. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  535. 'generate_status' => '待制作',
  536. 'updated_at' => date('Y-m-d H:i:s')
  537. ]);
  538. }
  539. public function saveParagraphAudio($data) {
  540. $bid = getProp($data, 'bid');
  541. $cid = getProp($data, 'cid');
  542. $version_id = getProp($data, 'version_id');
  543. $sequence = getProp($data, 'sequence');
  544. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  545. // 获取所有情感
  546. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  547. $emotion_list = array_flip($emotion_list);
  548. // 获取音色支持情感
  549. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  550. $timbre_emotion = explode(',', $timbre_emotion);
  551. $emotion = getProp($data, 'emotion');
  552. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  553. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  554. $list = [
  555. 'bid' => $bid,
  556. 'cid' => $cid,
  557. 'version_id' => $version_id,
  558. 'sequence' => $sequence,
  559. 'role' => getProp($data, 'role'),
  560. 'gender' => getProp($data, 'gender'),
  561. 'text' => trim(getProp($data, 'text')),
  562. 'emotion' => $emotion,
  563. 'emotion_type' => $emotion_type,
  564. 'voice_type' => getProp($data, 'voice_type'),
  565. 'voice_name' => getProp($data, 'voice_name'),
  566. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  567. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  568. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  569. 'pitch' => getProp($data, 'pitch', 0),
  570. // 'paragraph_audio_url' => '',
  571. 'generate_status' => '制作中',
  572. 'error_msg' => '',
  573. 'updated_at' => date('Y-m-d H:i:s')
  574. ];
  575. $continue = false;
  576. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  577. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  578. $list['generate_status'] = '制作成功';
  579. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  580. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  581. $continue = true;
  582. }
  583. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  584. if ($id) {
  585. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  586. }else {
  587. $list['created_at'] = date('Y-m-d H:i:s');
  588. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  589. $boolen = $id ? true : false;
  590. }
  591. // 如果更新成功则加入查询队列
  592. if ($boolen) {
  593. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  594. Redis::sadd($redis_key, $id);
  595. }
  596. if ($boolen && !$continue) {
  597. $boolen = false;
  598. $client = new Client(['timeout' => 300, 'verify' => false]);
  599. // 根据ID通过API通知合成音频
  600. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  601. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  602. $response = $result->getBody()->getContents();
  603. $response_arr = json_decode($response, true);
  604. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  605. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  606. Log::info('通知火山生成段落音频失败: '.$error_msg);
  607. Utils::throwError('20003:通知火山生成段落音频失败');
  608. }
  609. $boolen = true;
  610. }
  611. return $boolen;
  612. }
  613. public function insertAudioEffect($data) {
  614. $audio_id = getProp($data, 'audio_id');
  615. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  616. $bid = getProp($chapter_audio, 'bid');
  617. $version_id = getProp($chapter_audio, 'version_id');
  618. $cid = getProp($chapter_audio, 'cid');
  619. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  620. $audio_effect_json = getProp($data, 'audio_effect_json');
  621. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  622. try {
  623. DB::beginTransaction();
  624. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  625. if (!$count) {
  626. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  627. }else {
  628. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  629. }
  630. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  631. 'audio_effect_status' => '添加中',
  632. 'audio_effect_json' => $audio_effect_json,
  633. 'updated_at' => date('Y-m-d H:i:s')
  634. ]);
  635. if (!$boolen1) {
  636. DB::rollBack();
  637. Utils::throwError('20003:更新生成数据失败');
  638. }
  639. $id = DB::table('mp_audio_tasks')->insertGetId([
  640. 'audio_id' => $audio_id,
  641. 'generate_status' => '执行中',
  642. 'generate_json' => json_encode([], 256),
  643. 'bid' => $bid,
  644. 'book_name' => getProp($chapter_audio, 'book_name'),
  645. 'version_id' => $version_id,
  646. 'version_name' => getProp($chapter_audio, 'version_name'),
  647. 'cid' => $cid,
  648. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  649. 'task_name' => $task_name,
  650. 'created_at' => date('Y-m-d H:i:s'),
  651. 'updated_at' => date('Y-m-d H:i:s')
  652. ]);
  653. if (!$id) {
  654. DB::rollBack();
  655. Utils::throwError('20003:创建任务失败');
  656. }
  657. }catch (\Exception $e) {
  658. DB::rollBack();
  659. Utils::throwError('20003:'.$e->getMessage());
  660. }
  661. DB::commit();
  662. $client = new Client(['timeout' => 300, 'verify' => false]);
  663. // 根据ID通过API通知合成音频
  664. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  665. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  666. $response = $result->getBody()->getContents();
  667. $response_arr = json_decode($response, true);
  668. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  669. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  670. Log::info('通知火山插入音效失败: '.$error_msg);
  671. Utils::throwError('20003:通知火山插入音效失败');
  672. }
  673. return true;
  674. }
  675. public function insertBgm($data) {
  676. $audio_id = getProp($data, 'audio_id');
  677. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  678. $bid = getProp($chapter_audio, 'bid');
  679. $version_id = getProp($chapter_audio, 'version_id');
  680. $cid = getProp($chapter_audio, 'cid');
  681. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  682. $bgm_json = getProp($data, 'bgm_json');
  683. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  684. if (!$bgm_json) {
  685. $bgm_json = getProp($data, 'audio_effect_json');
  686. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  687. }
  688. try {
  689. DB::beginTransaction();
  690. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  691. if (!$count) {
  692. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  693. }else {
  694. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  695. }
  696. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  697. 'bgm_status' => '添加中',
  698. 'bgm_json' => $bgm_json,
  699. 'updated_at' => date('Y-m-d H:i:s')
  700. ]);
  701. if (!$boolen1) {
  702. DB::rollBack();
  703. Utils::throwError('20003:更新生成数据失败');
  704. }
  705. $id = DB::table('mp_audio_tasks')->insertGetId([
  706. 'audio_id' => $audio_id,
  707. 'generate_status' => '执行中',
  708. 'generate_json' => json_encode([], 256),
  709. 'bid' => $bid,
  710. 'book_name' => getProp($chapter_audio, 'book_name'),
  711. 'version_id' => $version_id,
  712. 'version_name' => getProp($chapter_audio, 'version_name'),
  713. 'cid' => $cid,
  714. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  715. 'task_name' => $task_name,
  716. 'created_at' => date('Y-m-d H:i:s'),
  717. 'updated_at' => date('Y-m-d H:i:s')
  718. ]);
  719. if (!$id) {
  720. DB::rollBack();
  721. Utils::throwError('20003:创建任务失败');
  722. }
  723. }catch (\Exception $e) {
  724. DB::rollBack();
  725. Utils::throwError('20003:'.$e->getMessage());
  726. }
  727. DB::commit();
  728. $client = new Client(['timeout' => 300, 'verify' => false]);
  729. // 根据ID通过API通知合成音频
  730. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  731. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  732. $response = $result->getBody()->getContents();
  733. $response_arr = json_decode($response, true);
  734. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  735. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  736. Log::info('通知火山插入bgm失败: '.$error_msg);
  737. Utils::throwError('20003:通知火山插入bgm失败');
  738. }
  739. return true;
  740. }
  741. public function getParagraphAudios($data) {
  742. $bid = getProp($data, 'bid');
  743. $cid = getProp($data, 'cid');
  744. $version_id = getProp($data, 'version_id');
  745. $sequence = getProp($data, 'sequence');
  746. // 获取已生成的音频
  747. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  748. if ($sequence) $query->where('sequence', $sequence);
  749. $paragraph_audios = $query->orderBy('sequence')->get();
  750. $result = [];
  751. foreach($paragraph_audios as $item) {
  752. $result[] = [
  753. 'sequence' => getProp($item, 'sequence'),
  754. 'role' => getProp($item, 'role'),
  755. 'gender' => getProp($item, 'gender'),
  756. 'text' => trim(getProp($item, 'text')),
  757. 'emotion' => getProp($item, 'emotion'),
  758. 'emotion_type' => getProp($item, 'emotion_type'),
  759. 'voice_type' => getProp($item, 'voice_type'),
  760. 'voice_name' => getProp($item, 'voice_name'),
  761. 'speed_ratio' => getProp($item, 'speed_ratio'),
  762. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  763. 'emotion_scale' => getProp($item, 'emotion_scale'),
  764. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  765. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  766. ];
  767. }
  768. return $result;
  769. }
  770. // 新增合成任务
  771. public function addGenerateTask($data) {
  772. $bid = getProp($data, 'bid');
  773. $cid = getProp($data, 'cid');
  774. $version_id = getProp($data, 'version_id');
  775. $generate_json = getProp($data, 'generate_json');
  776. // 获取已生成的音频
  777. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  778. $paragraph_list = [];
  779. foreach($paragraph_audios as $item) {
  780. $paragraph_list[getProp($item, 'sequence')] = [
  781. 'role' => getProp($item, 'role'),
  782. 'gender' => getProp($item, 'gender'),
  783. 'text' => trim(getProp($item, 'text')),
  784. 'emotion' => getProp($item, 'emotion'),
  785. 'emotion_type' => getProp($item, 'emotion_type'),
  786. 'voice_type' => getProp($item, 'voice_type'),
  787. 'voice_name' => getProp($item, 'voice_name'),
  788. 'speed_ratio' => getProp($item, 'speed_ratio'),
  789. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  790. 'emotion_scale' => getProp($item, 'emotion_scale'),
  791. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  792. ];
  793. }
  794. // 更新角色-音色信息
  795. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  796. $existed_role_info = json_decode($existed_role_info, true);
  797. if (!$existed_role_info) $existed_role_info = [];
  798. // 获取情感信息
  799. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  800. $emotion_list = array_flip($emotion_list);
  801. // 获取音色对应情感组
  802. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  803. $timbre_emotion_list = [];
  804. foreach($timbre_emotions as $item) {
  805. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  806. }
  807. // 构造生成音频的json
  808. $words = json_decode($generate_json, true);
  809. // 最终合成前的参数组
  810. $mp_chapter_paragraph_audios = [];
  811. $sequence = 1;
  812. $complete_paragraph_sequences = [];
  813. foreach($words as &$word) {
  814. 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:参数格式有误');
  815. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  816. $role = getProp($word, 'role');
  817. $word['gender'] = (int)$word['gender'];
  818. // 判断音色对应情感是否支持,不支持则调整为中性
  819. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  820. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  821. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  822. if (isset($emotion_list[getProp($word, 'emotion')])) {
  823. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  824. }else {
  825. $word['emotion'] = '中性';
  826. $word['emotion_type'] = 'neutral';
  827. }
  828. $existed_role_info[$role] = [
  829. 'timbre_type' => $word['voice_type'],
  830. 'timbre_name' => $word['voice_name'],
  831. 'emotion' => $word['emotion'],
  832. 'emotion_type' => $word['emotion_type'],
  833. 'speed_ratio' => $word['speed_ratio'],
  834. 'loudness_ratio'=> $word['loudness_ratio'],
  835. 'emotion_scale' => $word['emotion_scale'],
  836. 'pitch' => $word['pitch']
  837. ];
  838. $word['paragraph_audio_url'] = '';
  839. // 判断生成参数是否相同,相同则直接使用已生成的音频
  840. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  841. // 如果音频存在并且参数都未改变则使用已生成的音频
  842. if (getProp($paragraph, 'paragraph_audio_url')) {
  843. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  844. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  845. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  846. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  847. // {
  848. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  849. // }
  850. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  851. }
  852. $tmp = $word;
  853. // 组装章节分句音频数据
  854. // $tmp['sequence'] = getProp($word, 'sequence');
  855. // $tmp['text'] = getProp($word, 'text');
  856. // $tmp['emotion'] = getProp($word, 'emotion');
  857. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  858. // $tmp['voice_name'] = getProp($word, 'voice_name');
  859. // $tmp['voice_type'] = getProp($word, 'voice_type');
  860. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  861. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  862. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  863. $tmp['bid'] = $bid;
  864. $tmp['version_id'] = $version_id;
  865. $tmp['cid'] = $cid;
  866. $tmp['sequence'] = $sequence;
  867. $tmp['created_at'] = date('Y-m-d H:i:s');
  868. $tmp['updated_at'] = date('Y-m-d H:i:s');
  869. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  870. $mp_chapter_paragraph_audios[] = $tmp;
  871. $complete_paragraph_sequences[] = $sequence;
  872. $sequence++;
  873. }
  874. $generate_json = json_encode($words, 256);
  875. // 判断是否有未生成字幕的段落
  876. $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();
  877. if ($no_subtitle_sequences) {
  878. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  879. }
  880. try {
  881. DB::beginTransaction();
  882. $role_info = json_encode($existed_role_info, 256);
  883. $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')]);
  884. if (!$boolen) {
  885. DB::rollBack();
  886. Utils::throwError('20003:更新角色信息失败');
  887. }
  888. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  889. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  890. if (!$count) {
  891. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  892. }else {
  893. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  894. }
  895. $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')]);
  896. if (!$boolen1) {
  897. DB::rollBack();
  898. Utils::throwError('20003:更新生成数据失败');
  899. }
  900. $id = DB::table('mp_audio_tasks')->insertGetId([
  901. 'audio_id' => getProp($chapter_audio, 'id'),
  902. 'generate_status' => '执行中',
  903. 'generate_json' => $generate_json,
  904. 'bid' => $bid,
  905. 'book_name' => getProp($chapter_audio, 'book_name'),
  906. 'version_id' => $version_id,
  907. 'version_name' => getProp($chapter_audio, 'version_name'),
  908. 'cid' => $cid,
  909. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  910. 'task_name' => $task_name,
  911. 'created_at' => date('Y-m-d H:i:s'),
  912. 'updated_at' => date('Y-m-d H:i:s')
  913. ]);
  914. if (!$id) {
  915. DB::rollBack();
  916. Utils::throwError('20003:创建任务失败');
  917. }
  918. // 删除不在段落序号范围内的其他数据
  919. if ($complete_paragraph_sequences) {
  920. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  921. }
  922. // // 删除章节分句音频数据并重新插入
  923. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  924. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  925. // if (!$boolen3) {
  926. // DB::rollBack();
  927. // Utils::throwError('20003:更新章节分句音频失败');
  928. // }
  929. } catch (\Exception $e) {
  930. DB::rollBack();
  931. Utils::throwError('20003:'.$e->getMessage());
  932. }
  933. DB::commit();
  934. // 通知火山生成音频
  935. $client = new Client(['timeout' => 300, 'verify' => false]);
  936. // 根据ID通过API通知合成音频
  937. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  938. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  939. $response = $result->getBody()->getContents();
  940. $response_arr = json_decode($response, true);
  941. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  942. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  943. Log::info('通知火山生成音频失败: '.$error_msg);
  944. Utils::throwError('20003:通知火山生成音频失败');
  945. }
  946. return true;
  947. }
  948. public function timbreList($data) {
  949. $gender = getProp($data, 'gender');
  950. $timbre_name = getProp($data, 'voice_name');
  951. $category_id = getProp($data, 'category_id');
  952. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  953. if ($gender) {
  954. $query->where('gender', $gender);
  955. }
  956. if ($timbre_name) {
  957. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  958. }
  959. if ($category_id) {
  960. $query->where(function ($query) use ($category_id) {
  961. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  962. });
  963. }
  964. $list = $query->get()->map(function ($value) {
  965. $value = (array)$value;
  966. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  967. return $value;
  968. })->toArray();
  969. return $list;
  970. }
  971. // 生成火山临时token
  972. public function setStsToken() {
  973. // ************* 配置参数 *************
  974. $method = 'GET';
  975. $service = 'sts';
  976. $host = 'open.volcengineapi.com';
  977. $region = env('VOLC_REGION');
  978. $endpoint = 'https://open.volcengineapi.com';
  979. // $endpoint = 'https://tos-cn-beijing.volces.com';
  980. $access_key = env('VOLC_AK');
  981. $secret_key = env('VOLC_SK');
  982. // 获取缓存中的token,如果没有则请求接口
  983. $token = Redis::get('volc_sts_token');
  984. if (!$token) {
  985. // 查询参数
  986. $query_parameters = [
  987. 'Action' => 'AssumeRole',
  988. 'RoleSessionName' => 'user@zw',
  989. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  990. 'Version' => '2018-01-01'
  991. ];
  992. // 生成URL编码的查询字符串
  993. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  994. // 获取签名头信息
  995. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  996. // 构建完整URL
  997. $request_url = $endpoint . '?' . $request_parameters;
  998. $client = new Client(['verify' => false]);
  999. $response = $client->get($request_url, ['headers' => $headers]);
  1000. $response_arr = json_decode($response->getBody()->getContents(), true);
  1001. $result = [
  1002. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1003. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1004. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1005. 'Region' => env('VOLC_REGION'),
  1006. 'Endpoint' => env('VOLC_END_POINT'),
  1007. 'Bucket' => env('VOLC_BUCKET'),
  1008. ];
  1009. // 缓存token
  1010. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1011. return $result;
  1012. } else {
  1013. return json_decode($token, true);
  1014. }
  1015. // $response = $response['Response'];
  1016. // $access_key = $response['Credentials']['AccessKeyId'];
  1017. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1018. // $security_token = $response['Credentials']['SecurityToken'];
  1019. // $expiration = $response['Credentials']['Expiration'];
  1020. // dd($response_arr);
  1021. }
  1022. public function emotionGroups($data) {
  1023. $id = getProp($data, 'group_id');
  1024. $group_name = getProp($data, 'group_name');
  1025. $voice_type = getProp($data, 'voice_type');
  1026. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1027. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1028. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1029. if ($group_name) {
  1030. $query->where('group_name', 'like', "%{$group_name}%");
  1031. }
  1032. if ($id) {
  1033. $query->where('id', $id);
  1034. }
  1035. if ($voice_type) {
  1036. $query->where('voice_type', $voice_type);
  1037. }
  1038. return $query->orderBy('id')->get()->map(function ($value) {
  1039. return (array)$value;
  1040. })->toArray();
  1041. }
  1042. private function sign($key, $msg) {
  1043. return hash_hmac('sha256', $msg, $key, true);
  1044. }
  1045. // 生成签名密钥
  1046. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1047. $kDate = $this->sign($key, $dateStamp);
  1048. $kRegion = $this->sign($kDate, $regionName);
  1049. $kService = $this->sign($kRegion, $serviceName);
  1050. $kSigning = $this->sign($kService, 'request');
  1051. return $kSigning;
  1052. }
  1053. // 获取签名头信息
  1054. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1055. $contenttype = 'application/x-www-form-urlencoded';
  1056. $accept = 'application/json';
  1057. // 获取当前UTC时间
  1058. $t = new DateTime('now', new DateTimeZone('UTC'));
  1059. $xdate = $t->format('Ymd\THis\Z');
  1060. $datestamp = $t->format('Ymd');
  1061. // 1. 拼接规范请求串
  1062. $canonical_uri = '/';
  1063. $canonical_querystring = $request_parameters;
  1064. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1065. $signed_headers = 'content-type;host;x-date';
  1066. // 空请求体的SHA256哈希
  1067. $payload_hash = hash('sha256', '');
  1068. $canonical_request = implode("\n", [
  1069. $method,
  1070. $canonical_uri,
  1071. $canonical_querystring,
  1072. $canonical_headers,
  1073. $signed_headers,
  1074. $payload_hash
  1075. ]);
  1076. // 2. 拼接待签名字符串
  1077. $algorithm = 'HMAC-SHA256';
  1078. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1079. $hashed_canonical_request = hash('sha256', $canonical_request);
  1080. $string_to_sign = implode("\n", [
  1081. $algorithm,
  1082. $xdate,
  1083. $credential_scope,
  1084. $hashed_canonical_request
  1085. ]);
  1086. // 3. 计算签名
  1087. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1088. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1089. // 4. 添加签名到请求头
  1090. $authorization_header = sprintf(
  1091. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1092. $algorithm,
  1093. $access_key,
  1094. $credential_scope,
  1095. $signed_headers,
  1096. $signature
  1097. );
  1098. return [
  1099. 'Accept' => $accept,
  1100. 'Content-Type' => $contenttype,
  1101. 'X-Date' => $xdate,
  1102. 'Authorization' => $authorization_header
  1103. ];
  1104. }
  1105. // 文字合成语音(火山引擎)
  1106. public function tts($data) {
  1107. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1108. $headers = [
  1109. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1110. 'Content-Type' => 'application/json; charset=UTF-8'
  1111. ];
  1112. $post_data = [
  1113. 'app' => [
  1114. 'appid' => env('VOLC_APPID'),
  1115. 'token' => env('VOLC_TOKEN'),
  1116. 'cluster' => 'volcano_tts'
  1117. ],
  1118. 'user' => [
  1119. 'uid' => 'mp_audio'
  1120. ],
  1121. // 'audio' => [
  1122. // 'voice_type' =>
  1123. // ],
  1124. ];
  1125. }
  1126. public function scriptList($data) {
  1127. $script_id = getProp($data, 'script_id');
  1128. $script_name = getProp($data, 'script_name');
  1129. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  1130. if ($script_id) {
  1131. $query->where('id', $script_id);
  1132. }
  1133. if ($script_name) {
  1134. $query->where('script_name', 'like', "%{$script_name}%");
  1135. }
  1136. return $query->orderBy('created_at', 'desc')->paginate(12);
  1137. }
  1138. public function scripts($data) {
  1139. $script_id = getProp($data, 'script_id');
  1140. $script_name = getProp($data, 'script_name');
  1141. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('id as script_id', 'script_name');
  1142. if ($script_id) {
  1143. $query->where('id', $script_id);
  1144. }
  1145. if ($script_name) {
  1146. $query->where('script_name', 'like', "%{$script_name}%");
  1147. }
  1148. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1149. return (array)$value;
  1150. })->toArray();
  1151. }
  1152. public function scriptInfo($data) {
  1153. $script_id = getProp($data, 'script_id');
  1154. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1155. ->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();
  1156. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1157. $script = (array)$script;
  1158. $script['roles'] = json_decode($script['roles']);
  1159. $script['scenes'] = json_decode($script['scenes']);
  1160. // 获取分集组信息
  1161. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)
  1162. ->select('id as group_id', 'script_id', 'group_name', 'start_episode_number', 'end_episode_number')
  1163. ->orderBy('start_episode_number')->get()->map(function ($value) {
  1164. return (array)$value;
  1165. })->toArray();
  1166. foreach($groups as &$group) {
  1167. $script_id = getProp($group, 'script_id');
  1168. // 获取2个分集
  1169. $episode_list = DB::table('mp_script_episodes')->where('script_id', $script_id)->whereBetween('episode_number', [$group['start_episode_number'], $group['end_episode_number']])
  1170. ->select('episode_number', 'episode_name', 'episode_content')->orderBy('episode_number')->limit(2)->get()->map(function ($value) {
  1171. return (array)$value;
  1172. })->toArray();
  1173. $group['episodes'] = $episode_list;
  1174. }
  1175. $script['group'] = $groups;
  1176. return $script;
  1177. }
  1178. public function createScript($data) {
  1179. $script_name = getProp($data, 'script_name');
  1180. $uid = Site::getUid(); // 获取当前用户ID
  1181. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1182. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1183. $script_name .= '_'.date('YmdHis');
  1184. }
  1185. return DB::table('mp_scripts')->insertGetId([
  1186. 'script_name' => $script_name,
  1187. 'user_id' => $uid,
  1188. 'created_at' => date('Y-m-d H:i:s'),
  1189. 'updated_at' => date('Y-m-d H:i:s')
  1190. ]);
  1191. }
  1192. public function editScript($data) {
  1193. $script_id = getProp($data, 'script_id');
  1194. $script_name = getProp($data, 'script_name');
  1195. $uid = Site::getUid(); // 获取当前用户ID
  1196. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  1197. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  1198. if ($id && (int)$id !== (int)$script_id) {
  1199. $script_name .= '_'.date('YmdHis');
  1200. }
  1201. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1202. 'script_name' => $script_name,
  1203. 'updated_at' => date('Y-m-d H:i:s')
  1204. ]);
  1205. }
  1206. public function delScript($data) {
  1207. $script_id = getProp($data, 'script_id');
  1208. $uid = Site::getUid(); // 获取当前用户ID
  1209. if (!$script_id) Utils::throwError('20003:请选择剧本');
  1210. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1211. 'is_deleted' => 1,
  1212. 'updated_at' => date('Y-m-d H:i:s')
  1213. ]);
  1214. }
  1215. public function createEpisode($data) {
  1216. $script_id = getProp($data, 'script_id');
  1217. $group_name = getProp($data, 'group_name');
  1218. $remark = getProp($data, 'remark');
  1219. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  1220. $uid = Site::getUid(); // 获取当前用户ID
  1221. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  1222. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  1223. $group_name .= '_'.date('YmdHis');
  1224. }
  1225. return DB::table('mp_script_episode_group')->insertGetId([
  1226. 'script_id' => $script_id,
  1227. 'group_name' => $group_name,
  1228. 'user_id' => $uid,
  1229. 'remark' => $remark,
  1230. 'created_at' => date('Y-m-d H:i:s'),
  1231. 'updated_at' => date('Y-m-d H:i:s')
  1232. ]);
  1233. }
  1234. public function editEpisode($data) {
  1235. $group_id = getProp($data, 'group_id');
  1236. $start_episode_number = getProp($data, 'start_episode_number');
  1237. $end_episode_number = getProp($data, 'end_episode_number');
  1238. $group_name = getProp($data, 'group_name');
  1239. $uid = Site::getUid(); // 获取当前用户ID
  1240. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  1241. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  1242. if ($id && (int)$id !== (int)$group_id) {
  1243. $group_name .= '_'.date('YmdHis');
  1244. }
  1245. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1246. 'group_name' => $group_name,
  1247. 'start_episode_number' => $start_episode_number,
  1248. 'end_episode_number' => $end_episode_number,
  1249. 'updated_at' => date('Y-m-d H:i:s')
  1250. ]);
  1251. }
  1252. public function delEpisode($data) {
  1253. $group_id = getProp($data, 'group_id');
  1254. $uid = Site::getUid(); // 获取当前用户ID
  1255. if (!$group_id) Utils::throwError('20003:请选择分集');
  1256. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1257. 'is_deleted' => 1,
  1258. 'updated_at' => date('Y-m-d H:i:s')
  1259. ]);
  1260. }
  1261. /**
  1262. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1263. *
  1264. * @param array $data 包含以下参数:
  1265. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1266. * - question: 用户问题(可选)
  1267. * - model: 使用的模型(r1 或 v3,默认 v3)
  1268. * @return \Generator 返回生成器,用于流式输出
  1269. */
  1270. public function generateEpisodes($data) {
  1271. $script_id = getProp($data, 'script_id');
  1272. $group_id = getProp($data, 'group_id');
  1273. // $file = getProp($data, 'file');
  1274. $file = '';
  1275. $content = getProp($data, 'content', '');
  1276. // $bid = getProp($data, 'bid', 0);
  1277. $bid = 0;
  1278. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->first();
  1279. if (!$group) {
  1280. Utils::throwError('20003:剧本分集不存在');
  1281. }
  1282. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  1283. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  1284. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  1285. $prompt = getProp($data, 'prompt');
  1286. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  1287. $model = getProp($data, 'model');
  1288. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1289. Utils::throwError('20003:该模型不存在!');
  1290. }
  1291. $exists_sequence_arr = DB::table('mp_script_episodes')->where('script_id', $script_id)->whereBetween('episode_number', [$start_episode_sequence, $end_episode_sequence])->pluck('episode_number')->toArray();
  1292. if ($exists_sequence_arr) Utils::throwError('20003:剧集 '.implode('、', $exists_sequence_arr).' 已存在,不得创建!');
  1293. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1294. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1295. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1296. if ($model === 'deepseek-chat') {
  1297. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1298. $model = 'deepseek-v4-flash';
  1299. $thinkingMode = 'disabled';
  1300. } elseif ($model === 'deepseek-reasoner') {
  1301. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1302. $model = 'deepseek-v4-flash';
  1303. $thinkingMode = 'enabled';
  1304. }
  1305. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1306. if (!$script) {
  1307. Utils::throwError('20003:剧本不存在');
  1308. }
  1309. $content = getProp($script, 'content');
  1310. if (!$file && !$content && !$bid) {
  1311. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1312. }
  1313. // 提取文件内容
  1314. if ($file) {
  1315. $content = $this->extractFileContent($file);
  1316. if (!$content) {
  1317. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1318. }
  1319. } elseif ($bid) {
  1320. $content = $this->getContentByBid($bid);
  1321. if (!$content) {
  1322. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1323. }
  1324. } elseif ($content) {
  1325. $content = filterContent($content);
  1326. } elseif ($prompt) {
  1327. $content = filterContent($prompt);
  1328. } else {
  1329. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1330. }
  1331. // 构建消息
  1332. $messages = [
  1333. $this->sys_message,
  1334. [
  1335. 'role' => 'user',
  1336. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1337. ]
  1338. ];
  1339. $post_data = [
  1340. 'model' => $model,
  1341. 'messages' => $messages,
  1342. // 'max_tokens' => 8192,
  1343. 'temperature' => 0.7,
  1344. 'frequency_penalty' => 0,
  1345. 'presence_penalty' => 0,
  1346. 'thinking' => ['type' => $thinkingMode],
  1347. 'response_format' => ['type' => 'text'],
  1348. 'stream' => true
  1349. ];
  1350. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1351. // 根据模型类型选择调用方法
  1352. $fullContent = '';
  1353. $fullReasoningContent = '';
  1354. $usage = [];
  1355. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1356. // DeepSeek 官方模型使用 DeepSeek API
  1357. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1358. } else {
  1359. // 其他模型使用火山引擎API
  1360. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1361. }
  1362. // 处理流式输出
  1363. foreach ($streamGenerator as $chunk) {
  1364. if (isset($chunk['type'])) {
  1365. if ($chunk['type'] === 'done') {
  1366. // 最终结果
  1367. $fullContent = $chunk['full_content'];
  1368. $fullReasoningContent = $chunk['full_reasoning'];
  1369. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1370. } else {
  1371. // 逐块yield数据
  1372. yield $chunk;
  1373. }
  1374. }
  1375. }
  1376. dLog('deepseek')->info('完整内容: '.$fullContent);
  1377. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1378. // 处理完整内容并返回最终结果
  1379. $script_arr = [];
  1380. if ($fullContent) {
  1381. $script_arr = extractScriptContent($fullContent);
  1382. }
  1383. logDB('deepseek', 'info', '解析内容', $script_arr);
  1384. if (!$script_arr['episodes']) {
  1385. yield [
  1386. 'type' => 'error',
  1387. 'script' => $script_arr,
  1388. 'msg' => '未生成剧本相关信息',
  1389. 'answer' => $fullContent,
  1390. 'reasoning' => $fullReasoningContent,
  1391. 'usage' => $usage
  1392. ];
  1393. }
  1394. try {
  1395. DB::beginTransaction();
  1396. // 返回前保存剧本内容
  1397. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1398. 'content' => $content,
  1399. 'updated_at' => date('Y-m-d H:i:s')
  1400. ]);
  1401. if (!$boolen) {
  1402. Utils::throwError('20003:保存剧本内容失败');
  1403. }
  1404. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1405. 'start_episode_number' => $start_episode_sequence,
  1406. 'end_episode_number' => $end_episode_sequence,
  1407. 'updated_at' => date('Y-m-d H:i:s')
  1408. ]);
  1409. if (!$boolen1) {
  1410. Utils::throwError('20003:保存分集失败');
  1411. }
  1412. $episodes = [];
  1413. foreach ($script_arr['episodes'] as $item) {
  1414. $episodes[] = [
  1415. 'script_id' => $script_id,
  1416. 'episode_number' => $item['episode_number'],
  1417. 'episode_name' => $item['episode_name'],
  1418. 'episode_content' => $item['episode_content'],
  1419. 'created_at' => date('Y-m-d H:i:s'),
  1420. 'updated_at' => date('Y-m-d H:i:s'),
  1421. ];
  1422. }
  1423. if ($episodes) {
  1424. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1425. if (!$boolen2) {
  1426. Utils::throwError('20003:保存分集内容失败');
  1427. }
  1428. }else {
  1429. Utils::throwError('20003:分集剧本解析失败');
  1430. }
  1431. }catch (\Exception $e) {
  1432. DB::rollBack();
  1433. Utils::throwError('20003:'.$e->getMessage());
  1434. }
  1435. DB::commit();
  1436. yield [
  1437. 'type' => 'done',
  1438. 'script' => $script_arr,
  1439. 'answer' => $fullContent,
  1440. 'reasoning' => $fullReasoningContent,
  1441. 'usage' => $usage
  1442. ];
  1443. }
  1444. public function chatWithFileStream($data) {
  1445. $script_id = getProp($data, 'script_id');
  1446. $group_id = getProp($data, 'group_id');
  1447. $file = getProp($data, 'file');
  1448. $content = getProp($data, 'content', '');
  1449. $bid = getProp($data, 'bid', 0);
  1450. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1451. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1452. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  1453. $prompt = getProp($data, 'prompt');
  1454. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1455. $model = getProp($data, 'model');
  1456. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1457. Utils::throwError('20003:该模型不存在!');
  1458. }
  1459. $exists_sequence_arr = DB::table('mp_script_episodes')->where('script_id', $script_id)->whereBetween('episode_number', [$start_episode_sequence, $end_episode_sequence])->pluck('episode_number')->toArray();
  1460. if ($exists_sequence_arr) Utils::throwError('20003:剧集 '.implode('、', $exists_sequence_arr).' 已存在,不得创建!');
  1461. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1462. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1463. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1464. if ($model === 'deepseek-chat') {
  1465. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1466. $model = 'deepseek-v4-flash';
  1467. $thinkingMode = 'disabled';
  1468. } elseif ($model === 'deepseek-reasoner') {
  1469. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1470. $model = 'deepseek-v4-flash';
  1471. $thinkingMode = 'enabled';
  1472. }
  1473. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1474. if (!$script) {
  1475. Utils::throwError('20003:剧本不存在');
  1476. }
  1477. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->first();
  1478. if (!$group) {
  1479. Utils::throwError('20003:剧本分集不存在');
  1480. }
  1481. if (!$file && !$content && !$bid) {
  1482. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1483. }
  1484. // 提取文件内容
  1485. if ($file) {
  1486. $content = $this->extractFileContent($file);
  1487. if (!$content) {
  1488. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1489. }
  1490. } elseif ($bid) {
  1491. $content = $this->getContentByBid($bid);
  1492. if (!$content) {
  1493. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1494. }
  1495. } elseif ($content) {
  1496. $content = filterContent($content);
  1497. } elseif ($prompt) {
  1498. $content = filterContent($prompt);
  1499. } else {
  1500. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1501. }
  1502. // 构建消息
  1503. $messages = [
  1504. [
  1505. 'role' => 'system',
  1506. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1507. 强制要求:\n
  1508. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  1509. 2.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  1510. 普通要求:\n
  1511. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  1512. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  1513. 示例如下:\n
  1514. ###剧本名:西昆仑
  1515. ###故事梗概
  1516. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1517. ###剧本亮点
  1518. 亮点1:绝境奇药,生死一线
  1519. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1520. 亮点2:结拜兄妹,化解尴尬
  1521. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1522. 亮点3:纤发夺命,情愫暗涌
  1523. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1524. ###人物关系
  1525. 阿雪与梁萧之间存在兄妹之情。
  1526. ###核心矛盾
  1527. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1528. ###主体列表
  1529. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1530. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1531. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1532. 阴阳球:天地异宝,能化生精气,救人于危难。
  1533. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1534. ###美术风格
  1535. 基础画风风格词:厚涂古风
  1536. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1537. ###场景列表
  1538. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  1539. [
  1540. 'role' => 'user',
  1541. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1542. ]
  1543. ];
  1544. $post_data = [
  1545. 'model' => $model,
  1546. 'messages' => $messages,
  1547. // 'max_tokens' => 8192,
  1548. 'temperature' => 0.7,
  1549. 'frequency_penalty' => 0,
  1550. 'presence_penalty' => 0,
  1551. 'thinking' => ['type' => $thinkingMode],
  1552. 'response_format' => ['type' => 'text'],
  1553. 'stream' => true
  1554. ];
  1555. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1556. // 根据模型类型选择调用方法
  1557. $fullContent = '';
  1558. $fullReasoningContent = '';
  1559. $usage = [];
  1560. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1561. // DeepSeek 官方模型使用 DeepSeek API
  1562. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1563. } else {
  1564. // 其他模型使用火山引擎API
  1565. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1566. }
  1567. // 处理流式输出
  1568. foreach ($streamGenerator as $chunk) {
  1569. if (isset($chunk['type'])) {
  1570. if ($chunk['type'] === 'done') {
  1571. // 最终结果
  1572. $fullContent = $chunk['full_content'];
  1573. $fullReasoningContent = $chunk['full_reasoning'];
  1574. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1575. } else {
  1576. // 逐块yield数据
  1577. yield $chunk;
  1578. }
  1579. }
  1580. }
  1581. dLog('deepseek')->info('完整内容: '.$fullContent);
  1582. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1583. // 处理完整内容并返回最终结果
  1584. $script_arr = [];
  1585. if ($fullContent) {
  1586. $script_arr = extractScriptContent($fullContent);
  1587. }
  1588. logDB('deepseek', 'info', '解析内容', $script_arr);
  1589. if (!$script_arr['episodes']) {
  1590. yield [
  1591. 'type' => 'error',
  1592. 'script' => $script_arr,
  1593. 'msg' => '未生成剧本相关信息',
  1594. 'answer' => $fullContent,
  1595. 'reasoning' => $fullReasoningContent,
  1596. 'usage' => $usage
  1597. ];
  1598. }
  1599. try {
  1600. DB::beginTransaction();
  1601. // 返回前保存剧本内容
  1602. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1603. 'content' => $content,
  1604. 'status' => '解析完成',
  1605. 'updated_at' => date('Y-m-d H:i:s')
  1606. ]);
  1607. if (!$boolen) {
  1608. Utils::throwError('20003:保存剧本内容失败');
  1609. }
  1610. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1611. 'start_episode_number' => $start_episode_sequence,
  1612. 'end_episode_number' => $end_episode_sequence,
  1613. 'updated_at' => date('Y-m-d H:i:s')
  1614. ]);
  1615. if (!$boolen1) {
  1616. Utils::throwError('20003:保存分集失败');
  1617. }
  1618. // $episodes = [];
  1619. // foreach ($script_arr['episodes'] as $item) {
  1620. // $episodes[] = [
  1621. // 'script_id' => $script_id,
  1622. // 'episode_number' => $item['episode_number'],
  1623. // 'episode_name' => $item['episode_name'],
  1624. // 'episode_content' => $item['episode_content'],
  1625. // 'created_at' => date('Y-m-d H:i:s'),
  1626. // 'updated_at' => date('Y-m-d H:i:s'),
  1627. // ];
  1628. // }
  1629. // if ($episodes) {
  1630. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1631. // if (!$boolen2) {
  1632. // Utils::throwError('20003:保存分集内容失败');
  1633. // }
  1634. // }else {
  1635. // Utils::throwError('20003:分集剧本解析失败');
  1636. // }
  1637. }catch (\Exception $e) {
  1638. DB::rollBack();
  1639. Utils::throwError('20003:'.$e->getMessage());
  1640. }
  1641. DB::commit();
  1642. yield [
  1643. 'type' => 'done',
  1644. 'script' => $script_arr,
  1645. 'answer' => $fullContent,
  1646. 'reasoning' => $fullReasoningContent,
  1647. 'usage' => $usage
  1648. ];
  1649. }
  1650. /**
  1651. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1652. *
  1653. * @param array $data 包含以下参数:
  1654. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1655. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1656. * - model: 使用的模型(r1 或 v3,默认 v3)
  1657. * @return array
  1658. */
  1659. public function chatWithFile($data) {
  1660. $script_id = getProp($data, 'script_id');
  1661. $file = getProp($data, 'file');
  1662. $content = getProp($data, 'content', '');
  1663. $bid = getProp($data, 'bid', 0);
  1664. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1665. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1666. $prompt = getProp($data, 'prompt');
  1667. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1668. // 处理文本模型
  1669. $model = getProp($data, 'model');
  1670. if (!$model) {
  1671. // 用户没有输入,使用默认值
  1672. $model = 'doubao-seed-2-0-mini-260215';
  1673. }
  1674. // 验证模型是否在可用模型表中
  1675. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1676. $model = 'doubao-seed-2-0-mini-260215';
  1677. }
  1678. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1679. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1680. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1681. if ($model === 'deepseek-chat') {
  1682. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1683. $model = 'deepseek-v4-flash';
  1684. $thinkingMode = 'disabled';
  1685. } elseif ($model === 'deepseek-reasoner') {
  1686. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1687. $model = 'deepseek-v4-flash';
  1688. $thinkingMode = 'enabled';
  1689. }
  1690. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1691. if (!$script) {
  1692. Utils::throwError('20003:剧本不存在');
  1693. }
  1694. if (!$file && !$content && !$bid) {
  1695. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1696. }
  1697. // 提取文件内容
  1698. if ($file) {
  1699. $content = $this->extractFileContent($file);
  1700. if (!$content) {
  1701. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1702. }
  1703. } elseif ($bid) {
  1704. $content = $this->getContentByBid($bid);
  1705. if (!$content) {
  1706. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1707. }
  1708. } elseif ($content) {
  1709. $content = filterContent($content);
  1710. } elseif ($prompt) {
  1711. $content = filterContent($prompt);
  1712. } else {
  1713. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1714. }
  1715. // 构建消息
  1716. $messages = [
  1717. $this->sys_message,
  1718. [
  1719. 'role' => 'user',
  1720. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1721. ]
  1722. ];
  1723. $post_data = [
  1724. 'model' => $model,
  1725. 'messages' => $messages,
  1726. // 'max_tokens' => 8192,
  1727. 'temperature' => 0.7,
  1728. 'frequency_penalty' => 0,
  1729. 'presence_penalty' => 0,
  1730. 'thinking' => ['type' => $thinkingMode],
  1731. 'response_format' => ['type' => 'text'],
  1732. 'stream' => false
  1733. ];
  1734. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1735. // 根据模型类型选择调用方法
  1736. $fullContent = '';
  1737. $usage = [];
  1738. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1739. // DeepSeek 官方模型使用 DeepSeek API
  1740. $chatResult = $this->chatOnly($post_data);
  1741. } else {
  1742. // 其他模型使用火山引擎API
  1743. $chatResult = $this->volcEngineChatCompletion($post_data);
  1744. }
  1745. if (is_array($chatResult)) {
  1746. $fullContent = $chatResult['fullContent'];
  1747. $usage = $chatResult['usage'];
  1748. }
  1749. $script_arr = [];
  1750. // 处理结果
  1751. if ($fullContent) {
  1752. $script_arr = extractScriptContent($fullContent);
  1753. }
  1754. // 返回前保存剧本内容
  1755. DB::table('mp_scripts')->where('id', $script_id)->update([
  1756. 'content' => $content,
  1757. 'updated_at' => date('Y-m-d H:i:s')
  1758. ]);
  1759. return [
  1760. 'script' => $script_arr,
  1761. 'answer' => $fullContent,
  1762. 'usage' => $usage
  1763. ];
  1764. }
  1765. public function saveScript($data) {
  1766. $script_arr =getProp($data, 'script', []);
  1767. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1768. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1769. $script_id = getProp($data, 'script_id');
  1770. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1771. try {
  1772. DB::beginTransaction();
  1773. $update_data = [
  1774. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1775. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1776. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1777. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1778. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1779. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1780. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1781. 'status' => 3,
  1782. 'start_episode_sequence' => $start_episode_sequence,
  1783. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1784. 'episode_num' => count($script_arr['episodes']),
  1785. 'updated_at' => date('Y-m-d H:i:s')
  1786. ];
  1787. // 保存剧本内容
  1788. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1789. if (!$boolen) {
  1790. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1791. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  1792. Utils::throwError('20003:剧本内容保存失败');
  1793. }
  1794. // 保存分集内容
  1795. // 删除历史分集内容
  1796. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1797. $episodes = [];
  1798. $sequence = 1;
  1799. foreach ($script_arr['episodes'] as $episode) {
  1800. $segment_number = 1;
  1801. foreach($episode['segments'] as $segment) {
  1802. $episodes[] = [
  1803. 'script_id' => $script_id,
  1804. 'episode_number' => $episode['episode_number'],
  1805. 'title' => $episode['title'],
  1806. // 'content' => $episode['content'],
  1807. 'content' => '',
  1808. 'segment_number' => $segment_number,
  1809. 'segment_content' => $segment['segment_content'],
  1810. 'sequence' => $sequence,
  1811. 'created_at' => date('Y-m-d H:i:s'),
  1812. 'updated_at' => date('Y-m-d H:i:s')
  1813. ];
  1814. $sequence++;
  1815. $segment_number++;
  1816. }
  1817. }
  1818. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1819. if (!$boolen2) {
  1820. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1821. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  1822. Utils::throwError('20003:分集内容保存失败');
  1823. }
  1824. } catch (\Exception $e) {
  1825. DB::rollBack();
  1826. Utils::throwError('20003:'.$e->getMessage());
  1827. }
  1828. DB::commit();
  1829. return true;
  1830. }
  1831. public function getBookContent($data) {
  1832. $bid = getProp($data, 'bid');
  1833. $start_sequence = getProp($data, 'start_sequence');
  1834. $end_sequence = getProp($data, 'end_sequence');
  1835. $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])
  1836. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  1837. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  1838. return $return_content;
  1839. }
  1840. public function exportScript($data) {
  1841. $filename = getProp($data, 'filename');
  1842. $script_id = getProp($data, 'script_id');
  1843. $group_id = getProp($data, 'group_id');
  1844. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1845. ->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();
  1846. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1847. $script = (array)$script;
  1848. $script['roles'] = json_decode($script['roles']);
  1849. $script['scenes'] = json_decode($script['scenes']);
  1850. $start = 1;
  1851. $end = DB::table('mp_script_episodes')->where('script_id', $script_id)->count('id');
  1852. // 获取分集组信息
  1853. if ($group_id) {
  1854. $group = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)
  1855. ->select('start_episode_number', 'end_episode_number')->first();
  1856. if (!$group) Utils::throwError('20003:分集不存在');
  1857. $start = getProp($group, 'start_episode_number');
  1858. $end = getProp($group, 'end_episode_number');
  1859. }
  1860. // 获取分集信息
  1861. $episode_list = DB::table('mp_script_episodes')->where('script_id', $script_id)->whereBetween('episode_number', [$start, $end])
  1862. ->select('episode_number', 'episode_name', 'episode_content')->orderBy('episode_number')->get()->map(function ($value) {
  1863. return (array)$value;
  1864. })->toArray();
  1865. $script['episodes'] = $episode_list;
  1866. $export_type = getProp($data, 'export_type', 'txt');
  1867. // 生成文件名
  1868. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  1869. // 根据导出类型生成不同格式的文件
  1870. switch ($export_type) {
  1871. case 'txt':
  1872. return $this->exportScriptAsTxt($script, $filename);
  1873. case 'pdf':
  1874. return $this->exportScriptAsPdf($script, $filename);
  1875. default:
  1876. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1877. }
  1878. }
  1879. /**
  1880. * 导出剧本为TXT格式
  1881. */
  1882. private function exportScriptAsTxt($script, $filename) {
  1883. // 构建TXT内容
  1884. $content = $this->buildScriptContent($script);
  1885. // 设置响应头,直接下载
  1886. header('Content-Type: text/plain; charset=utf-8');
  1887. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1888. header('Content-Length: ' . strlen($content));
  1889. // 输出内容并结束
  1890. echo $content;
  1891. exit();
  1892. }
  1893. /**
  1894. * 导出剧本为PDF格式
  1895. */
  1896. private function exportScriptAsPdf($script, $filename) {
  1897. // 使用HTML转PDF的方式来更好地支持中文
  1898. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1899. // 创建PDF实例
  1900. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1901. // 设置文档信息
  1902. $pdf->SetCreator('剧本导出系统');
  1903. $pdf->SetAuthor('系统');
  1904. $pdf->SetTitle($script['script_name']);
  1905. $pdf->SetSubject('剧本导出');
  1906. // 设置边距
  1907. $pdf->SetMargins(15, 15, 15);
  1908. $pdf->SetAutoPageBreak(TRUE, 15);
  1909. // 添加页面
  1910. $pdf->AddPage();
  1911. // 注册并使用 simsun.ttf 字体
  1912. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1913. // 使用HTML内容生成PDF
  1914. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1915. // 直接输出PDF文件供下载
  1916. header('Content-Type: application/pdf');
  1917. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1918. // 直接输出PDF内容
  1919. $pdf->Output($filename . '.pdf', 'D');
  1920. exit();
  1921. }
  1922. /**
  1923. * 构建用于PDF的HTML内容
  1924. */
  1925. private function buildScriptHtmlForPdf($script) {
  1926. $html = '<style>
  1927. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  1928. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  1929. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  1930. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  1931. .info { margin-bottom: 8px; }
  1932. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  1933. .segment { margin-bottom: 10px; margin-left: 20px; }
  1934. </style>';
  1935. // 标题
  1936. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  1937. // 剧本简介
  1938. if (!empty($script['intro'])) {
  1939. $html .= '<h2>剧本简介</h2>';
  1940. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  1941. }
  1942. // 亮点
  1943. if (!empty($script['highlights'])) {
  1944. $html .= '<h2>亮点</h2>';
  1945. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  1946. }
  1947. // 核心矛盾
  1948. if (!empty($script['core_contradiction'])) {
  1949. $html .= '<h2>核心矛盾</h2>';
  1950. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  1951. }
  1952. // 艺术风格
  1953. if (!empty($script['art_style'])) {
  1954. $html .= '<h2>艺术风格</h2>';
  1955. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  1956. }
  1957. // 角色列表
  1958. if (!empty($script['roles']) && is_array($script['roles'])) {
  1959. $html .= '<h2>角色列表</h2>';
  1960. $html .= '<ul>';
  1961. foreach ($script['roles'] as $role) {
  1962. if (is_array($role) || is_object($role)) {
  1963. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  1964. } else {
  1965. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  1966. }
  1967. }
  1968. $html .= '</ul>';
  1969. }
  1970. // 角色关系
  1971. if (!empty($script['role_relationship'])) {
  1972. $html .= '<h2>角色关系</h2>';
  1973. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  1974. }
  1975. // 场景列表
  1976. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1977. $html .= '<h2>场景列表</h2>';
  1978. $html .= '<ul>';
  1979. foreach ($script['scenes'] as $scene) {
  1980. if (is_array($scene) || is_object($scene)) {
  1981. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  1982. } else {
  1983. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  1984. }
  1985. }
  1986. $html .= '</ul>';
  1987. }
  1988. // 分集内容
  1989. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1990. $html .= '<h2>分集内容</h2>';
  1991. foreach ($script['episodes'] as $episode) {
  1992. $html .= '<div class="episode">';
  1993. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  1994. if (!empty($episode['episode_name'])) {
  1995. $html .= ':' . htmlspecialchars($episode['episode_name']);
  1996. }
  1997. $html .= '</h3>';
  1998. // 处理分集内容
  1999. if (!empty($episode['episode_content'])) {
  2000. $html .= '<div class="segment">';
  2001. // 去掉第一行(标题行)
  2002. $content = $episode['episode_content'];
  2003. $lines = explode("\n", $content);
  2004. if (count($lines) > 1) {
  2005. array_shift($lines); // 移除第一行
  2006. $content = implode("\n", $lines);
  2007. } else {
  2008. $content = ''; // 如果只有一行,则清空
  2009. }
  2010. $html .= nl2br(htmlspecialchars($content));
  2011. $html .= '</div>';
  2012. }
  2013. $html .= '</div>';
  2014. }
  2015. }
  2016. return $html;
  2017. }
  2018. /**
  2019. * 构建PDF内容
  2020. */
  2021. private function buildPdfContent($pdf, $script) {
  2022. // 标题
  2023. $pdf->SetFont('dejavusans', 'B', 18);
  2024. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2025. $pdf->Ln(5);
  2026. // 基本信息
  2027. $pdf->SetFont('dejavusans', '', 12);
  2028. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2029. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2030. $pdf->Ln(5);
  2031. // 剧本简介
  2032. if (!empty($script['intro'])) {
  2033. $pdf->SetFont('dejavusans', 'B', 14);
  2034. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2035. $pdf->SetFont('dejavusans', '', 12);
  2036. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2037. $pdf->Ln(3);
  2038. }
  2039. // 亮点
  2040. if (!empty($script['highlights'])) {
  2041. $pdf->SetFont('dejavusans', 'B', 14);
  2042. $pdf->Cell(0, 10, '亮点', 0, 1);
  2043. $pdf->SetFont('dejavusans', '', 12);
  2044. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2045. $pdf->Ln(3);
  2046. }
  2047. // 核心矛盾
  2048. if (!empty($script['core_contradiction'])) {
  2049. $pdf->SetFont('dejavusans', 'B', 14);
  2050. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2051. $pdf->SetFont('dejavusans', '', 12);
  2052. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2053. $pdf->Ln(3);
  2054. }
  2055. // 艺术风格
  2056. if (!empty($script['art_style'])) {
  2057. $pdf->SetFont('dejavusans', 'B', 14);
  2058. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2059. $pdf->SetFont('dejavusans', '', 12);
  2060. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2061. $pdf->Ln(3);
  2062. }
  2063. // 备注
  2064. if (!empty($script['remark'])) {
  2065. $pdf->SetFont('dejavusans', 'B', 14);
  2066. $pdf->Cell(0, 10, '备注', 0, 1);
  2067. $pdf->SetFont('dejavusans', '', 12);
  2068. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2069. $pdf->Ln(3);
  2070. }
  2071. // 角色列表
  2072. if (!empty($script['roles']) && is_array($script['roles'])) {
  2073. $pdf->SetFont('dejavusans', 'B', 14);
  2074. $pdf->Cell(0, 10, '角色列表', 0, 1);
  2075. $pdf->SetFont('dejavusans', '', 12);
  2076. foreach ($script['roles'] as $index => $role) {
  2077. if (is_array($role) || is_object($role)) {
  2078. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  2079. } else {
  2080. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  2081. }
  2082. }
  2083. $pdf->Ln(3);
  2084. }
  2085. // 角色关系
  2086. if (!empty($script['role_relationship'])) {
  2087. $pdf->SetFont('dejavusans', 'B', 14);
  2088. $pdf->Cell(0, 10, '角色关系', 0, 1);
  2089. $pdf->SetFont('dejavusans', '', 12);
  2090. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  2091. $pdf->Ln(3);
  2092. }
  2093. // 场景列表
  2094. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  2095. $pdf->SetFont('dejavusans', 'B', 14);
  2096. $pdf->Cell(0, 10, '场景列表', 0, 1);
  2097. $pdf->SetFont('dejavusans', '', 12);
  2098. foreach ($script['scenes'] as $index => $scene) {
  2099. if (is_array($scene) || is_object($scene)) {
  2100. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  2101. } else {
  2102. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  2103. }
  2104. }
  2105. $pdf->Ln(5);
  2106. }
  2107. // 分集内容
  2108. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  2109. $pdf->SetFont('dejavusans', 'B', 16);
  2110. $pdf->Cell(0, 12, '分集内容', 0, 1);
  2111. $pdf->Ln(3);
  2112. foreach ($script['episodes'] as $episode) {
  2113. // 检查是否需要新页面
  2114. if ($pdf->GetY() > 250) {
  2115. $pdf->AddPage();
  2116. }
  2117. $pdf->SetFont('dejavusans', 'B', 14);
  2118. $episodeTitle = '第' . $episode['episode_number'] . '集';
  2119. if (!empty($episode['title'])) {
  2120. $episodeTitle .= ':' . $episode['title'];
  2121. }
  2122. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  2123. // 处理分段内容
  2124. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  2125. $pdf->SetFont('dejavusans', '', 12);
  2126. foreach ($episode['segments'] as $segment) {
  2127. if (!empty($segment['segment_content'])) {
  2128. // 如果有分段编号,显示分段标题
  2129. if (!empty($segment['segment_number'])) {
  2130. $pdf->SetFont('dejavusans', 'B', 12);
  2131. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  2132. $pdf->SetFont('dejavusans', '', 12);
  2133. }
  2134. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  2135. $pdf->Ln(2);
  2136. }
  2137. }
  2138. }
  2139. $pdf->Ln(5);
  2140. }
  2141. }
  2142. }
  2143. /**
  2144. * 构建剧本文本内容
  2145. */
  2146. private function buildScriptContent($script) {
  2147. $content = '';
  2148. // 剧本基本信息
  2149. if (!empty($script['intro'])) {
  2150. $content .= "###故事梗概\n" . $script['intro'] . "\n\n";
  2151. }
  2152. if (!empty($script['highlights'])) {
  2153. $content .= "###剧本亮点\n" . $script['highlights'] . "\n\n";
  2154. }
  2155. if (!empty($script['role_relationship'])) {
  2156. $content .= "###人物关系\n" . $script['role_relationship'] . "\n\n";
  2157. }
  2158. if (!empty($script['core_contradiction'])) {
  2159. $content .= "###核心矛盾\n" . $script['core_contradiction'] . "\n\n";
  2160. }
  2161. if (!empty($script['roles']) && is_array($script['roles'])) {
  2162. $content .= "###主体列表\n";
  2163. foreach ($script['roles'] as $role) {
  2164. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  2165. }
  2166. $content .= "\n\n";
  2167. }
  2168. if (!empty($script['art_style'])) {
  2169. $content .= "###美术风格\n" . $script['art_style'] . "\n\n";
  2170. }
  2171. // 场景信息
  2172. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  2173. $content .= "###场景列表\n";
  2174. foreach ($script['scenes'] as $scene) {
  2175. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  2176. }
  2177. $content .= "\n\n";
  2178. }
  2179. // 分集内容
  2180. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  2181. $content .= "###分集剧本\n";
  2182. foreach ($script['episodes'] as $episode) {
  2183. // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  2184. // if (!empty($episode['episode_name'])) {
  2185. // $content .= ":" . $episode['episode_name'];
  2186. // }
  2187. // $content .= "\n";
  2188. $content .= $episode['episode_content'] . "\n\n";
  2189. }
  2190. }
  2191. return $content;
  2192. }
  2193. /**
  2194. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2195. *
  2196. * @param array $data 包含以下参数:
  2197. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2198. * - question: 用户问题(可选)
  2199. * - model: 使用的模型(r1 或 v3,默认 v3)
  2200. * @return \Generator 返回生成器,用于流式输出
  2201. */
  2202. public function addChat($data) {
  2203. $uid = Site::getUid();
  2204. $anime_id = getProp($data, 'anime_id');
  2205. if (!$anime_id) Utils::throwError('20003:请选择对话');
  2206. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2207. if (!$anime) Utils::throwError('20003:对话不存在');
  2208. $file = getProp($data, 'file');
  2209. $content = getProp($data, 'content', '');
  2210. $bid = getProp($data, 'bid', 0);
  2211. $script_id = getProp($data, 'script_id', 0);
  2212. $prompt = getProp($data, 'prompt');
  2213. // 处理文本模型
  2214. $model = getProp($data, 'model');
  2215. if (!$model) {
  2216. // 用户没有输入,从anime表获取
  2217. $model = getProp($anime, 'model');
  2218. if (!$model) {
  2219. // anime表也没有,使用默认值
  2220. $model = 'doubao-seed-2-0-mini-260215';
  2221. }
  2222. }
  2223. // 验证模型是否在可用模型表中
  2224. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2225. $model = 'doubao-seed-2-0-mini-260215';
  2226. }
  2227. $is_multi = getProp($anime, 'is_multi');
  2228. $is_single = (int)$is_multi !== 1;
  2229. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2230. // if (!$file && !$content && !$bid) {
  2231. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2232. // }
  2233. // 提取文件内容
  2234. if ($file) {
  2235. $content = $this->extractFileContent($file);
  2236. if (!$content) {
  2237. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2238. }
  2239. } elseif ($script_id) {
  2240. $content = $this->getContentByScriptId($script_id);
  2241. if (!$content) {
  2242. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2243. }
  2244. } elseif ($bid) {
  2245. $content = $this->getContentByBid($bid);
  2246. if (!$content) {
  2247. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2248. }
  2249. } elseif ($content) {
  2250. $content = filterContent($content);
  2251. } else {
  2252. $content = getProp($anime, 'content');
  2253. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2254. $need_generate_content = true;
  2255. }
  2256. }
  2257. // 美术风格
  2258. $input_art_style = getProp($data, 'art_style');
  2259. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2260. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2261. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2262. 中年女:邻居阿姨
  2263. 老年男:幽默大爷
  2264. 老年女:婆婆
  2265. 萌娃:奶气萌娃";
  2266. // 判断是否需要生成原文内容
  2267. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2268. // 如果需要生成原文内容,添加额外的要求
  2269. $content_generation_requirement = $need_generate_content
  2270. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2271. : "";
  2272. $systemPrompt = $is_single
  2273. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2274. 强制要求:
  2275. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2276. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2277. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2278. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2279. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2280. 普通要求:
  2281. 1.剧集标题必须与文档内容高度相关,剧集序号是1。
  2282. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2283. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2284. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2285. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2286. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2287. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2288. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2289. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2290. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2291. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2292. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2293. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2294. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2295. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2296. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2297. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2298. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2299. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2300. 示例如下:\n
  2301. ###剧本名:西昆仑
  2302. ###故事梗概
  2303. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2304. ###剧本亮点
  2305. 亮点1:绝境奇药,生死一线
  2306. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2307. 亮点2:结拜兄妹,化解尴尬
  2308. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2309. 亮点3:纤发夺命,情愫暗涌
  2310. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2311. ###人物关系
  2312. 阿雪与梁萧之间存在兄妹之情。
  2313. ###核心矛盾
  2314. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2315. ###主体列表
  2316. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2317. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2318. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2319. 阴阳球:天地异宝,能化生精气,救人于危难。
  2320. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2321. ###美术风格
  2322. 基础画风风格词:厚涂古风
  2323. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2324. ###场景列表
  2325. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2326. ###分镜剧本
  2327. ##第1幕:徐家老旧厨房 白天 室内
  2328. 分镜1
  2329. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2330. 场景:徐家老旧厨房
  2331. 构图设计:全景,低角度仰视
  2332. 运镜调度:手持拍摄
  2333. 配音角色:旁白
  2334. 出镜角色:许芸-校服装、徐母
  2335. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2336. 画面类型:普通画面
  2337. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2338. 分镜2
  2339. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2340. 场景:徐家老旧厨房
  2341. 构图设计:近景,徐母面部特写
  2342. 运镜调度:固定镜头
  2343. 配音角色:徐母
  2344. 出镜角色:徐母
  2345. 台词内容:问我夜不归宿死哪儿去了。
  2346. 画面类型:对口型
  2347. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2348. ##第2幕:徐家简陋客厅 黄昏 室内
  2349. 分镜3
  2350. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2351. 场景:徐家简陋客厅
  2352. 构图设计:全景,景深虚化
  2353. 运镜调度:固定镜头
  2354. 配音角色:旁白
  2355. 出镜角色:无
  2356. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2357. 画面类型:普通画面
  2358. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2359. 分镜4
  2360. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2361. 场景:徐家简陋客厅
  2362. 构图设计:特写,火车票
  2363. 运镜调度:固定镜头
  2364. 配音角色:旁白
  2365. 出镜角色:无
  2366. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2367. 画面类型:普通画面
  2368. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2369. "
  2370. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2371. 强制要求:\n
  2372. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2373. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2374. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2375. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2376. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2377. 普通要求:\n
  2378. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2379. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  2380. 示例如下:\n
  2381. ###剧本名:西昆仑
  2382. ###故事梗概
  2383. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2384. ###剧本亮点
  2385. 亮点1:绝境奇药,生死一线
  2386. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2387. 亮点2:结拜兄妹,化解尴尬
  2388. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2389. 亮点3:纤发夺命,情愫暗涌
  2390. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2391. ###人物关系
  2392. 阿雪与梁萧之间存在兄妹之情。
  2393. ###核心矛盾
  2394. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2395. ###主体列表
  2396. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2397. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2398. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2399. 阴阳球:天地异宝,能化生精气,救人于危难。
  2400. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2401. ###美术风格
  2402. 基础画风风格词:厚涂古风
  2403. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2404. ###场景列表
  2405. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。";
  2406. // 构建消息
  2407. $messages = [
  2408. [
  2409. 'role' => 'system',
  2410. 'content' => $systemPrompt
  2411. ],
  2412. [
  2413. 'role' => 'user',
  2414. 'content' => "以下是文档内容:
  2415. {$content}
  2416. 用户问题:
  2417. {$question}"
  2418. ]
  2419. ];
  2420. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2421. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2422. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2423. if ($model === 'deepseek-chat') {
  2424. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2425. $model = 'deepseek-v4-flash';
  2426. $thinkingMode = 'disabled';
  2427. } elseif ($model === 'deepseek-reasoner') {
  2428. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2429. $model = 'deepseek-v4-flash';
  2430. $thinkingMode = 'enabled';
  2431. }
  2432. $post_data = [
  2433. 'model' => $model,
  2434. 'messages' => $messages,
  2435. // 'max_tokens' => 8192,
  2436. 'temperature' => 0.7,
  2437. 'frequency_penalty' => 0,
  2438. 'presence_penalty' => 0,
  2439. 'response_format' => ['type' => 'text'],
  2440. 'thinking' => ['type'=>$thinkingMode],
  2441. 'stream' => true // 启用流式输出
  2442. ];
  2443. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2444. // 根据模型类型选择调用方法
  2445. $fullContent = '';
  2446. $fullReasoningContent = '';
  2447. $usage = [];
  2448. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2449. // DeepSeek 官方模型使用 DeepSeek API
  2450. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2451. } else {
  2452. // 其他模型使用火山引擎API
  2453. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2454. }
  2455. // 处理流式输出
  2456. if (!is_iterable($streamGenerator)) {
  2457. dLog('deepseek')->error('addChat流式生成器无效', ['generator_type' => gettype($streamGenerator)]);
  2458. Utils::throwError('20003:接口返回数据异常,请重新请求');
  2459. }
  2460. foreach ($streamGenerator as $chunk) {
  2461. if (isset($chunk['type'])) {
  2462. if ($chunk['type'] === 'done') {
  2463. // 最终结果
  2464. $fullContent = $chunk['full_content'];
  2465. $fullReasoningContent = $chunk['full_reasoning'];
  2466. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2467. } else {
  2468. // 逐块yield数据
  2469. yield $chunk;
  2470. }
  2471. }
  2472. }
  2473. dLog('deepseek')->info('完整内容: '.$fullContent);
  2474. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  2475. // 处理完整内容并返回最终结果
  2476. $script_arr = [];
  2477. if ($fullContent) {
  2478. $script_arr = handleScriptContent($fullContent);
  2479. dLog('deepseek')->info('解析内容', $script_arr);
  2480. logDB('deepseek', 'info', '解析内容', $script_arr);
  2481. }
  2482. if (empty($script_arr['roles'])) {
  2483. // 未生成剧本相关内容,保存对话记录并返回提示
  2484. dLog('deepseek')->info('未生成剧本相关的内容');
  2485. try {
  2486. DB::beginTransaction();
  2487. $now = date('Y-m-d H:i:s');
  2488. // 保存对话记录
  2489. $records = [
  2490. [
  2491. 'uid' => $uid,
  2492. 'anime_id' => $anime_id,
  2493. 'sequence' => 0,
  2494. 'role' => 'user',
  2495. 'content' => "用户问题:\n
  2496. {$prompt}\n\n
  2497. 以下是文档内容:\n
  2498. {$content}",
  2499. 'created_at' => $now,
  2500. 'updated_at' => $now
  2501. ],
  2502. [
  2503. 'uid' => $uid,
  2504. 'anime_id' => $anime_id,
  2505. 'sequence' => 0,
  2506. 'role' => 'assistant',
  2507. 'content' => $fullContent,
  2508. 'created_at' => $now,
  2509. 'updated_at' => $now
  2510. ]
  2511. ];
  2512. DB::table('mp_anime_records')->insert($records);
  2513. DB::commit();
  2514. } catch (\Exception $e) {
  2515. DB::rollBack();
  2516. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2517. }
  2518. yield [
  2519. 'type' => 'done',
  2520. 'script' => [],
  2521. 'episode' => [],
  2522. 'answer' => $fullContent,
  2523. 'reasoning' => $fullReasoningContent,
  2524. 'usage' => $usage,
  2525. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  2526. ];
  2527. return;
  2528. }
  2529. // 如果需要生成原文内容,从script_arr中提取
  2530. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  2531. $content = $script_arr['content'];
  2532. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  2533. if (!$content) {
  2534. yield [
  2535. 'type' => 'done',
  2536. 'script' => [],
  2537. 'episode' => [],
  2538. 'answer' => $fullContent,
  2539. 'reasoning' => $fullReasoningContent,
  2540. 'usage' => $usage,
  2541. 'error' => '未生成剧本内容,请调整提示词再试'
  2542. ];
  2543. return;
  2544. }
  2545. }
  2546. // 替换美术风格
  2547. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2548. if ($mappedArtStyle !== '') {
  2549. $script_arr['art_style'] = $mappedArtStyle;
  2550. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2551. }
  2552. // 新建动漫
  2553. $anime_name = getProp($script_arr, 'script_name');
  2554. if (!$anime_name) {
  2555. // 未识别到剧本名,保存对话记录并返回提示
  2556. dLog('deepseek')->info('未能识别到剧本名称');
  2557. try {
  2558. DB::beginTransaction();
  2559. $now = date('Y-m-d H:i:s');
  2560. // 保存对话记录
  2561. $records = [
  2562. [
  2563. 'uid' => $uid,
  2564. 'anime_id' => $anime_id,
  2565. 'sequence' => 0,
  2566. 'role' => 'user',
  2567. 'content' => "用户问题:\n
  2568. {$prompt}\n\n
  2569. 以下是文档内容:\n
  2570. {$content}",
  2571. 'created_at' => $now,
  2572. 'updated_at' => $now
  2573. ],
  2574. [
  2575. 'uid' => $uid,
  2576. 'anime_id' => $anime_id,
  2577. 'sequence' => 0,
  2578. 'role' => 'assistant',
  2579. 'content' => $fullContent,
  2580. 'created_at' => $now,
  2581. 'updated_at' => $now
  2582. ]
  2583. ];
  2584. DB::table('mp_anime_records')->insert($records);
  2585. DB::commit();
  2586. } catch (\Exception $e) {
  2587. DB::rollBack();
  2588. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2589. }
  2590. yield [
  2591. 'type' => 'done',
  2592. 'script' => [],
  2593. 'episode' => [],
  2594. 'answer' => $fullContent,
  2595. 'reasoning' => $fullReasoningContent,
  2596. 'usage' => $usage,
  2597. 'error' => '未能识别到剧本名称,请调整提示词再试'
  2598. ];
  2599. return;
  2600. }
  2601. // 确认对话名称唯一性
  2602. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2603. $anime_name = $anime_name . '_' . date('YmdHis');
  2604. }
  2605. $table_data = [
  2606. 'user_id' => $uid,
  2607. 'anime_name' => $anime_name,
  2608. 'model' => $model,
  2609. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2610. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2611. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2612. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2613. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2614. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2615. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2616. 'status' => '解析完成',
  2617. 'content' => $content,
  2618. 'is_multi' => $is_multi,
  2619. 'generate_status' => '待执行',
  2620. 'updated_at' => date('Y-m-d H:i:s')
  2621. ];
  2622. $single_episode = [];
  2623. try {
  2624. DB::beginTransaction();
  2625. $now = date('Y-m-d H:i:s');
  2626. // 更新动漫大纲
  2627. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2628. if (!$boolen) {
  2629. dLog('deepseek')->info('动漫保存失败', $table_data);
  2630. Utils::throwError('20003:动漫保存失败');
  2631. }
  2632. // 保存对话记录
  2633. $records = [
  2634. [
  2635. 'uid' => $uid,
  2636. 'anime_id' => $anime_id,
  2637. 'sequence' => 0,
  2638. 'role' => 'user',
  2639. 'content' => "用户问题:\n
  2640. {$prompt}\n\n
  2641. 以下是文档内容:\n
  2642. {$content}",
  2643. 'created_at' => date('Y-m-d H:i:s'),
  2644. 'updated_at' => date('Y-m-d H:i:s')
  2645. ],
  2646. [
  2647. 'uid' => $uid,
  2648. 'anime_id' => $anime_id,
  2649. 'sequence' => 0,
  2650. 'role' => 'assistant',
  2651. 'content' => $fullContent,
  2652. 'created_at' => date('Y-m-d H:i:s'),
  2653. 'updated_at' => date('Y-m-d H:i:s')
  2654. ]
  2655. ];
  2656. // 保存对话记录
  2657. $boolen3 = DB::table('mp_anime_records')->insert($records);
  2658. if (!$boolen3) {
  2659. Utils::throwError('20003:对话记录保存失败');
  2660. }
  2661. if ($is_single) {
  2662. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  2663. if (empty($episode_arr['acts'])) {
  2664. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  2665. }
  2666. $saveResult = $this->saveEpisodeVersionData(
  2667. $anime_id,
  2668. 1,
  2669. $episode_arr,
  2670. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  2671. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  2672. null,
  2673. null,
  2674. false,
  2675. $content,
  2676. $now
  2677. );
  2678. $single_episode = $saveResult['episode'];
  2679. $episode_id = $saveResult['episode_id'];
  2680. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  2681. 'roles' => json_encode($saveResult['merged_roles'], 256),
  2682. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  2683. 'updated_at' => $now
  2684. ]);
  2685. if ($boolen5 === false) {
  2686. Utils::throwError('20003:单剧集主表资源同步失败');
  2687. }
  2688. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  2689. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  2690. $episode_record_content = '确认分镜大纲';
  2691. if ($content !== '') {
  2692. $episode_record_content .= "\n\n###上传内容\n" . $content;
  2693. }
  2694. $episode_records = [
  2695. [
  2696. 'uid' => $uid,
  2697. 'anime_id' => $anime_id,
  2698. 'role' => 'user',
  2699. 'content' => $episode_record_content,
  2700. 'sequence' => 1,
  2701. 'episode_id' => $episode_id,
  2702. 'created_at' => $now,
  2703. 'updated_at' => $now
  2704. ],
  2705. [
  2706. 'uid' => $uid,
  2707. 'anime_id' => $anime_id,
  2708. 'role' => 'assistant',
  2709. 'content' => $fullContent,
  2710. 'sequence' => 1,
  2711. 'episode_id' => $episode_id,
  2712. 'created_at' => $now,
  2713. 'updated_at' => $now
  2714. ]
  2715. ];
  2716. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  2717. if (!$boolen4) {
  2718. Utils::throwError('20003:单剧集分镜记录保存失败');
  2719. }
  2720. }
  2721. }catch (\Exception $e) {
  2722. DB::rollBack();
  2723. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2724. yield [
  2725. 'type' => 'done',
  2726. 'answer' => $fullContent,
  2727. 'reasoning' => $fullReasoningContent,
  2728. 'usage' => $usage,
  2729. 'error' => $e->getMessage(),
  2730. ];
  2731. return;
  2732. }
  2733. DB::commit();
  2734. dLog('deepseek')->info('保存完毕');
  2735. if ($is_single && !empty($single_episode)) {
  2736. $this->batchSetGlobalRoleImg([
  2737. 'anime_id' => $anime_id,
  2738. ]);
  2739. $this->batchSetGlobalSceneImg([
  2740. 'anime_id' => $anime_id,
  2741. ]);
  2742. }
  2743. $table_data['anime_id'] = $anime_id;
  2744. $table_data['roles'] = json_decode($table_data['roles'], true);
  2745. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2746. // $table_data['episodes'] = $script_arr['episodes'];
  2747. unset($table_data['created_at']);
  2748. unset($table_data['updated_at']);
  2749. unset($table_data['status']);
  2750. dLog('deepseek')->info('开始返回');
  2751. yield [
  2752. 'type' => 'done',
  2753. 'script' => $table_data,
  2754. 'episode' => $single_episode,
  2755. 'answer' => $fullContent,
  2756. 'reasoning' => $fullReasoningContent,
  2757. 'usage' => $usage
  2758. ];
  2759. }
  2760. public function reGenerateAnime($data) {
  2761. $uid = Site::getUid();
  2762. $file = getProp($data, 'file');
  2763. $content = getProp($data, 'content', '');
  2764. $bid = getProp($data, 'bid', 0);
  2765. $script_id = getProp($data, 'script_id', 0);
  2766. $anime_id = getProp($data, 'anime_id');
  2767. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  2768. if (!$anime) {
  2769. Utils::throwError('20003:该对话不存在');
  2770. }
  2771. $prompt = getProp($data, 'prompt');
  2772. // 处理文本模型
  2773. $model = getProp($data, 'model');
  2774. if (!$model) {
  2775. // 用户没有输入,从anime表获取
  2776. $model = getProp($anime, 'model');
  2777. if (!$model) {
  2778. // anime表也没有,使用默认值
  2779. $model = 'doubao-seed-2-0-mini-260215';
  2780. }
  2781. }
  2782. // 验证模型是否在可用模型表中
  2783. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2784. $model = 'doubao-seed-2-0-mini-260215';
  2785. }
  2786. $is_multi = getProp($anime, 'is_multi', 1);
  2787. $is_single = (int)$is_multi !== 1;
  2788. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  2789. if ($is_single) {
  2790. $episode_exists = DB::table('mp_anime_episodes')
  2791. ->where('anime_id', $anime_id)
  2792. ->where('sequence', 1)
  2793. ->exists();
  2794. if ($episode_exists) {
  2795. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  2796. }
  2797. }
  2798. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2799. // 提取文件内容
  2800. if ($file) {
  2801. $content = $this->extractFileContent($file);
  2802. if (!$content) {
  2803. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2804. }
  2805. } elseif ($script_id) {
  2806. $content = $this->getContentByScriptId($script_id);
  2807. if (!$content) {
  2808. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2809. }
  2810. } elseif ($bid) {
  2811. $content = $this->getContentByBid($bid);
  2812. if (!$content) {
  2813. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2814. }
  2815. } elseif ($content) {
  2816. $content = filterContent($content);
  2817. }else {
  2818. $content = filterContent(getProp($anime, 'content'));
  2819. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2820. $need_generate_content = true;
  2821. }
  2822. }
  2823. // 判断是否需要生成原文内容
  2824. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2825. // 如果需要生成原文内容,添加额外的要求
  2826. $content_generation_requirement = $need_generate_content
  2827. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2828. : "";
  2829. // 美术风格
  2830. $input_art_style = getProp($data, 'art_style');
  2831. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2832. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2833. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2834. 中年女:邻居阿姨
  2835. 老年男:幽默大爷
  2836. 老年女:婆婆
  2837. 萌娃:奶气萌娃";
  2838. $system_message = ['role'=>'system', 'content'=>$is_single
  2839. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2840. 强制要求:
  2841. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2842. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2843. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2844. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2845. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2846. 普通要求:
  2847. 1.剧集标题必须与文档内容高度相关,剧集序号是1。
  2848. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2849. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2850. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2851. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2852. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2853. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2854. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2855. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2856. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2857. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2858. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2859. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2860. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2861. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2862. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2863. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2864. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2865. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2866. 示例如下:\n
  2867. ###剧本名:西昆仑
  2868. ###故事梗概
  2869. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2870. ###剧本亮点
  2871. 亮点1:绝境奇药,生死一线
  2872. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2873. 亮点2:结拜兄妹,化解尴尬
  2874. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2875. 亮点3:纤发夺命,情愫暗涌
  2876. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2877. ###人物关系
  2878. 阿雪与梁萧之间存在兄妹之情。
  2879. ###核心矛盾
  2880. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2881. ###主体列表
  2882. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2883. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2884. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2885. 阴阳球:天地异宝,能化生精气,救人于危难。
  2886. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2887. ###美术风格
  2888. 基础画风风格词:厚涂古风
  2889. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2890. ###场景列表
  2891. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2892. ###分镜剧本
  2893. ##第1幕:徐家老旧厨房 白天 室内
  2894. 分镜1
  2895. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2896. 场景:徐家老旧厨房
  2897. 构图设计:全景,低角度仰视
  2898. 运镜调度:手持拍摄
  2899. 配音角色:旁白
  2900. 出镜角色:许芸-校服装、徐母
  2901. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2902. 画面类型:普通画面
  2903. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2904. 分镜2
  2905. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2906. 场景:徐家老旧厨房
  2907. 构图设计:近景,徐母面部特写
  2908. 运镜调度:固定镜头
  2909. 配音角色:徐母
  2910. 出镜角色:徐母
  2911. 台词内容:问我夜不归宿死哪儿去了。
  2912. 画面类型:对口型
  2913. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2914. ##第2幕:徐家简陋客厅 黄昏 室内
  2915. 分镜3
  2916. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2917. 场景:徐家简陋客厅
  2918. 构图设计:全景,景深虚化
  2919. 运镜调度:固定镜头
  2920. 配音角色:旁白
  2921. 出镜角色:无
  2922. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2923. 画面类型:普通画面
  2924. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2925. 分镜4
  2926. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2927. 场景:徐家简陋客厅
  2928. 构图设计:特写,火车票
  2929. 运镜调度:固定镜头
  2930. 配音角色:旁白
  2931. 出镜角色:无
  2932. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2933. 画面类型:普通画面
  2934. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2935. "
  2936. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2937. 强制要求:\n
  2938. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2939. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2940. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2941. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2942. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2943. 普通要求:\n
  2944. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2945. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  2946. 示例如下:\n
  2947. ###剧本名:西昆仑
  2948. ###故事梗概
  2949. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2950. ###剧本亮点
  2951. 亮点1:绝境奇药,生死一线
  2952. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2953. 亮点2:结拜兄妹,化解尴尬
  2954. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2955. 亮点3:纤发夺命,情愫暗涌
  2956. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2957. ###人物关系
  2958. 阿雪与梁萧之间存在兄妹之情。
  2959. ###核心矛盾
  2960. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2961. ###主体列表
  2962. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2963. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2964. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2965. 阴阳球:天地异宝,能化生精气,救人于危难。
  2966. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2967. ###美术风格
  2968. 基础画风风格词:厚涂古风
  2969. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2970. ###场景列表
  2971. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"];
  2972. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  2973. $episode_count = $this->extractEpisodeNumber($prompt);
  2974. if ((int)getProp($anime, 'is_multi') !== 1) {
  2975. yield [
  2976. 'type' => 'done',
  2977. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  2978. 'reasoning' => '',
  2979. 'usage' => []
  2980. ];
  2981. return;
  2982. }
  2983. if ($episode_count) {
  2984. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  2985. $system_message = [
  2986. 'role' => 'system',
  2987. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2988. 强制要求:\n
  2989. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2990. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2991. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2992. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2993. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2994. 普通要求:\n
  2995. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  2996. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  2997. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  2998. 示例如下:\n
  2999. ###剧本名:西昆仑
  3000. ###故事梗概
  3001. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3002. ###剧本亮点
  3003. 亮点1:绝境奇药,生死一线
  3004. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3005. 亮点2:结拜兄妹,化解尴尬
  3006. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3007. 亮点3:纤发夺命,情愫暗涌
  3008. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3009. ###人物关系
  3010. 阿雪与梁萧之间存在兄妹之情。
  3011. ###核心矛盾
  3012. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3013. ###主体列表
  3014. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3015. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  3016. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3017. 阴阳球:天地异宝,能化生精气,救人于危难。
  3018. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3019. ###美术风格
  3020. 基础画风风格词:厚涂古风
  3021. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3022. ###场景列表
  3023. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  3024. ###分集详细内容
  3025. ##第1章 重生
  3026. 我重生了。
  3027. 源于一个男人偏执的暗恋。
  3028. ##第2章 相救
  3029. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  3030. 我眼睛扫向站在锅炉后的卞大伟。"
  3031. ];
  3032. // 构建消息
  3033. $messages = [
  3034. $system_message,
  3035. [
  3036. 'role' => 'user',
  3037. 'content' => "以下是文档内容:
  3038. {$content}
  3039. 用户问题:
  3040. {$question}"
  3041. ]
  3042. ];
  3043. }else {
  3044. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  3045. // 构建消息
  3046. $messages = [
  3047. $system_message,
  3048. [
  3049. 'role' => 'user',
  3050. 'content' => "以下是文档内容:
  3051. {$content}
  3052. 用户问题:
  3053. {$question}"
  3054. ]
  3055. ];
  3056. }else {
  3057. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  3058. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  3059. return (array)$value;
  3060. })->toArray();
  3061. array_unshift($messages, $system_message);
  3062. $messages[] = [
  3063. 'role' => 'user',
  3064. 'content' => $prompt
  3065. ];
  3066. }
  3067. }
  3068. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3069. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3070. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3071. if ($model === 'deepseek-chat') {
  3072. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3073. $model = 'deepseek-v4-flash';
  3074. $thinkingMode = 'disabled';
  3075. } elseif ($model === 'deepseek-reasoner') {
  3076. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3077. $model = 'deepseek-v4-flash';
  3078. $thinkingMode = 'enabled';
  3079. }
  3080. $post_data = [
  3081. 'model' => $model,
  3082. 'messages' => $messages,
  3083. // 'max_tokens' => 8192,
  3084. 'temperature' => 0.7,
  3085. 'frequency_penalty' => 0,
  3086. 'presence_penalty' => 0,
  3087. 'response_format' => ['type' => 'text'],
  3088. 'thinking' => ['type' => $thinkingMode],
  3089. 'stream' => true // 启用流式输出
  3090. ];
  3091. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3092. // 根据模型类型选择调用方法
  3093. $fullContent = '';
  3094. $fullReasoningContent = '';
  3095. $usage = [];
  3096. // dd($post_data);
  3097. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  3098. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3099. // DeepSeek 官方模型使用 DeepSeek API
  3100. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3101. } else {
  3102. // 其他模型使用火山引擎API
  3103. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3104. }
  3105. // 处理流式输出
  3106. foreach ($streamGenerator as $chunk) {
  3107. if (isset($chunk['type'])) {
  3108. if ($chunk['type'] === 'done') {
  3109. // 最终结果
  3110. $fullContent = $chunk['full_content'];
  3111. $fullReasoningContent = $chunk['full_reasoning'];
  3112. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3113. } else {
  3114. // 逐块yield数据
  3115. yield $chunk;
  3116. }
  3117. }
  3118. }
  3119. dLog('deepseek')->info('完整内容: '.$fullContent);
  3120. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3121. // 处理完整内容并返回最终结果
  3122. $script_arr = [];
  3123. if ($fullContent) {
  3124. $script_arr = handleScriptContent($fullContent);
  3125. dLog('deepseek')->info('解析内容', $script_arr);
  3126. logDB('deepseek', 'info', '解析内容', $script_arr);
  3127. }
  3128. if (empty($script_arr['roles'])) {
  3129. // 未生成剧本相关内容,保存对话记录并返回提示
  3130. dLog('deepseek')->info('未生成剧本相关的内容');
  3131. try {
  3132. $now = date('Y-m-d H:i:s');
  3133. // 保存对话记录
  3134. $records = [
  3135. [
  3136. 'uid' => $uid,
  3137. 'anime_id' => $anime_id,
  3138. 'sequence' => 0,
  3139. 'role' => 'user',
  3140. 'content' => $prompt,
  3141. 'created_at' => $now,
  3142. 'updated_at' => $now
  3143. ],
  3144. [
  3145. 'uid' => $uid,
  3146. 'anime_id' => $anime_id,
  3147. 'sequence' => 0,
  3148. 'role' => 'assistant',
  3149. 'content' => $fullContent,
  3150. 'created_at' => $now,
  3151. 'updated_at' => $now
  3152. ]
  3153. ];
  3154. DB::table('mp_anime_records')->insert($records);
  3155. } catch (\Exception $e) {
  3156. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3157. }
  3158. yield [
  3159. 'type' => 'done',
  3160. 'script' => [],
  3161. 'episode' => [],
  3162. 'answer' => $fullContent,
  3163. 'reasoning' => $fullReasoningContent,
  3164. 'usage' => $usage,
  3165. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3166. ];
  3167. return;
  3168. }
  3169. // 替换美术风格
  3170. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3171. if ($mappedArtStyle !== '') {
  3172. $script_arr['art_style'] = $mappedArtStyle;
  3173. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3174. }
  3175. $table_data = [
  3176. 'user_id' => $uid,
  3177. 'model' => $model,
  3178. 'anime_name' => isset($script_arr['script_name']) ? $script_arr['script_name'] : '',
  3179. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3180. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3181. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3182. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3183. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  3184. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3185. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  3186. 'status' => '解析完成',
  3187. 'generate_status' => '待执行',
  3188. 'updated_at' => date('Y-m-d H:i:s')
  3189. ];
  3190. // 如果是修改集数,则将content内容更新(会改变原文)
  3191. if (isset($episode_count) && $episode_count > 0) {
  3192. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  3193. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  3194. }else {
  3195. // 如果需要生成原文内容,从script_arr中提取
  3196. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3197. $table_data['content'] = $script_arr['content'];
  3198. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  3199. if (!$content) {
  3200. yield [
  3201. 'type' => 'done',
  3202. 'script' => [],
  3203. 'episode' => [],
  3204. 'answer' => $fullContent,
  3205. 'reasoning' => $fullReasoningContent,
  3206. 'usage' => $usage,
  3207. 'error' => '未生成剧本内容,请调整提示词再试'
  3208. ];
  3209. return;
  3210. }
  3211. } else {
  3212. $chapters = $this->splitContent($content);
  3213. $chapter_count = count($chapters);
  3214. if ($chapter_count > 0) {
  3215. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3216. }
  3217. }
  3218. }
  3219. $single_episode = [];
  3220. try {
  3221. DB::beginTransaction();
  3222. $now = date('Y-m-d H:i:s');
  3223. // 更新动漫大纲
  3224. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3225. if (!$boolen) {
  3226. dLog('deepseek')->info('对话修改失败', $table_data);
  3227. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  3228. Utils::throwError('20003:对话修改失败');
  3229. }
  3230. // 保存对话记录
  3231. $records = [
  3232. [
  3233. 'uid' => $uid,
  3234. 'anime_id' => $anime_id,
  3235. 'sequence' => 0,
  3236. 'role' => 'user',
  3237. 'content' => $prompt,
  3238. 'created_at' => $now,
  3239. 'updated_at' => $now
  3240. ],
  3241. [
  3242. 'uid' => $uid,
  3243. 'anime_id' => $anime_id,
  3244. 'sequence' => 0,
  3245. 'role' => 'assistant',
  3246. 'content' => $fullContent,
  3247. 'created_at' => $now,
  3248. 'updated_at' => $now
  3249. ]
  3250. ];
  3251. // 保存对话记录
  3252. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3253. if (!$boolen3) {
  3254. Utils::throwError('20003:对话记录保存失败');
  3255. }
  3256. // 单剧集模式:生成并保存剧集信息
  3257. if ($is_single) {
  3258. $anime_name = getProp($anime, 'anime_name', '未命名');
  3259. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3260. if (empty($episode_arr['acts'])) {
  3261. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3262. }
  3263. $saveResult = $this->saveEpisodeVersionData(
  3264. $anime_id,
  3265. 1,
  3266. $episode_arr,
  3267. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3268. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3269. null,
  3270. null,
  3271. false,
  3272. $content,
  3273. $now
  3274. );
  3275. $single_episode = $saveResult['episode'];
  3276. $episode_id = $saveResult['episode_id'];
  3277. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3278. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3279. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3280. 'updated_at' => $now
  3281. ]);
  3282. if ($boolen5 === false) {
  3283. Utils::throwError('20003:单剧集主表资源同步失败');
  3284. }
  3285. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3286. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3287. $episode_record_content = '确认分镜大纲';
  3288. if ($content !== '') {
  3289. $episode_record_content .= "\n\n###上传内容\n" . $content;
  3290. }
  3291. $episode_records = [
  3292. [
  3293. 'uid' => $uid,
  3294. 'anime_id' => $anime_id,
  3295. 'role' => 'user',
  3296. 'content' => $episode_record_content,
  3297. 'sequence' => 1,
  3298. 'episode_id' => $episode_id,
  3299. 'created_at' => $now,
  3300. 'updated_at' => $now
  3301. ],
  3302. [
  3303. 'uid' => $uid,
  3304. 'anime_id' => $anime_id,
  3305. 'role' => 'assistant',
  3306. 'content' => $fullContent,
  3307. 'sequence' => 1,
  3308. 'episode_id' => $episode_id,
  3309. 'created_at' => $now,
  3310. 'updated_at' => $now
  3311. ]
  3312. ];
  3313. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3314. if (!$boolen4) {
  3315. Utils::throwError('20003:单剧集分镜记录保存失败');
  3316. }
  3317. }
  3318. }catch (\Exception $e) {
  3319. DB::rollBack();
  3320. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  3321. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  3322. yield [
  3323. 'type' => 'done',
  3324. 'answer' => $fullContent,
  3325. 'reasoning' => $fullReasoningContent,
  3326. 'usage' => $usage,
  3327. 'error' => $e->getMessage(),
  3328. ];
  3329. return;
  3330. }
  3331. DB::commit();
  3332. dLog('deepseek')->info('保存完毕');
  3333. if ($is_single && !empty($single_episode)) {
  3334. $this->batchSetGlobalRoleImg([
  3335. 'anime_id' => $anime_id,
  3336. ]);
  3337. $this->batchSetGlobalSceneImg([
  3338. 'anime_id' => $anime_id,
  3339. ]);
  3340. }
  3341. $table_data['anime_id'] = $anime_id;
  3342. $table_data['roles'] = json_decode($table_data['roles'], true);
  3343. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3344. unset($table_data['updated_at']);
  3345. unset($table_data['status']);
  3346. yield [
  3347. 'type' => 'done',
  3348. 'script' => $table_data,
  3349. 'episode' => $single_episode,
  3350. 'answer' => $fullContent,
  3351. 'reasoning' => $fullReasoningContent,
  3352. 'usage' => $usage
  3353. ];
  3354. }
  3355. public function chat($data) {
  3356. $uid = Site::getUid();
  3357. $anime_id = getProp($data, 'anime_id');
  3358. $file = getProp($data, 'file');
  3359. $content = getProp($data, 'content', '');
  3360. $bid = getProp($data, 'bid', 0);
  3361. $script_id = getProp($data, 'script_id', 0);
  3362. $episode_number = getProp($data, 'episode_number', 1);
  3363. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3364. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3365. if (!$anime) Utils::throwError('20003:该对话不存在!');
  3366. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  3367. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  3368. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  3369. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  3370. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  3371. $roles = is_array($roles) ? $roles : [];
  3372. $scenes = is_array($scenes) ? $scenes : [];
  3373. // 转换主体列表和场景列表的格式
  3374. $roles_content = $this->buildEpisodeItemContent($roles, 'role');
  3375. $scenes_content = $this->buildEpisodeItemContent($scenes, 'scene');
  3376. // 获取音色列表
  3377. // $timbres = DB::table('mp_timbres')->select('timbre_name')->where('is_enabled', 1)->where('id', '<=', 15)->get()->map(function ($value) {
  3378. // $value = (array)$value;
  3379. // $value['timbre_name'] = str_replace('(多情感)', '', $value['timbre_name']);
  3380. // return $value;
  3381. // })->pluck('timbre_name')->toArray();
  3382. // $timbres_content = implode('、', $timbres);
  3383. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3384. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3385. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3386. 中年女:邻居阿姨
  3387. 老年男:幽默大爷
  3388. 老年女:婆婆
  3389. 萌娃:奶气萌娃";
  3390. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3391. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3392. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3393. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3394. // 提取文件内容
  3395. if ($file) {
  3396. $uploaded_content = $this->extractFileContent($file);
  3397. if (!$uploaded_content) {
  3398. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3399. }
  3400. } elseif ($script_id) {
  3401. $uploaded_content = $this->getContentByScriptId($script_id);
  3402. if (!$uploaded_content) {
  3403. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3404. }
  3405. } elseif ($bid) {
  3406. $uploaded_content = $this->getContentByBid($bid);
  3407. if (!$uploaded_content) {
  3408. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3409. }
  3410. } elseif ($content) {
  3411. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  3412. }
  3413. // elseif ($prompt) {
  3414. // $uploaded_content = filterContent($prompt);
  3415. // }
  3416. else {
  3417. $uploaded_content = '';
  3418. }
  3419. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3420. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  3421. 强制要求:
  3422. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3423. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3424. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3425. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3426. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3427. 普通要求:
  3428. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  3429. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):\n{$roles_content}。
  3430. 2.1如果分集内容中出现了<主体列表>中不存在的新主体,则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在主题列表中。
  3431. 2.2主体列表的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3432. 3.<场景列表>必须在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,除非出现<场景列表>中不存在的场景,否则不得自定义:\n{$scenes_content}。
  3433. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3434. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3435. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3436. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3437. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3438. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3439. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3440. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3441. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3442. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3443. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3444. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3445. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3446. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3447. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3448. 示例格式:\n
  3449. 第1集:隐形的守护者
  3450. ###故事梗概
  3451. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  3452. ###美术风格
  3453. 基础画风风格词:韩漫二次元
  3454. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  3455. ###主体列表
  3456. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{{甜心小美}}
  3457. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{{爽快思思}}
  3458. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{{阳光青年}}
  3459. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。{{广州德哥}}
  3460. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。{{邻居阿姨}}
  3461. ###场景列表
  3462. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  3463. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  3464. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  3465. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  3466. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  3467. ###分镜剧本
  3468. ##第1幕:徐家老旧厨房 白天 室内
  3469. 分镜1
  3470. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3471. 场景:徐家老旧厨房
  3472. 构图设计:全景,低角度仰视
  3473. 运镜调度:手持拍摄
  3474. 配音角色:旁白
  3475. 出镜角色:许芸-校服装、徐母
  3476. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3477. 画面类型:普通画面
  3478. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3479. 分镜2
  3480. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3481. 场景:徐家老旧厨房
  3482. 构图设计:近景,徐母面部特写
  3483. 运镜调度:固定镜头
  3484. 配音角色:徐母
  3485. 出镜角色:徐母
  3486. 台词内容:问我夜不归宿死哪儿去了。
  3487. 画面类型:对口型
  3488. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3489. ##第2幕:徐家简陋客厅 黄昏 室内
  3490. 分镜3
  3491. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3492. 场景:徐家简陋客厅
  3493. 构图设计:全景,景深虚化
  3494. 运镜调度:固定镜头
  3495. 配音角色:旁白
  3496. 出镜角色:无
  3497. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3498. 画面类型:普通画面
  3499. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3500. 分镜4
  3501. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3502. 场景:徐家简陋客厅
  3503. 构图设计:特写,火车票
  3504. 运镜调度:固定镜头
  3505. 配音角色:旁白
  3506. 出镜角色:无
  3507. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3508. 画面类型:普通画面
  3509. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  3510. \n\n";
  3511. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3512. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  3513. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  3514. $prompt = $origin_prompt;
  3515. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  3516. // 获取章节内容
  3517. $full_content = getProp($anime, 'content');
  3518. // 根据章节内容拆分章节
  3519. $chapters = $this->splitContent($full_content);
  3520. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  3521. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  3522. $messages = [];
  3523. if ($prompt == '确认分镜大纲') {
  3524. $content = $uploaded_content ?: $chapter_content;
  3525. if ($is_single) $content = $full_content; // 单剧集使用全文
  3526. if (!$content) {
  3527. Utils::throwError('20003:章节内容无法获取,请确认');
  3528. }
  3529. $question = $is_single
  3530. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  3531. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  3532. // 构建消息
  3533. $messages[] =
  3534. [
  3535. 'role' => 'user',
  3536. 'content' => $question
  3537. ];
  3538. }else if ($prompt == '继续策划下一集') {
  3539. if ($is_single) {
  3540. Utils::throwError('20003:单剧集不支持继续策划下一集');
  3541. }
  3542. $content = $uploaded_content ?: $chapter_content;
  3543. if (!$content) {
  3544. Utils::throwError('20003:章节内容无法获取,请确认');
  3545. }
  3546. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  3547. // 获取上一集最后记录
  3548. $prev_sequence = $episode_number - 1;
  3549. $messages = $this->getEpisodeChatMessages($anime_id, $prev_sequence);
  3550. // 构建消息
  3551. $messages[] =
  3552. [
  3553. 'role' => 'user',
  3554. 'content' => $question
  3555. ];
  3556. }else {
  3557. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  3558. if (!$content) {
  3559. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  3560. }
  3561. if (!$content) {
  3562. Utils::throwError('20003:章节内容无法获取,请确认');
  3563. }
  3564. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  3565. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  3566. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。"
  3567. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  3568. $messages[] =
  3569. [
  3570. 'role' => 'user',
  3571. 'content' => $question
  3572. ];
  3573. }
  3574. // 处理文本模型
  3575. $model = getProp($data, 'model');
  3576. if (!$model) {
  3577. // 用户没有输入,从anime表获取
  3578. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3579. $model = getProp($anime, 'model');
  3580. if (!$model) {
  3581. // anime表也没有,使用默认值
  3582. $model = 'doubao-seed-2-0-mini-260215';
  3583. }
  3584. }
  3585. // 验证模型是否在可用模型表中
  3586. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3587. $model = 'doubao-seed-2-0-mini-260215';
  3588. }
  3589. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3590. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3591. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3592. if ($model === 'deepseek-chat') {
  3593. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3594. $model = 'deepseek-v4-flash';
  3595. $thinkingMode = 'disabled';
  3596. } elseif ($model === 'deepseek-reasoner') {
  3597. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3598. $model = 'deepseek-v4-flash';
  3599. $thinkingMode = 'enabled';
  3600. }
  3601. $post_data = [
  3602. 'model' => $model,
  3603. 'messages' => $messages,
  3604. // 'max_tokens' => 8192,
  3605. 'temperature' => 0.7,
  3606. 'frequency_penalty' => 0,
  3607. 'presence_penalty' => 0,
  3608. 'response_format' => ['type' => 'text'],
  3609. 'thinking' => ['type' => $thinkingMode],
  3610. 'stream' => true // 启用流式输出
  3611. ];
  3612. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3613. // 根据模型类型选择调用方法
  3614. $fullContent = '';
  3615. $fullReasoningContent = '';
  3616. $usage = [];
  3617. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3618. // DeepSeek 官方模型使用 DeepSeek API
  3619. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3620. } else {
  3621. // 其他模型使用火山引擎API
  3622. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3623. }
  3624. // 处理流式输出
  3625. if (!is_iterable($streamGenerator)) {
  3626. dLog('deepseek')->error('chat流式生成器无效', ['generator_type' => gettype($streamGenerator)]);
  3627. Utils::throwError('20003:接口返回数据异常,请重新请求');
  3628. }
  3629. foreach ($streamGenerator as $chunk) {
  3630. if (isset($chunk['type'])) {
  3631. if ($chunk['type'] === 'done') {
  3632. // 最终结果
  3633. $fullContent = $chunk['full_content'];
  3634. $fullReasoningContent = $chunk['full_reasoning'];
  3635. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3636. } else {
  3637. // 逐块yield数据
  3638. yield $chunk;
  3639. }
  3640. }
  3641. }
  3642. dLog('deepseek')->info('完整内容: '.$fullContent);
  3643. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3644. // 处理完整内容并返回最终结果
  3645. $episode_arr = handleEpisodeContent($fullContent);
  3646. logDB('deepseek', 'info', '解析内容', $episode_arr);
  3647. if (empty($episode_arr['acts'])) {
  3648. // 未生成剧本相关内容,保存对话记录并返回提示
  3649. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  3650. try {
  3651. $now = date('Y-m-d H:i:s');
  3652. // 保存对话记录
  3653. $records = [
  3654. [
  3655. 'uid' => $uid,
  3656. 'anime_id' => $anime_id,
  3657. 'sequence' => $episode_number,
  3658. 'role' => 'user',
  3659. 'content' => $prompt,
  3660. 'created_at' => $now,
  3661. 'updated_at' => $now
  3662. ],
  3663. [
  3664. 'uid' => $uid,
  3665. 'anime_id' => $anime_id,
  3666. 'sequence' => $episode_number,
  3667. 'role' => 'assistant',
  3668. 'content' => $fullContent,
  3669. 'created_at' => $now,
  3670. 'updated_at' => $now
  3671. ]
  3672. ];
  3673. DB::table('mp_anime_records')->insert($records);
  3674. } catch (\Exception $e) {
  3675. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3676. }
  3677. yield [
  3678. 'type' => 'done',
  3679. 'episode' => [],
  3680. 'answer' => $fullContent,
  3681. 'reasoning' => $fullReasoningContent,
  3682. 'usage' => $usage,
  3683. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  3684. ];
  3685. return;
  3686. }
  3687. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3688. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3689. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3690. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3691. $now = date('Y-m-d H:i:s');
  3692. try {
  3693. DB::beginTransaction();
  3694. $saveResult = $this->saveEpisodeVersionData(
  3695. $anime_id,
  3696. $episode_number,
  3697. $episode_arr,
  3698. $existing_roles,
  3699. $existing_scenes,
  3700. $current_episode,
  3701. $base_episode,
  3702. $is_regenerate_version,
  3703. $content,
  3704. $now
  3705. );
  3706. $episode = $saveResult['episode'];
  3707. $episode_id = $saveResult['episode_id'];
  3708. $merged_roles = $saveResult['merged_roles'];
  3709. $merged_scenes = $saveResult['merged_scenes'];
  3710. $record_content = $origin_prompt;
  3711. if ($uploaded_content !== '') {
  3712. $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  3713. }
  3714. $records = [
  3715. [
  3716. 'uid' => $uid,
  3717. 'anime_id' => $anime_id,
  3718. 'role' => 'user',
  3719. 'content' => $record_content,
  3720. 'sequence' => $episode_number,
  3721. 'episode_id' => $episode_id,
  3722. 'created_at' => $now,
  3723. 'updated_at' => $now
  3724. ],
  3725. [
  3726. 'uid' => $uid,
  3727. 'anime_id' => $anime_id,
  3728. 'role' => 'assistant',
  3729. 'content' => $fullContent,
  3730. 'sequence' => $episode_number,
  3731. 'episode_id' => $episode_id,
  3732. 'created_at' => $now,
  3733. 'updated_at' => $now
  3734. ]
  3735. ];
  3736. $boolen4 = DB::table('mp_anime_records')->insert($records);
  3737. if (!$boolen4) {
  3738. Utils::throwError('20003:对话记录保存失败');
  3739. }
  3740. // 保存模型到anime表
  3741. DB::table('mp_animes')->where('id', $anime_id)->update([
  3742. 'model' => $model,
  3743. 'updated_at' => $now
  3744. ]);
  3745. }catch (\Exception $e) {
  3746. DB::rollBack();
  3747. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3748. yield [
  3749. 'type' => 'done',
  3750. 'answer' => $fullContent,
  3751. 'reasoning' => $fullReasoningContent,
  3752. 'usage' => $usage,
  3753. 'error' => $e->getMessage(),
  3754. ];
  3755. return;
  3756. }
  3757. DB::commit();
  3758. if ($is_global_generate_pics) {
  3759. // 批量生成全局角色图片
  3760. $this->batchSetGlobalRoleImg([
  3761. 'anime_id' => $anime_id,
  3762. ]);
  3763. // 批量生成全局场景图片
  3764. $this->batchSetGlobalSceneImg([
  3765. 'anime_id' => $anime_id,
  3766. ]);
  3767. }
  3768. $episode['episode_id'] = $episode_id;
  3769. $episode['roles'] = $merged_roles;
  3770. $episode['scenes'] = $merged_scenes;
  3771. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  3772. yield [
  3773. 'type' => 'done',
  3774. 'episode' => $episode,
  3775. 'answer' => $fullContent,
  3776. 'reasoning' => $fullReasoningContent,
  3777. 'usage' => $usage
  3778. ];
  3779. }
  3780. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  3781. {
  3782. $episode_arr = [
  3783. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  3784. 'intro' => getProp($script_arr, 'intro'),
  3785. 'art_style' => getProp($script_arr, 'art_style'),
  3786. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3787. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3788. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  3789. ];
  3790. if (empty($episode_arr['acts'])) {
  3791. $fallback_episode_arr = handleEpisodeContent($fullContent);
  3792. if (!empty($fallback_episode_arr['acts'])) {
  3793. $episode_arr = array_merge($fallback_episode_arr, [
  3794. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  3795. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  3796. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  3797. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  3798. ]);
  3799. }
  3800. }
  3801. // if (!getProp($episode_arr, 'episode_title')) {
  3802. // $episode_title = '';
  3803. // $episodes = getProp($script_arr, 'episodes', []);
  3804. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  3805. // $episode_title = '第1集:' . $episodes[0]['title'];
  3806. // }
  3807. // if (!$episode_title) {
  3808. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  3809. // }
  3810. // $episode_arr['episode_title'] = $episode_title;
  3811. // }
  3812. return $episode_arr;
  3813. }
  3814. private function saveEpisodeVersionData(
  3815. int $anime_id,
  3816. int $episode_number,
  3817. array $episode_arr,
  3818. array $existing_roles,
  3819. array $existing_scenes,
  3820. $current_episode,
  3821. $base_episode,
  3822. bool $is_regenerate_version,
  3823. string $content,
  3824. string $now
  3825. ): array {
  3826. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  3827. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  3828. $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  3829. $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  3830. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  3831. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3832. $global_roles = json_decode(getProp($anime, 'roles'), true);
  3833. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  3834. $global_roles = is_array($global_roles) ? $global_roles : [];
  3835. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  3836. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  3837. // 检查并创建 roles 的图片生成任务
  3838. $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  3839. // 检查并创建 scenes 的图片生成任务
  3840. $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  3841. $role_arr = [];
  3842. foreach ($merged_roles as $item) {
  3843. $role_arr[$item['role']] = $item;
  3844. }
  3845. $version_count = DB::table('mp_anime_episodes')
  3846. ->where('anime_id', $anime_id)
  3847. ->where('episode_number', $episode_number)
  3848. ->count('id');
  3849. $episode = [
  3850. 'anime_id' => $anime_id,
  3851. 'episode_number' => $episode_number,
  3852. 'title' => getProp($episode_arr, 'episode_title'),
  3853. 'content' => $content,
  3854. 'intro' => getProp($episode_arr, 'intro'),
  3855. 'art_style' => getProp($episode_arr, 'art_style'),
  3856. 'roles' => json_encode($merged_roles, 256),
  3857. 'scenes' => json_encode($merged_scenes, 256),
  3858. 'generate_status' => '待执行',
  3859. 'generate_at' => $now,
  3860. 'is_default' => 1,
  3861. 'updated_at' => $now,
  3862. ];
  3863. $del_flag = false;
  3864. if ($is_regenerate_version) {
  3865. DB::table('mp_anime_episodes')
  3866. ->where('anime_id', $anime_id)
  3867. ->where('episode_number', $episode_number)
  3868. ->update(['is_default' => 0, 'updated_at' => $now]);
  3869. $episode['sequence'] = $version_count + 1;
  3870. $episode['created_at'] = $now;
  3871. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  3872. if (!$episode_id) {
  3873. Utils::throwError('20003:创建剧集版本失败');
  3874. }
  3875. } else {
  3876. $target_episode = $current_episode ?: $base_episode;
  3877. if ($target_episode) {
  3878. $episode_id = getProp($target_episode, 'id');
  3879. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  3880. DB::table('mp_anime_episodes')
  3881. ->where('anime_id', $anime_id)
  3882. ->where('episode_number', $episode_number)
  3883. ->where('id', '<>', $episode_id)
  3884. ->update(['is_default' => 0, 'updated_at' => $now]);
  3885. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  3886. if ($boolen === false) {
  3887. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  3888. Utils::throwError('20003:分集内容保存失败');
  3889. }
  3890. $del_flag = true;
  3891. } else {
  3892. DB::table('mp_anime_episodes')
  3893. ->where('anime_id', $anime_id)
  3894. ->where('episode_number', $episode_number)
  3895. ->update(['is_default' => 0, 'updated_at' => $now]);
  3896. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  3897. $episode['created_at'] = $now;
  3898. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  3899. if (!$episode_id) {
  3900. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  3901. Utils::throwError('20003:分集内容保存失败');
  3902. }
  3903. }
  3904. }
  3905. $segments = [];
  3906. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  3907. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3908. $emotion_list = array_flip($emotion_list);
  3909. foreach ($acts as $act) {
  3910. $act_segments = getProp($act, 'segments', []);
  3911. if (!is_array($act_segments)) {
  3912. continue;
  3913. }
  3914. foreach ($act_segments as $segment) {
  3915. $voice_actor = getProp($segment, 'voice_actor');
  3916. $timbre_info = isset($role_arr[$voice_actor]) ? $role_arr[$voice_actor] : [];
  3917. $voice_type = getProp($timbre_info, 'voice_type');
  3918. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3919. if ($timbre_emotion) {
  3920. $timbre_emotion = explode(',', $timbre_emotion);
  3921. } else {
  3922. $timbre_emotion = [];
  3923. }
  3924. $emotion = getProp($segment, 'emotion', '中性');
  3925. if (!in_array($emotion, $timbre_emotion)) {
  3926. $emotion = '中性';
  3927. }
  3928. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3929. $segments[] = [
  3930. 'anime_id' => $anime_id,
  3931. 'episode_id' => $episode_id,
  3932. 'episode_number' => $episode_number,
  3933. 'act_number' => getProp($act, 'act_number'),
  3934. 'act_title' => getProp($act, 'act_title'),
  3935. 'segment_id' => getProp($segment, 'segment_id'),
  3936. 'segment_number' => getProp($segment, 'segment_number'),
  3937. 'segment_content' => getProp($segment, 'segment_content'),
  3938. 'description' => getProp($segment, 'description'),
  3939. 'composition' => getProp($segment, 'composition'),
  3940. 'camera_movement' => getProp($segment, 'camera_movement'),
  3941. 'voice_actor' => $voice_actor,
  3942. 'dialogue' => getProp($segment, 'dialogue'),
  3943. 'frame_type' => getProp($segment, 'frame_type'),
  3944. 'scene' => getProp($segment, 'scene'),
  3945. 'characters' => getProp($segment, 'characters'),
  3946. 'tail_frame' => getProp($segment, 'tail_frame'),
  3947. 'voice_name' => getProp($timbre_info, 'voice_name'),
  3948. 'voice_type' => $voice_type,
  3949. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  3950. 'emotion' => $emotion,
  3951. 'emotion_type' => $emotion_type,
  3952. 'gender' => getProp($segment, 'gender', '0'),
  3953. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  3954. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  3955. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  3956. 'pitch' => getProp($segment, 'pitch', 0),
  3957. 'created_at' => $now,
  3958. 'updated_at' => $now
  3959. ];
  3960. }
  3961. }
  3962. if ($segments) {
  3963. if ($del_flag) {
  3964. DB::table('mp_episode_segments')
  3965. ->where('anime_id', $anime_id)
  3966. ->where('episode_id', $episode_id)
  3967. ->delete();
  3968. }
  3969. $boolen = DB::table('mp_episode_segments')->insert($segments);
  3970. if (!$boolen) {
  3971. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  3972. Utils::throwError('20003:分镜内容保存失败');
  3973. }
  3974. }
  3975. $episode['episode_id'] = $episode_id;
  3976. $episode['roles'] = $merged_roles;
  3977. $episode['scenes'] = $merged_scenes;
  3978. $episode['acts'] = $acts;
  3979. return [
  3980. 'episode' => $episode,
  3981. 'episode_id' => $episode_id,
  3982. 'merged_roles' => $merged_roles,
  3983. 'merged_scenes' => $merged_scenes,
  3984. ];
  3985. }
  3986. private function buildEpisodeItemContent(array $items, string $nameKey): string
  3987. {
  3988. $content = '';
  3989. foreach ($items as $item) {
  3990. $name = trim((string)getProp($item, $nameKey));
  3991. if ($name === '') {
  3992. continue;
  3993. }
  3994. $description = trim((string)getProp($item, 'description'));
  3995. $content .= $name . ': ' . $description . "\n";
  3996. }
  3997. return trim($content);
  3998. }
  3999. private function getEpisodeChatMessages($animeId, $sequence): array
  4000. {
  4001. if ((int)$sequence <= 0) {
  4002. return [];
  4003. }
  4004. return DB::table('mp_anime_records')
  4005. ->where('anime_id', $animeId)
  4006. ->where('sequence', $sequence)
  4007. ->select('role', 'content')
  4008. ->orderBy('created_at')
  4009. ->orderBy('id')
  4010. ->get()
  4011. ->map(function ($value) {
  4012. return (array)$value;
  4013. })
  4014. ->toArray();
  4015. }
  4016. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  4017. {
  4018. $existingMap = [];
  4019. foreach ($existingItems as $item) {
  4020. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4021. if ($itemKey === '') {
  4022. continue;
  4023. }
  4024. $existingMap[$itemKey] = $item;
  4025. }
  4026. if (!$generatedItems) {
  4027. return array_values($existingItems);
  4028. }
  4029. $merged = [];
  4030. foreach ($generatedItems as $item) {
  4031. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4032. if ($itemKey === '') {
  4033. continue;
  4034. }
  4035. if (isset($existingMap[$itemKey])) {
  4036. if (trim((string)getProp($item, 'description')) === '') {
  4037. $merged[] = $existingMap[$itemKey];
  4038. continue;
  4039. }
  4040. // 检查内容是否发生变化
  4041. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  4042. if (!$isChanged) {
  4043. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  4044. $mergedItem = [
  4045. $nameKey => trim((string)getProp($item, $nameKey)),
  4046. 'description' => trim((string)getProp($item, 'description')),
  4047. ];
  4048. // 继承现有项的 URL
  4049. $existingUrl = getProp($existingMap[$itemKey], 'url');
  4050. if (!empty($existingUrl)) {
  4051. $mergedItem['url'] = $existingUrl;
  4052. }
  4053. // 继承现有项的 task_id
  4054. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  4055. if (!empty($existingTaskId)) {
  4056. $mergedItem['task_id'] = $existingTaskId;
  4057. }
  4058. // 继承现有项的 task_status
  4059. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  4060. if (!empty($existingTaskStatus)) {
  4061. $mergedItem['task_status'] = $existingTaskStatus;
  4062. }
  4063. // 保留生成项的音色字段
  4064. $voiceName = getProp($item, 'voice_name');
  4065. if (!empty($voiceName)) {
  4066. $mergedItem['voice_name'] = $voiceName;
  4067. }
  4068. $voiceType = getProp($item, 'voice_type');
  4069. if (!empty($voiceType)) {
  4070. $mergedItem['voice_type'] = $voiceType;
  4071. }
  4072. $audioUrl = getProp($item, 'voice_audio_url');
  4073. if (!empty($audioUrl)) {
  4074. $mergedItem['voice_audio_url'] = $audioUrl;
  4075. }
  4076. $merged[] = $mergedItem;
  4077. } else {
  4078. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  4079. $mergedItem = [
  4080. $nameKey => trim((string)getProp($item, $nameKey)),
  4081. 'description' => trim((string)getProp($item, 'description')),
  4082. ];
  4083. // 保留生成项的音色字段
  4084. $voiceName = getProp($item, 'voice_name');
  4085. if (!empty($voiceName)) {
  4086. $mergedItem['voice_name'] = $voiceName;
  4087. }
  4088. $voiceType = getProp($item, 'voice_type');
  4089. if (!empty($voiceType)) {
  4090. $mergedItem['voice_type'] = $voiceType;
  4091. }
  4092. $audioUrl = getProp($item, 'voice_audio_url');
  4093. if (!empty($audioUrl)) {
  4094. $mergedItem['voice_audio_url'] = $audioUrl;
  4095. }
  4096. // 不继承 URL、task_id 和 task_status(重置状态)
  4097. $merged[] = $mergedItem;
  4098. }
  4099. } else {
  4100. // 新增项,保留生成项的所有字段
  4101. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url']);
  4102. }
  4103. }
  4104. return $merged ?: array_values($existingItems);
  4105. }
  4106. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  4107. {
  4108. $resetItem = [
  4109. $nameKey => trim((string)getProp($item, $nameKey)),
  4110. 'description' => trim((string)getProp($item, 'description')),
  4111. ];
  4112. // 保留指定的字段
  4113. foreach ($preserveFields as $field) {
  4114. $value = getProp($item, $field);
  4115. if (!empty($value)) {
  4116. $resetItem[$field] = $value;
  4117. }
  4118. }
  4119. return $resetItem;
  4120. }
  4121. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  4122. {
  4123. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  4124. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  4125. if ($existingKey !== $generatedKey) {
  4126. return true;
  4127. }
  4128. return trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'));
  4129. }
  4130. private function normalizeEpisodeResourceKey($value): string
  4131. {
  4132. $value = trim((string)$value);
  4133. if ($value === '') {
  4134. return '';
  4135. }
  4136. return strtolower((string)preg_replace('/\s+/u', '', $value));
  4137. }
  4138. // 生成全局角色图片
  4139. private function batchSetGlobalRoleImg($data, $is_force=false) {
  4140. $anime_id = getProp($data, 'anime_id');
  4141. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4142. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4143. $roles = json_decode(getProp($anime, 'roles'), true);
  4144. $art_style = getProp($anime, 'art_style');
  4145. $update_flag = false;
  4146. foreach ($roles as &$role) {
  4147. $role_name = getProp($role, 'role');
  4148. if ($role_name == '旁白') continue;
  4149. $description = getProp($role, 'description');
  4150. if ($art_style) $description = "美术风格:\n$art_style\n主体描述:$description";
  4151. // 参考图地址
  4152. $ref_img_url = getProp($role, 'url');
  4153. if (!$is_force && $ref_img_url) continue;
  4154. $update_flag = true;
  4155. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4156. try {
  4157. $params = [
  4158. 'prompt' => $description,
  4159. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4160. ];
  4161. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4162. $task_id = $task->id;
  4163. if (!$task_id) {
  4164. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  4165. }
  4166. $role['task_id'] = $task_id;
  4167. $role['task_status'] = 'processing';
  4168. } catch (\Exception $e) {
  4169. Utils::throwError("20003:" . $e->getMessage());
  4170. }
  4171. }
  4172. if (!$update_flag) return true;
  4173. // 保存角色信息
  4174. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4175. 'roles' => json_encode($roles, 256),
  4176. 'generate_status' => '执行中',
  4177. 'generate_at' => date('Y-m-d H:i:s'),
  4178. 'updated_at' => date('Y-m-d H:i:s')
  4179. ]);
  4180. if (!$boolen) {
  4181. Utils::throwError('20003:保存角色信息失败');
  4182. }
  4183. return $boolen;
  4184. }
  4185. // 生成全局场景图片
  4186. private function batchSetGlobalSceneImg($data, $is_force=false) {
  4187. $anime_id = getProp($data, 'anime_id');
  4188. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4189. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4190. $scenes = json_decode(getProp($anime, 'scenes'), true);
  4191. $art_style = getProp($anime, 'art_style');
  4192. $update_flag = false;
  4193. foreach ($scenes as &$scene) {
  4194. $scene_name = getProp($scene, 'scene');
  4195. $description = getProp($scene, 'description');
  4196. if ($art_style) $description = "美术风格:\n$art_style\n\n场景描述:$description";
  4197. // 参考图地址
  4198. $ref_img_url = getProp($scene, 'url');
  4199. if (!$is_force && $ref_img_url) continue;
  4200. $update_flag = true;
  4201. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4202. try {
  4203. $params = [
  4204. 'prompt' => $description,
  4205. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4206. ];
  4207. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4208. $task_id = $task->id;
  4209. if (!$task_id) {
  4210. Utils::throwError("20003: 角色({$scene_name})生成图片失败");
  4211. }
  4212. $scene['task_id'] = $task_id;
  4213. $scene['task_status'] = 'processing';
  4214. } catch (\Exception $e) {
  4215. Utils::throwError("20003:" . $e->getMessage());
  4216. }
  4217. }
  4218. if (!$update_flag) return true;
  4219. // 保存角色信息
  4220. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4221. 'scenes' => json_encode($scenes, 256),
  4222. 'generate_status' => '执行中',
  4223. 'generate_at' => date('Y-m-d H:i:s'),
  4224. 'updated_at' => date('Y-m-d H:i:s')
  4225. ]);
  4226. if (!$boolen) {
  4227. Utils::throwError('20003:保存角色信息失败');
  4228. }
  4229. return $boolen;
  4230. }
  4231. public function chatChangeImg($data) {
  4232. $segment = getProp($data, 'segment');
  4233. $segment_content = getProp($segment, 'segment_content');
  4234. $prompt = getProp($data, 'prompt');
  4235. $ref_img = getProp($data, 'ref_img');
  4236. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  4237. // 处理文本模型
  4238. $model = getProp($data, 'model');
  4239. if (!$model) {
  4240. // 用户没有输入,从anime表获取
  4241. $segment_id = getProp($segment, 'segment_id');
  4242. if ($segment_id) {
  4243. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  4244. if ($episode_id) {
  4245. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  4246. if ($anime_id) {
  4247. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  4248. }
  4249. }
  4250. }
  4251. if (!$model) {
  4252. // anime表也没有,使用默认值
  4253. $model = 'doubao-seed-2-0-mini-260215';
  4254. }
  4255. }
  4256. // 验证模型是否在可用模型表中
  4257. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4258. $model = 'doubao-seed-2-0-mini-260215';
  4259. }
  4260. $messages[] =
  4261. [
  4262. 'role' => 'user',
  4263. 'content' => $question
  4264. ];
  4265. $post_data = [
  4266. 'model' => $model,
  4267. 'messages' => $messages,
  4268. // 'max_tokens' => 8192,
  4269. 'temperature' => 0.7,
  4270. 'frequency_penalty' => 0,
  4271. 'presence_penalty' => 0,
  4272. 'response_format' => ['type' => 'text'],
  4273. 'stream' => false // 是否启用流式输出
  4274. ];
  4275. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4276. // DeepSeek 官方模型使用 DeepSeek API
  4277. $chatResult = $this->chatOnly($post_data);
  4278. } else {
  4279. // 其他模型使用火山引擎API
  4280. $chatResult = $this->volcEngineChatCompletion($post_data);
  4281. }
  4282. if (is_array($chatResult)) {
  4283. extract($chatResult);
  4284. }else {
  4285. Utils::throwError('20003: 接口调用失败!');
  4286. }
  4287. return [
  4288. 'type' => 'done',
  4289. // 'episode' => $episode,
  4290. 'answer' => $fullContent,
  4291. 'reasoning' => $fullReasoningContent,
  4292. 'usage' => $usage
  4293. ];
  4294. }
  4295. // 仅调用deepseek对话接口
  4296. private function chatOnly($post_data) {
  4297. $client = new Client(['timeout' => 1200, 'verify' => false]);
  4298. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  4299. $response = $result->getBody()->getContents();
  4300. $response_arr = json_decode($response, true);
  4301. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  4302. $fullContent = '';
  4303. $fullReasoningContent = [];
  4304. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  4305. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  4306. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  4307. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  4308. }
  4309. return [
  4310. 'fullContent' => $fullContent,
  4311. 'fullReasoningContent' => $fullReasoningContent,
  4312. 'usage' => $usage
  4313. ];
  4314. }
  4315. private function splitContent($content) {
  4316. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4317. $chapters = [];
  4318. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  4319. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  4320. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  4321. foreach ($matches as $match) {
  4322. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  4323. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  4324. if (!empty($title) && !empty($chapterContent)) {
  4325. $chapters[] = [
  4326. 'title' => $title,
  4327. 'content' => $chapterContent
  4328. ];
  4329. }
  4330. }
  4331. }else {
  4332. $chapters[] = [
  4333. 'title' => '',
  4334. 'content' => $content
  4335. ];
  4336. }
  4337. return $chapters;
  4338. }
  4339. public function getContentByBid($bid) {
  4340. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  4341. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  4342. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  4343. $content = '';
  4344. foreach ($chapters as $chapter) {
  4345. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  4346. }
  4347. return $content;
  4348. }
  4349. public function getContentByScriptId($script_id) {
  4350. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  4351. if (!$content) $content = '';
  4352. return $content;
  4353. }
  4354. /**
  4355. * 根据文件类型提取文本内容
  4356. *
  4357. * @param mixed $file 文件对象或文件路径
  4358. * @return string
  4359. */
  4360. public function extractFileContent($file) {
  4361. // 获取文件路径和扩展名
  4362. if (is_string($file)) {
  4363. $filePath = $file;
  4364. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  4365. } else {
  4366. // Laravel UploadedFile 对象
  4367. $filePath = $file->getRealPath();
  4368. $extension = strtolower($file->getClientOriginalExtension());
  4369. }
  4370. $content = '';
  4371. switch ($extension) {
  4372. case 'txt':
  4373. $content = $this->extractTxtContent($filePath);
  4374. break;
  4375. case 'pdf':
  4376. $content = $this->extractPdfContent($filePath);
  4377. break;
  4378. case 'doc':
  4379. case 'docx':
  4380. $content = $this->extractWordContent($filePath);
  4381. break;
  4382. // case 'jpg':
  4383. // case 'jpeg':
  4384. // case 'png':
  4385. // case 'gif':
  4386. // case 'bmp':
  4387. // case 'webp':
  4388. // $content = $this->extractImageContent($filePath);
  4389. // break;
  4390. default:
  4391. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  4392. }
  4393. return $content;
  4394. }
  4395. /**
  4396. * 提取 TXT 文件内容
  4397. */
  4398. private function extractTxtContent($filePath) {
  4399. if (!file_exists($filePath)) {
  4400. Utils::throwError('20003:文件不存在');
  4401. }
  4402. $content = file_get_contents($filePath);
  4403. // 尝试检测并转换编码
  4404. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  4405. if ($encoding && $encoding !== 'UTF-8') {
  4406. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  4407. }
  4408. return trim($content);
  4409. }
  4410. /**
  4411. * 提取 PDF 文件内容
  4412. */
  4413. private function extractPdfContent($filePath) {
  4414. if (!file_exists($filePath)) {
  4415. Utils::throwError('20003:文件不存在');
  4416. }
  4417. try {
  4418. $parser = new PdfParser();
  4419. $pdf = $parser->parseFile($filePath);
  4420. $content = $pdf->getText();
  4421. return trim($content);
  4422. } catch (\Exception $e) {
  4423. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  4424. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  4425. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  4426. }
  4427. }
  4428. /**
  4429. * 提取 Word 文件内容(支持 doc 和 docx)
  4430. */
  4431. private function extractWordContent($filePath) {
  4432. if (!file_exists($filePath)) {
  4433. Utils::throwError('20003:文件不存在');
  4434. }
  4435. try {
  4436. $phpWord = WordIOFactory::load($filePath);
  4437. $content = '';
  4438. foreach ($phpWord->getSections() as $section) {
  4439. foreach ($section->getElements() as $element) {
  4440. $content .= $this->extractWordElementText($element);
  4441. }
  4442. }
  4443. return trim($content);
  4444. } catch (\Exception $e) {
  4445. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  4446. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  4447. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  4448. }
  4449. }
  4450. /**
  4451. * 递归提取 Word 元素中的文本
  4452. */
  4453. private function extractWordElementText($element) {
  4454. $text = '';
  4455. if (method_exists($element, 'getText')) {
  4456. $text .= $element->getText() . "\n";
  4457. } elseif (method_exists($element, 'getElements')) {
  4458. foreach ($element->getElements() as $childElement) {
  4459. $text .= $this->extractWordElementText($childElement);
  4460. }
  4461. }
  4462. return $text;
  4463. }
  4464. /**
  4465. * 提取图片内容(使用火山引擎 OCR)
  4466. */
  4467. private function extractImageContent($filePath) {
  4468. if (!file_exists($filePath)) {
  4469. Utils::throwError('20003:文件不存在');
  4470. }
  4471. try {
  4472. // 读取图片并转换为 base64
  4473. $imageData = file_get_contents($filePath);
  4474. $base64Image = base64_encode($imageData);
  4475. // 调用火山引擎 OCR 服务
  4476. $content = $this->callVolcEngineOCR($base64Image);
  4477. return trim($content);
  4478. } catch (\Exception $e) {
  4479. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  4480. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  4481. Utils::throwError('20003:图片识别失败');
  4482. }
  4483. }
  4484. /**
  4485. * 调用火山引擎 OCR 服务识别图片文字
  4486. *
  4487. * @param string $base64Image base64 编码的图片数据
  4488. * @return string 识别的文字内容
  4489. */
  4490. private function callVolcEngineOCR($base64Image) {
  4491. $method = 'POST';
  4492. $service = 'cv';
  4493. $host = 'visual.volcengineapi.com';
  4494. $region = env('VOLC_REGION', 'cn-north-1');
  4495. $access_key = env('VOLC_AK');
  4496. $secret_key = env('VOLC_SK');
  4497. $action = 'OCRNormal';
  4498. $version = '2020-08-26';
  4499. if (!$access_key || !$secret_key) {
  4500. Utils::throwError('20003:请配置火山引擎 AK/SK');
  4501. }
  4502. // 请求体
  4503. $body = json_encode([
  4504. 'image_base64' => $base64Image
  4505. ]);
  4506. // 生成签名
  4507. $headers = $this->getVolcEngineSignHeaders(
  4508. $method, $service, $host, $region,
  4509. "Action={$action}&Version={$version}",
  4510. $access_key, $secret_key, $body
  4511. );
  4512. $client = new Client(['timeout' => 60, 'verify' => false]);
  4513. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  4514. 'headers' => $headers,
  4515. 'body' => $body
  4516. ]);
  4517. $response_arr = json_decode($response->getBody()->getContents(), true);
  4518. // 提取识别的文字
  4519. $textLines = [];
  4520. if (isset($response_arr['data']['line_texts'])) {
  4521. $textLines = $response_arr['data']['line_texts'];
  4522. } elseif (isset($response_arr['data']['ocr_infos'])) {
  4523. foreach ($response_arr['data']['ocr_infos'] as $info) {
  4524. if (isset($info['text'])) {
  4525. $textLines[] = $info['text'];
  4526. }
  4527. }
  4528. }
  4529. if (empty($textLines)) {
  4530. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  4531. return '';
  4532. }
  4533. return implode("\n", $textLines);
  4534. }
  4535. /**
  4536. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  4537. */
  4538. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  4539. $contentType = 'application/json';
  4540. $accept = 'application/json';
  4541. // 获取当前UTC时间
  4542. $t = new DateTime('now', new DateTimeZone('UTC'));
  4543. $xDate = $t->format('Ymd\THis\Z');
  4544. $dateStamp = $t->format('Ymd');
  4545. // 计算 body 的 sha256 哈希
  4546. $payloadHash = hash('sha256', $body);
  4547. // 1. 拼接规范请求串
  4548. $canonicalUri = '/';
  4549. $canonicalQueryString = $queryString;
  4550. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  4551. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  4552. $canonicalRequest = implode("\n", [
  4553. $method,
  4554. $canonicalUri,
  4555. $canonicalQueryString,
  4556. $canonicalHeaders,
  4557. $signedHeaders,
  4558. $payloadHash
  4559. ]);
  4560. // 2. 拼接待签名字符串
  4561. $algorithm = 'HMAC-SHA256';
  4562. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  4563. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  4564. $stringToSign = implode("\n", [
  4565. $algorithm,
  4566. $xDate,
  4567. $credentialScope,
  4568. $hashedCanonicalRequest
  4569. ]);
  4570. // 3. 计算签名
  4571. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  4572. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  4573. // 4. 添加签名到请求头
  4574. $authorizationHeader = sprintf(
  4575. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4576. $algorithm,
  4577. $access_key,
  4578. $credentialScope,
  4579. $signedHeaders,
  4580. $signature
  4581. );
  4582. return [
  4583. 'Accept' => $accept,
  4584. 'Content-Type' => $contentType,
  4585. 'Host' => $host,
  4586. 'X-Date' => $xDate,
  4587. 'X-Content-Sha256'=> $payloadHash,
  4588. 'Authorization' => $authorizationHeader
  4589. ];
  4590. }
  4591. public function generateScriptWords($cid, $model = 'r1') {
  4592. ini_set('max_execution_time', 0);
  4593. if (!$cid) Utils::throwError('20003: 请选择章节!');
  4594. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  4595. // 模型兼容性处理和思考模式设置
  4596. $thinkingMode = 'disabled';
  4597. $reasoningEffort = 'high';
  4598. if ($model == 'r1') {
  4599. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  4600. $thinkingMode = 'enabled';
  4601. } else {
  4602. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  4603. $thinkingMode = 'disabled';
  4604. }
  4605. $messages = [
  4606. [
  4607. 'role' => 'system',
  4608. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  4609. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  4610. 2.非对话部分请全部用旁白角色代替
  4611. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  4612. ],
  4613. [
  4614. 'role' => 'user',
  4615. 'content' => $content
  4616. ]
  4617. ];
  4618. $post_data = [
  4619. 'model' => $model,
  4620. 'messages' => $messages,
  4621. // 'max_tokens' => 8192,
  4622. 'temperature' => 1,
  4623. 'frequency_penalty' => 0,
  4624. 'presence_penalty' => 0,
  4625. 'thinking' => ['type' => $thinkingMode],
  4626. 'response_format' => [
  4627. 'type' => 'text'
  4628. ],
  4629. 'stream' => false
  4630. ];
  4631. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4632. // 根据模型类型选择调用方法
  4633. $fullContent = '';
  4634. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4635. // DeepSeek 官方模型使用 DeepSeek API
  4636. $chatResult = $this->chatOnly($post_data);
  4637. } else {
  4638. // 其他模型使用火山引擎API
  4639. $chatResult = $this->volcEngineChatCompletion($post_data);
  4640. }
  4641. if (is_array($chatResult)) {
  4642. $fullContent = $chatResult['fullContent'];
  4643. }
  4644. return $fullContent;
  4645. }
  4646. /**
  4647. * 智能化解析集数信息
  4648. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  4649. *
  4650. * @param string $prompt 用户输入的提示词
  4651. * @return int|null 解析出的集数,如果没有找到则返回null
  4652. */
  4653. private function extractEpisodeNumber($prompt)
  4654. {
  4655. if (empty($prompt)) {
  4656. return null;
  4657. }
  4658. // 定义各种可能的表达模式
  4659. $patterns = [
  4660. // 基本模式:改成N集、调整成N集、修改成N集
  4661. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  4662. // 扩展模式:分成N集、拆分成N集、分割成N集
  4663. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  4664. // 数量模式:N集、共N集、总共N集
  4665. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  4666. // 制作模式:制作N集、生成N集、创建N集
  4667. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  4668. // 计划模式:计划N集、预计N集、打算N集
  4669. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  4670. // 需要模式:需要N集、要N集
  4671. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  4672. // 中文数字模式:改成三集、调整成五集等
  4673. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  4674. // 英文数字模式
  4675. '/(?: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',
  4676. ];
  4677. // 中文数字转阿拉伯数字的映射
  4678. $chineseNumbers = [
  4679. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  4680. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  4681. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  4682. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  4683. ];
  4684. // 逐个尝试匹配模式
  4685. foreach ($patterns as $pattern) {
  4686. if (preg_match($pattern, $prompt, $matches)) {
  4687. $number = trim($matches[1]);
  4688. // 如果是中文数字,转换为阿拉伯数字
  4689. if (isset($chineseNumbers[$number])) {
  4690. return $chineseNumbers[$number];
  4691. }
  4692. // 如果是阿拉伯数字,直接返回
  4693. if (is_numeric($number)) {
  4694. $episodeNum = intval($number);
  4695. // 合理性检查:集数应该在1-100之间
  4696. if ($episodeNum >= 1 && $episodeNum <= 100) {
  4697. return $episodeNum;
  4698. }
  4699. }
  4700. }
  4701. }
  4702. return null;
  4703. }
  4704. /**
  4705. * 调用火山引擎对话(Chat) API
  4706. *
  4707. * @param array $params 包含以下参数:
  4708. * - model: 模型ID(必填)
  4709. * - messages: 消息列表(必填)
  4710. * - stream: 是否流式输出(可选,默认false)
  4711. * - max_tokens: 最大输出token数(可选)
  4712. * - temperature: 采样温度(可选,默认1)
  4713. * - top_p: 核采样概率(可选,默认0.7)
  4714. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  4715. * - presence_penalty: 存在惩罚系数(可选,默认0)
  4716. * - stop: 停止词(可选)
  4717. * - tools: 工具列表(可选)
  4718. * @return array|Generator 非流式返回数组,流式返回生成器
  4719. */
  4720. public function volcEngineChatCompletion(array $params)
  4721. {
  4722. $apiKey = env('VOLC_AI_API_KEY');
  4723. if (empty($apiKey)) {
  4724. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  4725. }
  4726. // 构建请求参数
  4727. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  4728. $requestData = [
  4729. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  4730. 'messages' => $params['messages'] ?? [],
  4731. ];
  4732. if (!in_array($originalModel, $this->valid_text_models)) {
  4733. Utils::throwError('20003:该模型不支持!');
  4734. }
  4735. // 添加可选参数
  4736. if (isset($params['stream'])) {
  4737. $requestData['stream'] = $params['stream'];
  4738. }
  4739. if (isset($params['stream_options'])) {
  4740. $requestData['stream_options'] = $params['stream_options'];
  4741. }
  4742. if (isset($params['max_tokens'])) {
  4743. $requestData['max_tokens'] = $params['max_tokens'];
  4744. }
  4745. if (isset($params['max_completion_tokens'])) {
  4746. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  4747. }
  4748. if (isset($params['temperature'])) {
  4749. $requestData['temperature'] = $params['temperature'];
  4750. }
  4751. if (isset($params['top_p'])) {
  4752. $requestData['top_p'] = $params['top_p'];
  4753. }
  4754. if (isset($params['frequency_penalty'])) {
  4755. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  4756. }
  4757. if (isset($params['presence_penalty'])) {
  4758. $requestData['presence_penalty'] = $params['presence_penalty'];
  4759. }
  4760. if (isset($params['stop'])) {
  4761. $requestData['stop'] = $params['stop'];
  4762. }
  4763. if (isset($params['tools'])) {
  4764. $requestData['tools'] = $params['tools'];
  4765. }
  4766. if (isset($params['tool_choice'])) {
  4767. $requestData['tool_choice'] = $params['tool_choice'];
  4768. }
  4769. if (isset($params['response_format'])) {
  4770. $requestData['response_format'] = $params['response_format'];
  4771. }
  4772. if (isset($params['thinking'])) {
  4773. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  4774. if (is_array($params['thinking'])) {
  4775. $requestData['thinking'] = $params['thinking'];
  4776. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  4777. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  4778. }
  4779. } else {
  4780. $requestData['thinking'] = ['type' => $params['thinking']];
  4781. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  4782. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  4783. }
  4784. }
  4785. } else {
  4786. $requestData['thinking'] = ['type' => 'disabled'];
  4787. }
  4788. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  4789. $client = new Client(['verify' => false, 'timeout' => 1200]);
  4790. try {
  4791. // 判断是否为流式输出
  4792. $isStream = isset($params['stream']) && $params['stream'] === true;
  4793. if ($isStream) {
  4794. // 流式输出
  4795. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  4796. } else {
  4797. // 非流式输出
  4798. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  4799. 'headers' => [
  4800. 'Authorization' => 'Bearer ' . $apiKey,
  4801. 'Content-Type' => 'application/json',
  4802. ],
  4803. 'json' => $requestData
  4804. ]);
  4805. $responseData = json_decode($response->getBody(), true);
  4806. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  4807. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  4808. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  4809. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  4810. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  4811. }
  4812. return [
  4813. 'fullContent' => $fullContent,
  4814. 'fullReasoningContent' => $fullReasoningContent,
  4815. 'usage' => $usage
  4816. ];
  4817. }
  4818. } catch (\Exception $e) {
  4819. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  4820. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  4821. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  4822. }
  4823. }
  4824. /**
  4825. * 火山引擎对话API流式输出
  4826. *
  4827. * @param Client $client HTTP客户端
  4828. * @param string $apiKey API密钥
  4829. * @param array $requestData 请求数据
  4830. * @return Generator
  4831. */
  4832. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  4833. {
  4834. try {
  4835. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  4836. 'headers' => [
  4837. 'Authorization' => 'Bearer ' . $apiKey,
  4838. 'Content-Type' => 'application/json',
  4839. ],
  4840. 'json' => $requestData,
  4841. 'stream' => true
  4842. ]);
  4843. $body = $response->getBody();
  4844. $buffer = '';
  4845. $fullContent = '';
  4846. $fullReasoningContent = '';
  4847. $usage = [];
  4848. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  4849. // 逐行读取流式响应
  4850. while (!$body->eof()) {
  4851. $chunk = $body->read(1024);
  4852. $buffer .= $chunk;
  4853. // 按行分割
  4854. $lines = explode("\n", $buffer);
  4855. $buffer = array_pop($lines);
  4856. foreach ($lines as $line) {
  4857. $line = trim($line);
  4858. if (empty($line)) {
  4859. continue;
  4860. }
  4861. // 检查是否是SSE数据行
  4862. if (strpos($line, 'data: ') !== 0) {
  4863. continue;
  4864. }
  4865. $data = substr($line, 6);
  4866. if ($data === '[DONE]') {
  4867. dLog('deepseek')->info('收到结束标记');
  4868. break 2;
  4869. }
  4870. try {
  4871. $json = json_decode($data, true);
  4872. if (json_last_error() !== JSON_ERROR_NONE) {
  4873. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  4874. continue;
  4875. }
  4876. if (isset($json['choices'][0]['delta'])) {
  4877. $delta = $json['choices'][0]['delta'];
  4878. // 处理思维链内容
  4879. if (isset($delta['reasoning_content'])) {
  4880. $fullReasoningContent .= $delta['reasoning_content'];
  4881. yield [
  4882. 'type' => 'reasoning',
  4883. 'content' => $delta['reasoning_content'],
  4884. 'full_reasoning' => $fullReasoningContent
  4885. ];
  4886. }
  4887. // 处理回答内容
  4888. if (isset($delta['content'])) {
  4889. $fullContent .= $delta['content'];
  4890. yield [
  4891. 'type' => 'content',
  4892. 'content' => $delta['content'],
  4893. ];
  4894. }
  4895. }
  4896. // 获取使用统计信息
  4897. if (isset($json['usage'])) {
  4898. $usage = $json['usage'];
  4899. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  4900. }
  4901. } catch (\Exception $e) {
  4902. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  4903. continue;
  4904. }
  4905. }
  4906. }
  4907. dLog('deepseek')->info('流式读取完成', [
  4908. 'content_length' => strlen($fullContent),
  4909. 'reasoning_length' => strlen($fullReasoningContent)
  4910. ]);
  4911. yield [
  4912. 'type' => 'done',
  4913. 'full_content' => $fullContent,
  4914. 'full_reasoning' => $fullReasoningContent,
  4915. 'usage' => $usage
  4916. ];
  4917. } catch (\Exception $e) {
  4918. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  4919. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  4920. throw $e;
  4921. }
  4922. }
  4923. /**
  4924. * 检查并创建图片生成任务
  4925. *
  4926. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  4927. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  4928. * @param string $nameKey 资源名称字段('role' 或 'scene')
  4929. * @param string $art_style 美术风格
  4930. * @return array 更新后的资源列表
  4931. */
  4932. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  4933. {
  4934. // 构建全局资源映射表,用于快速查找
  4935. $global_map = [];
  4936. foreach ($global_items as $item) {
  4937. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4938. if ($itemKey === '') {
  4939. continue;
  4940. }
  4941. $global_map[$itemKey] = $item;
  4942. }
  4943. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  4944. foreach ($merged_items as &$item) {
  4945. $item_name = getProp($item, $nameKey);
  4946. $item_description = getProp($item, 'description');
  4947. // $item_url = getProp($item, 'url');
  4948. // // 如果已有图片URL,跳过
  4949. // if (!empty($item_url)) {
  4950. // continue;
  4951. // }
  4952. // 如果是旁白角色,跳过
  4953. if ($nameKey === 'role' && $item_name === '旁白') {
  4954. continue;
  4955. }
  4956. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  4957. if ($itemKey === '') {
  4958. continue;
  4959. }
  4960. $need_create_task = false;
  4961. // 条件1:在全局资源中找不到匹配的名称
  4962. if (!isset($global_map[$itemKey])) {
  4963. $need_create_task = true;
  4964. } else {
  4965. // 条件2:名称匹配但描述不一致
  4966. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  4967. $current_description = trim((string)$item_description);
  4968. if ($global_description !== $current_description) {
  4969. $need_create_task = true;
  4970. }
  4971. }
  4972. // 如果需要创建任务,调用图片生成服务
  4973. if ($need_create_task) {
  4974. try {
  4975. $description = $item_description;
  4976. // 添加美术风格前缀
  4977. if ($art_style) {
  4978. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  4979. $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  4980. }
  4981. $params = [
  4982. 'prompt' => $description,
  4983. 'ref_img_urls' => []
  4984. ];
  4985. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4986. $task_id = $task->id;
  4987. if ($task_id) {
  4988. $item['task_id'] = $task_id;
  4989. $item['task_status'] = 'processing';
  4990. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  4991. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  4992. }
  4993. } catch (\Exception $e) {
  4994. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  4995. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  4996. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  4997. // 不抛出异常,继续处理其他资源
  4998. }
  4999. }
  5000. }
  5001. return $merged_items;
  5002. }
  5003. /**
  5004. * 解析分镜内容的公开方法
  5005. */
  5006. public function parseSegmentContent($segment_content, $model = null) {
  5007. if (!$model) {
  5008. $model = DB::table('mp_text_models')->where('is_enabled', 1)->orderBy('id')->value('model');
  5009. if (!$model) {
  5010. return $segment_content;
  5011. }
  5012. }
  5013. // 构建系统提示词
  5014. $systemPrompt = "你是一个专业的分镜内容解析助手。请将用户提供的分镜内容解析成标准格式,包含以下字段:
  5015. 画面描述:详细描述画面内容
  5016. 构图设计:镜头构图方式
  5017. 运镜调度:摄影机运动方式
  5018. 配音角色:配音的角色名称
  5019. 台词内容:角色说的话
  5020. 画面类型:普通画面或对口型
  5021. 场景:拍摄场景
  5022. 出镜角色:画面中出现的角色
  5023. 尾帧描述:镜头结束时的画面描述
  5024. 情感:配音情感(开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦)
  5025. 性别:1(男)、2(女)、0(中性)
  5026. 语速:-50到100之间的整数
  5027. 音量:-50到100之间的整数
  5028. 情感强度:1到5之间的整数
  5029. 音调:-12到12之间的整数
  5030. 请严格按照上述格式输出,如果某个字段无法确定,请设置合理的默认值。";
  5031. // 构建消息
  5032. $messages = [
  5033. [
  5034. 'role' => 'system',
  5035. 'content' => $systemPrompt
  5036. ],
  5037. [
  5038. 'role' => 'user',
  5039. 'content' => $segment_content
  5040. ]
  5041. ];
  5042. $post_data = [
  5043. 'model' => $model,
  5044. 'messages' => $messages,
  5045. // 'max_tokens' => 2048,
  5046. 'temperature' => 0.7,
  5047. 'frequency_penalty' => 0,
  5048. 'presence_penalty' => 0,
  5049. 'response_format' => ['type' => 'text'],
  5050. 'stream' => false
  5051. ];
  5052. try {
  5053. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5054. // 使用DeepSeek API
  5055. $chatResult = $this->chatOnly($post_data);
  5056. } else {
  5057. // 使用火山引擎API
  5058. $chatResult = $this->volcEngineChatCompletion($post_data);
  5059. }
  5060. if (is_array($chatResult) && !empty($chatResult['fullContent'])) {
  5061. return $chatResult['fullContent'];
  5062. }
  5063. } catch (\Exception $e) {
  5064. dLog('deepseek')->error('解析分镜内容失败: ' . $e->getMessage());
  5065. logDB('deepseek', 'error', '解析分镜内容失败', ['error' => $e->getMessage()]);
  5066. }
  5067. return $segment_content;
  5068. }
  5069. }