DeepSeekService.php 261 KB

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