DeepSeekService.php 228 KB

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