DeepSeekService.php 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402
  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 Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Redis;
  12. use OSS\Core\OssException;
  13. use OSS\OssClient;
  14. use Smalot\PdfParser\Parser as PdfParser;
  15. use TCPDF;
  16. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  17. class DeepSeekService
  18. {
  19. private $url;
  20. private $api_key;
  21. private $sys_message;
  22. private $headers;
  23. public function __construct() {
  24. $this->url = 'https://api.deepseek.com/chat/completions';
  25. $this->api_key = env('DEEPSEEK_API_KEY');
  26. $this->headers = [
  27. 'Authorization' => 'Bearer '.$this->api_key,
  28. 'Content-Type' => 'application/json; charset=UTF-8'
  29. ];
  30. $this->sys_message = [
  31. 'role' => 'system',
  32. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  33. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  34. 2.<分集剧本>要求包含“分集序号”、“分集标题”以及分镜信息,分镜信息需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。\n
  35. 3.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答\n
  36. 示例如下:\n\n
  37. ###剧本名:西昆仑
  38. ###故事梗概
  39. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  40. ###剧本亮点
  41. 亮点1:绝境奇药,生死一线
  42. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  43. 亮点2:结拜兄妹,化解尴尬
  44. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  45. 亮点3:纤发夺命,情愫暗涌
  46. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  47. ###人物关系
  48. 阿雪与梁萧之间存在兄妹之情。
  49. ###核心矛盾
  50. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  51. ###主体列表
  52. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  53. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  54. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  55. 阴阳球:天地异宝,能化生精气,救人于危难。
  56. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  57. ###美术风格
  58. 基础画风风格词:厚涂古风
  59. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  60. ###场景列表
  61. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  62. ###分集剧本
  63. ##分集01
  64. 分集名: 第一集
  65. 分镜01-1
  66. 场景描述:地点、时间、场景
  67. 运镜:固定近距离
  68. 出场角色:男主、女主
  69. 台词内容:
  70. 女主: 女主对话
  71. 男主:男主对话
  72. 女主: 女主对话
  73. 男主: 男主对话
  74. 分镜01-2
  75. 场景描述:地点、时间、场景
  76. 运镜:从近到远
  77. 出场角色:男主、女主
  78. 台词内容:
  79. 女主: 女主对话
  80. 男主:男主对话
  81. 女主: 女主对话
  82. 男主: 男主对话
  83. 分镜01-3
  84. 场景描述:地点、时间、场景
  85. 运镜:快速拉近
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 分集名: 第二集
  94. 分镜02-1
  95. 场景描述:地点、时间、场景
  96. 运镜:从近到远
  97. 出场角色:男主、女主
  98. 台词内容:
  99. 女主: 女主对话
  100. 男主:男主对话
  101. 女主: 女主对话
  102. 男主: 男主对话
  103. 分镜02-2
  104. 场景描述:地点、时间、场景
  105. 运镜:从近到远
  106. 出场角色:男主、女主
  107. 台词内容:
  108. 女主: 女主对话
  109. 男主:男主对话
  110. 女主: 女主对话
  111. 男主: 男主对话"
  112. ];
  113. }
  114. private function getArtStylePromptMappings(): array
  115. {
  116. return [
  117. '厚涂古风' => [
  118. 'aliases' => ['厚涂古风', '古风厚涂', '国风厚涂', '古风'],
  119. 'prompt' => "基础画风风格词:厚涂古风\n整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,可辅以温暖的金色、琥珀色光晕强化画面情绪。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。"
  120. ],
  121. '现代都市情感' => [
  122. 'aliases' => ['现代都市', '都市情感', '现代情感', '都市写实', '现代写实'],
  123. 'prompt' => "基础画风风格词:写实细腻的现代都市情感风格,带有轻微悬疑色彩。\n整体采用电影质感的写实风格,色彩随情绪和剧情变化。日常场景偏自然光感与生活化细节,压抑或冲突场景可适度加强蓝灰、暗绿色调,营造情感张力与轻悬疑氛围。人物造型追求真实可信,环境道具需体现都市生活气息。"
  124. ],
  125. '现实主义超现实' => [
  126. 'aliases' => ['现实主义', '超现实', '现实主义超现实', '现实主义奇幻', '现代奇幻写实'],
  127. 'prompt' => "基础画风风格词:现实主义的细腻光影与超现实元素结合\n整体以现实主义基调塑造人物与场景,色彩饱和度适中偏低,通过细腻光影与局部超现实视觉元素制造情绪冲击。画面在真实生活质感之上融入象征性表达,让现实压迫感与奇异氛围并存。"
  128. ],
  129. '韩漫二次元' => [
  130. 'aliases' => ['韩漫', '韩漫二次元', '二次元', '漫画风', '韩系漫画'],
  131. 'prompt' => "基础画风风格词:韩漫二次元\n整体采用精致清晰的韩漫二次元风格,人物五官立体、轮廓干净,画面注重高颜值塑造与情绪表达。色彩通透,光影偏柔和,兼顾浪漫氛围与剧情张力,适合强化角色关系和戏剧冲突。"
  132. ],
  133. ];
  134. }
  135. private function getArtStylePromptByInput($inputArtStyle): string
  136. {
  137. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  138. if ($normalizedInput === '') {
  139. return '';
  140. }
  141. foreach ($this->getArtStylePromptMappings() as $mapping) {
  142. foreach ($mapping['aliases'] as $alias) {
  143. $normalizedAlias = $this->normalizeArtStyleInput($alias);
  144. if ($normalizedAlias === '') {
  145. continue;
  146. }
  147. if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  148. return $mapping['prompt'];
  149. }
  150. }
  151. }
  152. return '';
  153. }
  154. private function normalizeArtStyleInput($value): string
  155. {
  156. $value = trim((string)$value);
  157. if ($value === '') {
  158. return '';
  159. }
  160. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  161. return mb_strtolower($value, 'UTF-8');
  162. }
  163. private function replaceArtStyleSection(string $content, string $artStyle): string
  164. {
  165. if ($content === '' || $artStyle === '') {
  166. return $content;
  167. }
  168. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  169. if (!preg_match($pattern, $content)) {
  170. return $content;
  171. }
  172. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  173. }
  174. // 与推理模型对话
  175. public function chatWithReasoner($data) {
  176. $content = getProp($data, 'content');
  177. $model = getProp($data, 'model', 'r1');
  178. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  179. // 获取可选情感(根据音色可支持情感选)
  180. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  181. $emotion_list = [];
  182. foreach ($timbre_emotion as $emotion) {
  183. $tmp = explode(',', $emotion);
  184. $emotion_list = array_merge($emotion_list, $tmp);
  185. }
  186. $emotion_list = array_unique($emotion_list);
  187. $emotion_str = implode('、', $emotion_list);
  188. // // 获取可选情感
  189. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  190. // $emotion_str = implode('、', $emotion_list);
  191. // 是否启用情感
  192. $enable_emotion = getProp($data, 'enable_emotion', 0);
  193. if ($enable_emotion) {
  194. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  195. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  196. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  197. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  198. }else {
  199. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  200. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  201. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  202. }
  203. $messages = [
  204. [
  205. 'role' => 'system',
  206. 'content' => $sys_content
  207. ],
  208. [
  209. 'role' => 'user',
  210. 'content' => $content
  211. ]
  212. ];
  213. $post_data = [
  214. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  215. 'messages' => $messages,
  216. 'max_tokens' => 8192,
  217. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  218. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  219. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  220. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  221. 'response_format' => [
  222. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  223. ],
  224. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  225. ];
  226. $client = new Client(['timeout' => 1200, 'verify' => false]);
  227. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  228. $response = $result->getBody()->getContents();
  229. $response_arr = json_decode($response, true);
  230. $update_data = [];
  231. $content = '';
  232. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  233. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  234. $update_data = [
  235. 'role' => 'assistant',
  236. 'content' => $response_arr['choices'][0]['message']['content'],
  237. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  238. ];
  239. }
  240. // 处理获取到的剧本数据
  241. $script_content = handleScriptWords($content, $enable_emotion);
  242. $result = [
  243. 'origin_content' => $content,
  244. 'roles' => getProp($script_content, 'roles'),
  245. 'words' => getProp($script_content, 'words'),
  246. ];
  247. return $result;
  248. }
  249. public function resetParagraphAudio($data) {
  250. $bid = getProp($data, 'bid');
  251. $cid = getProp($data, 'cid');
  252. $version_id = getProp($data, 'version_id');
  253. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  254. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  255. 'generate_status' => '待制作',
  256. 'updated_at' => date('Y-m-d H:i:s')
  257. ]);
  258. }
  259. public function saveParagraphAudio($data) {
  260. $bid = getProp($data, 'bid');
  261. $cid = getProp($data, 'cid');
  262. $version_id = getProp($data, 'version_id');
  263. $sequence = getProp($data, 'sequence');
  264. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  265. // 获取所有情感
  266. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  267. $emotion_list = array_flip($emotion_list);
  268. // 获取音色支持情感
  269. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  270. $timbre_emotion = explode(',', $timbre_emotion);
  271. $emotion = getProp($data, 'emotion');
  272. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  273. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  274. $list = [
  275. 'bid' => $bid,
  276. 'cid' => $cid,
  277. 'version_id' => $version_id,
  278. 'sequence' => $sequence,
  279. 'role' => getProp($data, 'role'),
  280. 'gender' => getProp($data, 'gender'),
  281. 'text' => trim(getProp($data, 'text')),
  282. 'emotion' => $emotion,
  283. 'emotion_type' => $emotion_type,
  284. 'voice_type' => getProp($data, 'voice_type'),
  285. 'voice_name' => getProp($data, 'voice_name'),
  286. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  287. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  288. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  289. 'pitch' => getProp($data, 'pitch', 0),
  290. // 'paragraph_audio_url' => '',
  291. 'generate_status' => '制作中',
  292. 'error_msg' => '',
  293. 'updated_at' => date('Y-m-d H:i:s')
  294. ];
  295. $continue = false;
  296. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  297. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  298. $list['generate_status'] = '制作成功';
  299. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  300. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  301. $continue = true;
  302. }
  303. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  304. if ($id) {
  305. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  306. }else {
  307. $list['created_at'] = date('Y-m-d H:i:s');
  308. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  309. $boolen = $id ? true : false;
  310. }
  311. // 如果更新成功则加入查询队列
  312. if ($boolen) {
  313. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  314. Redis::sadd($redis_key, $id);
  315. }
  316. if ($boolen && !$continue) {
  317. $boolen = false;
  318. $client = new Client(['timeout' => 300, 'verify' => false]);
  319. // 根据ID通过API通知合成音频
  320. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  321. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  322. $response = $result->getBody()->getContents();
  323. $response_arr = json_decode($response, true);
  324. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  325. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  326. Log::info('通知火山生成段落音频失败: '.$error_msg);
  327. Utils::throwError('20003:通知火山生成段落音频失败');
  328. }
  329. $boolen = true;
  330. }
  331. return $boolen;
  332. }
  333. public function insertAudioEffect($data) {
  334. $audio_id = getProp($data, 'audio_id');
  335. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  336. $bid = getProp($chapter_audio, 'bid');
  337. $version_id = getProp($chapter_audio, 'version_id');
  338. $cid = getProp($chapter_audio, 'cid');
  339. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  340. $audio_effect_json = getProp($data, 'audio_effect_json');
  341. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  342. try {
  343. DB::beginTransaction();
  344. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  345. if (!$count) {
  346. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  347. }else {
  348. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  349. }
  350. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  351. 'audio_effect_status' => '添加中',
  352. 'audio_effect_json' => $audio_effect_json,
  353. 'updated_at' => date('Y-m-d H:i:s')
  354. ]);
  355. if (!$boolen1) {
  356. DB::rollBack();
  357. Utils::throwError('20003:更新生成数据失败');
  358. }
  359. $id = DB::table('mp_audio_tasks')->insertGetId([
  360. 'audio_id' => $audio_id,
  361. 'generate_status' => '执行中',
  362. 'generate_json' => json_encode([], 256),
  363. 'bid' => $bid,
  364. 'book_name' => getProp($chapter_audio, 'book_name'),
  365. 'version_id' => $version_id,
  366. 'version_name' => getProp($chapter_audio, 'version_name'),
  367. 'cid' => $cid,
  368. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  369. 'task_name' => $task_name,
  370. 'created_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$id) {
  374. DB::rollBack();
  375. Utils::throwError('20003:创建任务失败');
  376. }
  377. }catch (\Exception $e) {
  378. DB::rollBack();
  379. Utils::throwError('20003:'.$e->getMessage());
  380. }
  381. DB::commit();
  382. $client = new Client(['timeout' => 300, 'verify' => false]);
  383. // 根据ID通过API通知合成音频
  384. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  385. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  386. $response = $result->getBody()->getContents();
  387. $response_arr = json_decode($response, true);
  388. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  389. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  390. Log::info('通知火山插入音效失败: '.$error_msg);
  391. Utils::throwError('20003:通知火山插入音效失败');
  392. }
  393. return true;
  394. }
  395. public function insertBgm($data) {
  396. $audio_id = getProp($data, 'audio_id');
  397. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  398. $bid = getProp($chapter_audio, 'bid');
  399. $version_id = getProp($chapter_audio, 'version_id');
  400. $cid = getProp($chapter_audio, 'cid');
  401. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  402. $bgm_json = getProp($data, 'bgm_json');
  403. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  404. if (!$bgm_json) {
  405. $bgm_json = getProp($data, 'audio_effect_json');
  406. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  407. }
  408. try {
  409. DB::beginTransaction();
  410. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  411. if (!$count) {
  412. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  413. }else {
  414. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  415. }
  416. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  417. 'bgm_status' => '添加中',
  418. 'bgm_json' => $bgm_json,
  419. 'updated_at' => date('Y-m-d H:i:s')
  420. ]);
  421. if (!$boolen1) {
  422. DB::rollBack();
  423. Utils::throwError('20003:更新生成数据失败');
  424. }
  425. $id = DB::table('mp_audio_tasks')->insertGetId([
  426. 'audio_id' => $audio_id,
  427. 'generate_status' => '执行中',
  428. 'generate_json' => json_encode([], 256),
  429. 'bid' => $bid,
  430. 'book_name' => getProp($chapter_audio, 'book_name'),
  431. 'version_id' => $version_id,
  432. 'version_name' => getProp($chapter_audio, 'version_name'),
  433. 'cid' => $cid,
  434. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  435. 'task_name' => $task_name,
  436. 'created_at' => date('Y-m-d H:i:s'),
  437. 'updated_at' => date('Y-m-d H:i:s')
  438. ]);
  439. if (!$id) {
  440. DB::rollBack();
  441. Utils::throwError('20003:创建任务失败');
  442. }
  443. }catch (\Exception $e) {
  444. DB::rollBack();
  445. Utils::throwError('20003:'.$e->getMessage());
  446. }
  447. DB::commit();
  448. $client = new Client(['timeout' => 300, 'verify' => false]);
  449. // 根据ID通过API通知合成音频
  450. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  451. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  452. $response = $result->getBody()->getContents();
  453. $response_arr = json_decode($response, true);
  454. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  455. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  456. Log::info('通知火山插入bgm失败: '.$error_msg);
  457. Utils::throwError('20003:通知火山插入bgm失败');
  458. }
  459. return true;
  460. }
  461. public function getParagraphAudios($data) {
  462. $bid = getProp($data, 'bid');
  463. $cid = getProp($data, 'cid');
  464. $version_id = getProp($data, 'version_id');
  465. $sequence = getProp($data, 'sequence');
  466. // 获取已生成的音频
  467. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  468. if ($sequence) $query->where('sequence', $sequence);
  469. $paragraph_audios = $query->orderBy('sequence')->get();
  470. $result = [];
  471. foreach($paragraph_audios as $item) {
  472. $result[] = [
  473. 'sequence' => getProp($item, 'sequence'),
  474. 'role' => getProp($item, 'role'),
  475. 'gender' => getProp($item, 'gender'),
  476. 'text' => trim(getProp($item, 'text')),
  477. 'emotion' => getProp($item, 'emotion'),
  478. 'emotion_type' => getProp($item, 'emotion_type'),
  479. 'voice_type' => getProp($item, 'voice_type'),
  480. 'voice_name' => getProp($item, 'voice_name'),
  481. 'speed_ratio' => getProp($item, 'speed_ratio'),
  482. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  483. 'emotion_scale' => getProp($item, 'emotion_scale'),
  484. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  485. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  486. ];
  487. }
  488. return $result;
  489. }
  490. // 新增合成任务
  491. public function addGenerateTask($data) {
  492. $bid = getProp($data, 'bid');
  493. $cid = getProp($data, 'cid');
  494. $version_id = getProp($data, 'version_id');
  495. $generate_json = getProp($data, 'generate_json');
  496. // 获取已生成的音频
  497. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  498. $paragraph_list = [];
  499. foreach($paragraph_audios as $item) {
  500. $paragraph_list[getProp($item, 'sequence')] = [
  501. 'role' => getProp($item, 'role'),
  502. 'gender' => getProp($item, 'gender'),
  503. 'text' => trim(getProp($item, 'text')),
  504. 'emotion' => getProp($item, 'emotion'),
  505. 'emotion_type' => getProp($item, 'emotion_type'),
  506. 'voice_type' => getProp($item, 'voice_type'),
  507. 'voice_name' => getProp($item, 'voice_name'),
  508. 'speed_ratio' => getProp($item, 'speed_ratio'),
  509. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  510. 'emotion_scale' => getProp($item, 'emotion_scale'),
  511. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  512. ];
  513. }
  514. // 更新角色-音色信息
  515. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  516. $existed_role_info = json_decode($existed_role_info, true);
  517. if (!$existed_role_info) $existed_role_info = [];
  518. // 获取情感信息
  519. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  520. $emotion_list = array_flip($emotion_list);
  521. // 获取音色对应情感组
  522. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  523. $timbre_emotion_list = [];
  524. foreach($timbre_emotions as $item) {
  525. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  526. }
  527. // 构造生成音频的json
  528. $words = json_decode($generate_json, true);
  529. // 最终合成前的参数组
  530. $mp_chapter_paragraph_audios = [];
  531. $sequence = 1;
  532. $complete_paragraph_sequences = [];
  533. foreach($words as &$word) {
  534. 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:参数格式有误');
  535. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  536. $role = getProp($word, 'role');
  537. $word['gender'] = (int)$word['gender'];
  538. // 判断音色对应情感是否支持,不支持则调整为中性
  539. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  540. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  541. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  542. if (isset($emotion_list[getProp($word, 'emotion')])) {
  543. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  544. }else {
  545. $word['emotion'] = '中性';
  546. $word['emotion_type'] = 'neutral';
  547. }
  548. $existed_role_info[$role] = [
  549. 'timbre_type' => $word['voice_type'],
  550. 'timbre_name' => $word['voice_name'],
  551. 'emotion' => $word['emotion'],
  552. 'emotion_type' => $word['emotion_type'],
  553. 'speed_ratio' => $word['speed_ratio'],
  554. 'loudness_ratio'=> $word['loudness_ratio'],
  555. 'emotion_scale' => $word['emotion_scale'],
  556. 'pitch' => $word['pitch']
  557. ];
  558. $word['paragraph_audio_url'] = '';
  559. // 判断生成参数是否相同,相同则直接使用已生成的音频
  560. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  561. // 如果音频存在并且参数都未改变则使用已生成的音频
  562. if (getProp($paragraph, 'paragraph_audio_url')) {
  563. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  564. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  565. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  566. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  567. // {
  568. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  569. // }
  570. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  571. }
  572. $tmp = $word;
  573. // 组装章节分句音频数据
  574. // $tmp['sequence'] = getProp($word, 'sequence');
  575. // $tmp['text'] = getProp($word, 'text');
  576. // $tmp['emotion'] = getProp($word, 'emotion');
  577. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  578. // $tmp['voice_name'] = getProp($word, 'voice_name');
  579. // $tmp['voice_type'] = getProp($word, 'voice_type');
  580. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  581. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  582. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  583. $tmp['bid'] = $bid;
  584. $tmp['version_id'] = $version_id;
  585. $tmp['cid'] = $cid;
  586. $tmp['sequence'] = $sequence;
  587. $tmp['created_at'] = date('Y-m-d H:i:s');
  588. $tmp['updated_at'] = date('Y-m-d H:i:s');
  589. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  590. $mp_chapter_paragraph_audios[] = $tmp;
  591. $complete_paragraph_sequences[] = $sequence;
  592. $sequence++;
  593. }
  594. $generate_json = json_encode($words, 256);
  595. // 判断是否有未生成字幕的段落
  596. $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();
  597. if ($no_subtitle_sequences) {
  598. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  599. }
  600. try {
  601. DB::beginTransaction();
  602. $role_info = json_encode($existed_role_info, 256);
  603. $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')]);
  604. if (!$boolen) {
  605. DB::rollBack();
  606. Utils::throwError('20003:更新角色信息失败');
  607. }
  608. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  609. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  610. if (!$count) {
  611. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  612. }else {
  613. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  614. }
  615. $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')]);
  616. if (!$boolen1) {
  617. DB::rollBack();
  618. Utils::throwError('20003:更新生成数据失败');
  619. }
  620. $id = DB::table('mp_audio_tasks')->insertGetId([
  621. 'audio_id' => getProp($chapter_audio, 'id'),
  622. 'generate_status' => '执行中',
  623. 'generate_json' => $generate_json,
  624. 'bid' => $bid,
  625. 'book_name' => getProp($chapter_audio, 'book_name'),
  626. 'version_id' => $version_id,
  627. 'version_name' => getProp($chapter_audio, 'version_name'),
  628. 'cid' => $cid,
  629. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  630. 'task_name' => $task_name,
  631. 'created_at' => date('Y-m-d H:i:s'),
  632. 'updated_at' => date('Y-m-d H:i:s')
  633. ]);
  634. if (!$id) {
  635. DB::rollBack();
  636. Utils::throwError('20003:创建任务失败');
  637. }
  638. // 删除不在段落序号范围内的其他数据
  639. if ($complete_paragraph_sequences) {
  640. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  641. }
  642. // // 删除章节分句音频数据并重新插入
  643. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  644. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  645. // if (!$boolen3) {
  646. // DB::rollBack();
  647. // Utils::throwError('20003:更新章节分句音频失败');
  648. // }
  649. } catch (\Exception $e) {
  650. DB::rollBack();
  651. Utils::throwError('20003:'.$e->getMessage());
  652. }
  653. DB::commit();
  654. // 通知火山生成音频
  655. $client = new Client(['timeout' => 300, 'verify' => false]);
  656. // 根据ID通过API通知合成音频
  657. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  658. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  659. $response = $result->getBody()->getContents();
  660. $response_arr = json_decode($response, true);
  661. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  662. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  663. Log::info('通知火山生成音频失败: '.$error_msg);
  664. Utils::throwError('20003:通知火山生成音频失败');
  665. }
  666. return true;
  667. }
  668. public function timbreList($data) {
  669. $gender = getProp($data, 'gender');
  670. $timbre_name = getProp($data, 'voice_name');
  671. $category_id = getProp($data, 'category_id');
  672. $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');
  673. if ($gender) {
  674. $query->where('gender', $gender);
  675. }
  676. if ($timbre_name) {
  677. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  678. }
  679. if ($category_id) {
  680. $query->where(function ($query) use ($category_id) {
  681. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  682. });
  683. }
  684. $list = $query->get()->map(function ($value) {
  685. $value = (array)$value;
  686. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  687. return $value;
  688. })->toArray();
  689. return $list;
  690. }
  691. // 生成火山临时token
  692. public function setStsToken() {
  693. // ************* 配置参数 *************
  694. $method = 'GET';
  695. $service = 'sts';
  696. $host = 'open.volcengineapi.com';
  697. $region = env('VOLC_REGION');
  698. $endpoint = 'https://open.volcengineapi.com';
  699. // $endpoint = 'https://tos-cn-beijing.volces.com';
  700. $access_key = env('VOLC_AK');
  701. $secret_key = env('VOLC_SK');
  702. // 获取缓存中的token,如果没有则请求接口
  703. $token = Redis::get('volc_sts_token');
  704. if (!$token) {
  705. // 查询参数
  706. $query_parameters = [
  707. 'Action' => 'AssumeRole',
  708. 'RoleSessionName' => 'user@zw',
  709. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  710. 'Version' => '2018-01-01'
  711. ];
  712. // 生成URL编码的查询字符串
  713. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  714. // 获取签名头信息
  715. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  716. // 构建完整URL
  717. $request_url = $endpoint . '?' . $request_parameters;
  718. $client = new Client(['verify' => false]);
  719. $response = $client->get($request_url, ['headers' => $headers]);
  720. $response_arr = json_decode($response->getBody()->getContents(), true);
  721. $result = [
  722. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  723. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  724. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  725. 'Region' => env('VOLC_REGION'),
  726. 'Endpoint' => env('VOLC_END_POINT'),
  727. 'Bucket' => env('VOLC_BUCKET'),
  728. ];
  729. // 缓存token
  730. Redis::setex('volc_sts_token', 3000, json_encode($result));
  731. return $result;
  732. } else {
  733. return json_decode($token, true);
  734. }
  735. // $response = $response['Response'];
  736. // $access_key = $response['Credentials']['AccessKeyId'];
  737. // $secret_key = $response['Credentials']['AccessKeySecret'];
  738. // $security_token = $response['Credentials']['SecurityToken'];
  739. // $expiration = $response['Credentials']['Expiration'];
  740. // dd($response_arr);
  741. }
  742. public function emotionGroups($data) {
  743. $id = getProp($data, 'group_id');
  744. $group_name = getProp($data, 'group_name');
  745. $voice_type = getProp($data, 'voice_type');
  746. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  747. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  748. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  749. if ($group_name) {
  750. $query->where('group_name', 'like', "%{$group_name}%");
  751. }
  752. if ($id) {
  753. $query->where('id', $id);
  754. }
  755. if ($voice_type) {
  756. $query->where('voice_type', $voice_type);
  757. }
  758. return $query->orderBy('id')->get()->map(function ($value) {
  759. return (array)$value;
  760. })->toArray();
  761. }
  762. private function sign($key, $msg) {
  763. return hash_hmac('sha256', $msg, $key, true);
  764. }
  765. // 生成签名密钥
  766. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  767. $kDate = $this->sign($key, $dateStamp);
  768. $kRegion = $this->sign($kDate, $regionName);
  769. $kService = $this->sign($kRegion, $serviceName);
  770. $kSigning = $this->sign($kService, 'request');
  771. return $kSigning;
  772. }
  773. // 获取签名头信息
  774. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  775. $contenttype = 'application/x-www-form-urlencoded';
  776. $accept = 'application/json';
  777. // 获取当前UTC时间
  778. $t = new DateTime('now', new DateTimeZone('UTC'));
  779. $xdate = $t->format('Ymd\THis\Z');
  780. $datestamp = $t->format('Ymd');
  781. // 1. 拼接规范请求串
  782. $canonical_uri = '/';
  783. $canonical_querystring = $request_parameters;
  784. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  785. $signed_headers = 'content-type;host;x-date';
  786. // 空请求体的SHA256哈希
  787. $payload_hash = hash('sha256', '');
  788. $canonical_request = implode("\n", [
  789. $method,
  790. $canonical_uri,
  791. $canonical_querystring,
  792. $canonical_headers,
  793. $signed_headers,
  794. $payload_hash
  795. ]);
  796. // 2. 拼接待签名字符串
  797. $algorithm = 'HMAC-SHA256';
  798. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  799. $hashed_canonical_request = hash('sha256', $canonical_request);
  800. $string_to_sign = implode("\n", [
  801. $algorithm,
  802. $xdate,
  803. $credential_scope,
  804. $hashed_canonical_request
  805. ]);
  806. // 3. 计算签名
  807. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  808. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  809. // 4. 添加签名到请求头
  810. $authorization_header = sprintf(
  811. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  812. $algorithm,
  813. $access_key,
  814. $credential_scope,
  815. $signed_headers,
  816. $signature
  817. );
  818. return [
  819. 'Accept' => $accept,
  820. 'Content-Type' => $contenttype,
  821. 'X-Date' => $xdate,
  822. 'Authorization' => $authorization_header
  823. ];
  824. }
  825. // 文字合成语音(火山引擎)
  826. public function tts($data) {
  827. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  828. $headers = [
  829. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  830. 'Content-Type' => 'application/json; charset=UTF-8'
  831. ];
  832. $post_data = [
  833. 'app' => [
  834. 'appid' => env('VOLC_APPID'),
  835. 'token' => env('VOLC_TOKEN'),
  836. 'cluster' => 'volcano_tts'
  837. ],
  838. 'user' => [
  839. 'uid' => 'mp_audio'
  840. ],
  841. // 'audio' => [
  842. // 'voice_type' =>
  843. // ],
  844. ];
  845. }
  846. public function scriptList($data) {
  847. $script_id = getProp($data, 'script_id');
  848. $script_name = getProp($data, 'script_name');
  849. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  850. if ($script_id) {
  851. $query->where('id', $script_id);
  852. }
  853. if ($script_name) {
  854. $query->where('script_name', 'like', "%{$script_name}%");
  855. }
  856. return $query->orderBy('created_at', 'desc')->paginate(12);
  857. }
  858. public function scriptInfo($data) {
  859. $script_id = getProp($data, 'script_id');
  860. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  861. ->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();
  862. if (!$script) Utils::throwError('20003:该剧本不存在!');
  863. $script = (array)$script;
  864. $script['roles'] = json_decode($script['roles']);
  865. $script['scenes'] = json_decode($script['scenes']);
  866. // 获取分集信息
  867. $episodes = DB::table('mp_script_episodes')->where('script_id', $script_id)->orderBy('episode_number')
  868. ->select('id', 'episode_number', 'title', 'content', 'segment_number', 'segment_content')
  869. ->orderBy('episode_number')->orderBy('segment_number')->get()->map(function ($value) {
  870. return (array)$value;
  871. })->toArray();
  872. $return_episodes = [];
  873. foreach($episodes as $episode) {
  874. $episode_number = getProp($episode, 'episode_number');
  875. if (isset($return_episodes[$episode_number])) {
  876. $return_episodes[$episode_number]['segments'][] = [
  877. 'segment_number' => getProp($episode, 'segment_number'),
  878. 'segment_content' => getProp($episode, 'segment_content')
  879. ];
  880. }else {
  881. $return_episodes[$episode_number] = [
  882. 'episode_number' => $episode_number,
  883. 'title' => getProp($episode, 'title'),
  884. 'segments' => [
  885. [
  886. 'segment_number' => getProp($episode, 'segment_number'),
  887. 'segment_content' => getProp($episode, 'segment_content')
  888. ]
  889. ]
  890. ];
  891. }
  892. }
  893. $script['episodes'] = array_values($return_episodes);
  894. return $script;
  895. }
  896. public function createScript($data) {
  897. $script_name = getProp($data, 'script_name');
  898. $uid = Site::getUid(); // 获取当前用户ID
  899. if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
  900. return DB::table('mp_scripts')->insertGetId([
  901. 'script_name' => $script_name,
  902. 'user_id' => $uid,
  903. 'created_at' => date('Y-m-d H:i:s'),
  904. 'updated_at' => date('Y-m-d H:i:s')
  905. ]);
  906. }
  907. /**
  908. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  909. *
  910. * @param array $data 包含以下参数:
  911. * - file: 上传的文件(UploadedFile 对象)或文件路径
  912. * - question: 用户问题(可选)
  913. * - model: 使用的模型(r1 或 v3,默认 v3)
  914. * @return \Generator 返回生成器,用于流式输出
  915. */
  916. public function chatWithFileStream($data) {
  917. $script_id = getProp($data, 'script_id');
  918. $file = getProp($data, 'file');
  919. $content = getProp($data, 'content', '');
  920. $bid = getProp($data, 'bid', 0);
  921. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  922. $total_episode_num = getProp($data, 'total_episode_num', 30);
  923. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  924. $model = getProp($data, 'model', 'v3');
  925. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  926. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  927. if (!$script) {
  928. Utils::throwError('20003:剧本不存在');
  929. }
  930. if (!$file && !$content && !$bid) {
  931. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  932. }
  933. // 提取文件内容
  934. if ($content) {
  935. $content = filterContent($content);
  936. } elseif ($file) {
  937. $content = $this->extractFileContent($file);
  938. if (!$content) {
  939. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  940. }
  941. } elseif ($bid) {
  942. $content = $this->getContentByBid($bid);
  943. if (!$content) {
  944. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  945. }
  946. } else {
  947. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  948. }
  949. // 构建消息
  950. $messages = [
  951. $this->sys_message,
  952. [
  953. 'role' => 'user',
  954. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  955. ]
  956. ];
  957. $post_data = [
  958. 'model' => $model,
  959. 'messages' => $messages,
  960. 'max_tokens' => 8192,
  961. 'temperature' => 0.7,
  962. 'frequency_penalty' => 0,
  963. 'presence_penalty' => 0,
  964. 'response_format' => ['type' => 'text'],
  965. 'stream' => true // 启用流式输出
  966. ];
  967. $client = new Client(['timeout' => 1200, 'verify' => false]);
  968. $response = $client->post($this->url, [
  969. 'json' => $post_data,
  970. 'headers' => $this->headers,
  971. 'stream' => true // 启用流式响应
  972. ]);
  973. $body = $response->getBody();
  974. $fullContent = '';
  975. $fullReasoningContent = '';
  976. $usage = [];
  977. $buffer = '';
  978. Log::info('开始读取 DeepSeek 流式响应');
  979. // 逐行读取流式响应
  980. while (!$body->eof()) {
  981. $chunk = $body->read(1024); // 每次读取 1KB
  982. $buffer .= $chunk;
  983. // 按行分割
  984. $lines = explode("\n", $buffer);
  985. // 保留最后一个不完整的行
  986. $buffer = array_pop($lines);
  987. foreach ($lines as $line) {
  988. $line = trim($line);
  989. // 跳过空行
  990. if (empty($line)) {
  991. continue;
  992. }
  993. // Log::info('收到原始行数据', ['line' => $line]);
  994. // 检查是否是 SSE 数据行
  995. if (strpos($line, 'data: ') !== 0) {
  996. Log::warning('非 SSE 数据行', ['line' => $line]);
  997. continue;
  998. }
  999. $data = substr($line, 6); // 移除 "data: " 前缀
  1000. if ($data === '[DONE]') {
  1001. Log::info('收到结束标记');
  1002. break 2; // 跳出两层循环
  1003. }
  1004. try {
  1005. $json = json_decode($data, true);
  1006. if (json_last_error() !== JSON_ERROR_NONE) {
  1007. Log::warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1008. continue;
  1009. }
  1010. // Log::info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1011. if (isset($json['choices'][0]['delta'])) {
  1012. $delta = $json['choices'][0]['delta'];
  1013. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1014. // 注释掉以下内容则不返回d思维链内容
  1015. if (isset($delta['reasoning_content'])) {
  1016. $fullReasoningContent .= $delta['reasoning_content'];
  1017. // Log::info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1018. yield [
  1019. 'type' => 'reasoning',
  1020. 'content' => $delta['reasoning_content'],
  1021. 'full_reasoning' => $fullReasoningContent
  1022. ];
  1023. }
  1024. // 处理最终回答内容
  1025. if (isset($delta['content'])) {
  1026. $fullContent .= $delta['content'];
  1027. // Log::info('输出回答内容', ['length' => strlen($delta['content'])]);
  1028. yield [
  1029. 'type' => 'content',
  1030. 'content' => $delta['content'],
  1031. 'full_content' => $fullContent
  1032. ];
  1033. }
  1034. }
  1035. // 获取使用统计信息
  1036. if (isset($json['usage'])) {
  1037. $usage = $json['usage'];
  1038. Log::info('收到使用统计', ['usage' => $usage]);
  1039. }
  1040. } catch (\Exception $e) {
  1041. Log::error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1042. continue;
  1043. }
  1044. }
  1045. }
  1046. Log::info('流式读取完成', [
  1047. 'content_length' => strlen($fullContent),
  1048. 'reasoning_length' => strlen($fullReasoningContent)
  1049. ]);
  1050. // 处理完整内容并返回最终结果
  1051. $script_arr = [];
  1052. if ($fullContent) {
  1053. $script_arr = handleScriptContent($fullContent);
  1054. }
  1055. yield [
  1056. 'type' => 'done',
  1057. 'script' => $script_arr,
  1058. 'answer' => $fullContent,
  1059. 'reasoning' => $fullReasoningContent,
  1060. 'usage' => $usage
  1061. ];
  1062. }
  1063. /**
  1064. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1065. *
  1066. * @param array $data 包含以下参数:
  1067. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1068. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1069. * - model: 使用的模型(r1 或 v3,默认 v3)
  1070. * @return array
  1071. */
  1072. public function chatWithFile($data) {
  1073. // dd(handleScriptContent(''));
  1074. $script_id = getProp($data, 'script_id');
  1075. $file = getProp($data, 'file');
  1076. $content = getProp($data, 'content', '');
  1077. $bid = getProp($data, 'bid', 0);
  1078. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1079. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1080. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1081. $model = getProp($data, 'model', 'v3');
  1082. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1083. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1084. if (!$script) {
  1085. Utils::throwError('20003:剧本不存在');
  1086. }
  1087. if (!$file && !$content && !$bid) {
  1088. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1089. }
  1090. // 提取文件内容
  1091. if ($content) {
  1092. $content = filterContent($content);
  1093. } elseif ($file) {
  1094. $content = $this->extractFileContent($file);
  1095. if (!$content) {
  1096. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1097. }
  1098. } elseif ($bid) {
  1099. $content = $this->getContentByBid($bid);
  1100. if (!$content) {
  1101. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1102. }
  1103. } else {
  1104. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1105. }
  1106. // 构建消息
  1107. $messages = [
  1108. $this->sys_message,
  1109. [
  1110. 'role' => 'user',
  1111. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1112. ]
  1113. ];
  1114. $post_data = [
  1115. 'model' => $model,
  1116. 'messages' => $messages,
  1117. 'max_tokens' => 8192,
  1118. 'temperature' => 0.7,
  1119. 'frequency_penalty' => 0,
  1120. 'presence_penalty' => 0,
  1121. 'response_format' => ['type' => 'text'],
  1122. 'stream' => false
  1123. ];
  1124. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1125. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1126. $response = $result->getBody()->getContents();
  1127. $response_arr = json_decode($response, true);
  1128. $content = '';
  1129. $usage = [];
  1130. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1131. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1132. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  1133. }
  1134. // \Log::info('返回值内容: '.$content);
  1135. $script_arr = [];
  1136. // 处理结果
  1137. if ($content) {
  1138. $script_arr = handleScriptContent($content);
  1139. }
  1140. return [
  1141. 'script' => $script_arr,
  1142. 'answer' => $content,
  1143. 'usage' => $usage
  1144. ];
  1145. }
  1146. public function saveScript($data) {
  1147. $script_arr =getProp($data, 'script', []);
  1148. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1149. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1150. $script_id = getProp($data, 'script_id');
  1151. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1152. try {
  1153. DB::beginTransaction();
  1154. $update_data = [
  1155. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1156. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1157. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1158. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1159. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1160. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1161. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1162. 'status' => 3,
  1163. 'start_episode_sequence' => $start_episode_sequence,
  1164. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1165. 'episode_num' => count($script_arr['episodes']),
  1166. 'updated_at' => date('Y-m-d H:i:s')
  1167. ];
  1168. // 保存剧本内容
  1169. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1170. if (!$boolen) {
  1171. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1172. Utils::throwError('20003:剧本内容保存失败');
  1173. }
  1174. // 保存分集内容
  1175. // 删除历史分集内容
  1176. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1177. $episodes = [];
  1178. $sequence = 1;
  1179. foreach ($script_arr['episodes'] as $episode) {
  1180. $segment_number = 1;
  1181. foreach($episode['segments'] as $segment) {
  1182. $episodes[] = [
  1183. 'script_id' => $script_id,
  1184. 'episode_number' => $episode['episode_number'],
  1185. 'title' => $episode['title'],
  1186. // 'content' => $episode['content'],
  1187. 'content' => '',
  1188. 'segment_number' => $segment_number,
  1189. 'segment_content' => $segment['segment_content'],
  1190. 'sequence' => $sequence,
  1191. 'created_at' => date('Y-m-d H:i:s'),
  1192. 'updated_at' => date('Y-m-d H:i:s')
  1193. ];
  1194. $sequence++;
  1195. $segment_number++;
  1196. }
  1197. }
  1198. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1199. if (!$boolen2) {
  1200. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1201. Utils::throwError('20003:分集内容保存失败');
  1202. }
  1203. } catch (\Exception $e) {
  1204. DB::rollBack();
  1205. Utils::throwError('20003:'.$e->getMessage());
  1206. }
  1207. DB::commit();
  1208. return true;
  1209. }
  1210. public function exportScript($data) {
  1211. $script = $this->scriptInfo($data);
  1212. $export_type = getProp($data, 'export_type', 'txt');
  1213. // 生成文件名
  1214. $filename = $script['script_name'] . '_' . date('YmdHis');
  1215. // 根据导出类型生成不同格式的文件
  1216. switch ($export_type) {
  1217. case 'txt':
  1218. return $this->exportScriptAsTxt($script, $filename);
  1219. case 'pdf':
  1220. return $this->exportScriptAsPdf($script, $filename);
  1221. default:
  1222. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1223. }
  1224. }
  1225. /**
  1226. * 导出剧本为TXT格式
  1227. */
  1228. private function exportScriptAsTxt($script, $filename) {
  1229. // 构建TXT内容
  1230. $content = $this->buildScriptContent($script);
  1231. // 设置响应头,直接下载
  1232. header('Content-Type: text/plain; charset=utf-8');
  1233. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1234. header('Content-Length: ' . strlen($content));
  1235. // 输出内容并结束
  1236. echo $content;
  1237. exit();
  1238. }
  1239. /**
  1240. * 导出剧本为PDF格式
  1241. */
  1242. private function exportScriptAsPdf($script, $filename) {
  1243. // 使用HTML转PDF的方式来更好地支持中文
  1244. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1245. // 创建PDF实例
  1246. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1247. // 设置文档信息
  1248. $pdf->SetCreator('剧本导出系统');
  1249. $pdf->SetAuthor('系统');
  1250. $pdf->SetTitle($script['script_name']);
  1251. $pdf->SetSubject('剧本导出');
  1252. // 设置边距
  1253. $pdf->SetMargins(15, 15, 15);
  1254. $pdf->SetAutoPageBreak(TRUE, 15);
  1255. // 添加页面
  1256. $pdf->AddPage();
  1257. // 注册并使用 simsun.ttf 字体
  1258. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1259. // 使用HTML内容生成PDF
  1260. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1261. // 直接输出PDF文件供下载
  1262. header('Content-Type: application/pdf');
  1263. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1264. // 直接输出PDF内容
  1265. $pdf->Output($filename . '.pdf', 'D');
  1266. exit();
  1267. }
  1268. /**
  1269. * 构建用于PDF的HTML内容
  1270. */
  1271. private function buildScriptHtmlForPdf($script) {
  1272. $html = '<style>
  1273. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  1274. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  1275. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  1276. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  1277. .info { margin-bottom: 8px; }
  1278. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  1279. .segment { margin-bottom: 10px; margin-left: 20px; }
  1280. </style>';
  1281. // 标题
  1282. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  1283. // 剧本简介
  1284. if (!empty($script['intro'])) {
  1285. $html .= '<h2>剧本简介</h2>';
  1286. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  1287. }
  1288. // 亮点
  1289. if (!empty($script['highlights'])) {
  1290. $html .= '<h2>亮点</h2>';
  1291. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  1292. }
  1293. // 核心矛盾
  1294. if (!empty($script['core_contradiction'])) {
  1295. $html .= '<h2>核心矛盾</h2>';
  1296. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  1297. }
  1298. // 艺术风格
  1299. if (!empty($script['art_style'])) {
  1300. $html .= '<h2>艺术风格</h2>';
  1301. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  1302. }
  1303. // 角色列表
  1304. if (!empty($script['roles']) && is_array($script['roles'])) {
  1305. $html .= '<h2>角色列表</h2>';
  1306. $html .= '<ul>';
  1307. foreach ($script['roles'] as $role) {
  1308. if (is_array($role) || is_object($role)) {
  1309. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  1310. } else {
  1311. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  1312. }
  1313. }
  1314. $html .= '</ul>';
  1315. }
  1316. // 角色关系
  1317. if (!empty($script['role_relationship'])) {
  1318. $html .= '<h2>角色关系</h2>';
  1319. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  1320. }
  1321. // 场景列表
  1322. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1323. $html .= '<h2>场景列表</h2>';
  1324. $html .= '<ul>';
  1325. foreach ($script['scenes'] as $scene) {
  1326. if (is_array($scene) || is_object($scene)) {
  1327. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  1328. } else {
  1329. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  1330. }
  1331. }
  1332. $html .= '</ul>';
  1333. }
  1334. // 分集内容
  1335. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1336. $html .= '<h2>分集内容</h2>';
  1337. foreach ($script['episodes'] as $episode) {
  1338. $html .= '<div class="episode">';
  1339. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  1340. if (!empty($episode['title'])) {
  1341. $html .= ':' . htmlspecialchars($episode['title']);
  1342. }
  1343. $html .= '</h3>';
  1344. // 处理分段内容
  1345. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1346. foreach ($episode['segments'] as $segment) {
  1347. if (!empty($segment['segment_content'])) {
  1348. $html .= '<div class="segment">';
  1349. if (!empty($segment['segment_number'])) {
  1350. $html .= '<strong>第' . htmlspecialchars($segment['segment_number']) . '段</strong><br>';
  1351. }
  1352. $html .= nl2br(htmlspecialchars($segment['segment_content']));
  1353. $html .= '</div>';
  1354. }
  1355. }
  1356. }
  1357. $html .= '</div>';
  1358. }
  1359. }
  1360. return $html;
  1361. }
  1362. /**
  1363. * 构建PDF内容
  1364. */
  1365. private function buildPdfContent($pdf, $script) {
  1366. // 标题
  1367. $pdf->SetFont('dejavusans', 'B', 18);
  1368. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  1369. $pdf->Ln(5);
  1370. // 基本信息
  1371. $pdf->SetFont('dejavusans', '', 12);
  1372. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  1373. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  1374. $pdf->Ln(5);
  1375. // 剧本简介
  1376. if (!empty($script['intro'])) {
  1377. $pdf->SetFont('dejavusans', 'B', 14);
  1378. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  1379. $pdf->SetFont('dejavusans', '', 12);
  1380. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  1381. $pdf->Ln(3);
  1382. }
  1383. // 亮点
  1384. if (!empty($script['highlights'])) {
  1385. $pdf->SetFont('dejavusans', 'B', 14);
  1386. $pdf->Cell(0, 10, '亮点', 0, 1);
  1387. $pdf->SetFont('dejavusans', '', 12);
  1388. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  1389. $pdf->Ln(3);
  1390. }
  1391. // 核心矛盾
  1392. if (!empty($script['core_contradiction'])) {
  1393. $pdf->SetFont('dejavusans', 'B', 14);
  1394. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  1395. $pdf->SetFont('dejavusans', '', 12);
  1396. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  1397. $pdf->Ln(3);
  1398. }
  1399. // 艺术风格
  1400. if (!empty($script['art_style'])) {
  1401. $pdf->SetFont('dejavusans', 'B', 14);
  1402. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  1403. $pdf->SetFont('dejavusans', '', 12);
  1404. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  1405. $pdf->Ln(3);
  1406. }
  1407. // 备注
  1408. if (!empty($script['remark'])) {
  1409. $pdf->SetFont('dejavusans', 'B', 14);
  1410. $pdf->Cell(0, 10, '备注', 0, 1);
  1411. $pdf->SetFont('dejavusans', '', 12);
  1412. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  1413. $pdf->Ln(3);
  1414. }
  1415. // 角色列表
  1416. if (!empty($script['roles']) && is_array($script['roles'])) {
  1417. $pdf->SetFont('dejavusans', 'B', 14);
  1418. $pdf->Cell(0, 10, '角色列表', 0, 1);
  1419. $pdf->SetFont('dejavusans', '', 12);
  1420. foreach ($script['roles'] as $index => $role) {
  1421. if (is_array($role) || is_object($role)) {
  1422. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  1423. } else {
  1424. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  1425. }
  1426. }
  1427. $pdf->Ln(3);
  1428. }
  1429. // 角色关系
  1430. if (!empty($script['role_relationship'])) {
  1431. $pdf->SetFont('dejavusans', 'B', 14);
  1432. $pdf->Cell(0, 10, '角色关系', 0, 1);
  1433. $pdf->SetFont('dejavusans', '', 12);
  1434. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  1435. $pdf->Ln(3);
  1436. }
  1437. // 场景列表
  1438. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1439. $pdf->SetFont('dejavusans', 'B', 14);
  1440. $pdf->Cell(0, 10, '场景列表', 0, 1);
  1441. $pdf->SetFont('dejavusans', '', 12);
  1442. foreach ($script['scenes'] as $index => $scene) {
  1443. if (is_array($scene) || is_object($scene)) {
  1444. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  1445. } else {
  1446. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  1447. }
  1448. }
  1449. $pdf->Ln(5);
  1450. }
  1451. // 分集内容
  1452. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1453. $pdf->SetFont('dejavusans', 'B', 16);
  1454. $pdf->Cell(0, 12, '分集内容', 0, 1);
  1455. $pdf->Ln(3);
  1456. foreach ($script['episodes'] as $episode) {
  1457. // 检查是否需要新页面
  1458. if ($pdf->GetY() > 250) {
  1459. $pdf->AddPage();
  1460. }
  1461. $pdf->SetFont('dejavusans', 'B', 14);
  1462. $episodeTitle = '第' . $episode['episode_number'] . '集';
  1463. if (!empty($episode['title'])) {
  1464. $episodeTitle .= ':' . $episode['title'];
  1465. }
  1466. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  1467. // 处理分段内容
  1468. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1469. $pdf->SetFont('dejavusans', '', 12);
  1470. foreach ($episode['segments'] as $segment) {
  1471. if (!empty($segment['segment_content'])) {
  1472. // 如果有分段编号,显示分段标题
  1473. if (!empty($segment['segment_number'])) {
  1474. $pdf->SetFont('dejavusans', 'B', 12);
  1475. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  1476. $pdf->SetFont('dejavusans', '', 12);
  1477. }
  1478. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  1479. $pdf->Ln(2);
  1480. }
  1481. }
  1482. }
  1483. $pdf->Ln(5);
  1484. }
  1485. }
  1486. }
  1487. /**
  1488. * 构建剧本文本内容
  1489. */
  1490. private function buildScriptContent($script) {
  1491. $content = '';
  1492. // 剧本基本信息
  1493. if (!empty($script['intro'])) {
  1494. $content .= "###故事梗概\n" . $script['intro'] . "\n\n";
  1495. }
  1496. if (!empty($script['highlights'])) {
  1497. $content .= "###剧本亮点\n" . $script['highlights'] . "\n\n";
  1498. }
  1499. if (!empty($script['role_relationship'])) {
  1500. $content .= "###人物关系\n" . $script['role_relationship'] . "\n\n";
  1501. }
  1502. if (!empty($script['core_contradiction'])) {
  1503. $content .= "###核心矛盾\n" . $script['core_contradiction'] . "\n\n";
  1504. }
  1505. if (!empty($script['roles']) && is_array($script['roles'])) {
  1506. $content .= "###主体列表\n";
  1507. foreach ($script['roles'] as $role) {
  1508. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  1509. }
  1510. $content .= "\n\n";
  1511. }
  1512. if (!empty($script['art_style'])) {
  1513. $content .= "###美术风格\n" . $script['art_style'] . "\n\n";
  1514. }
  1515. // 场景信息
  1516. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1517. $content .= "###场景列表\n";
  1518. foreach ($script['scenes'] as $scene) {
  1519. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  1520. }
  1521. $content .= "\n\n";
  1522. }
  1523. // 分集内容
  1524. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1525. $content .= "###分集剧本\n";
  1526. foreach ($script['episodes'] as $episode) {
  1527. $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  1528. if (!empty($episode['title'])) {
  1529. $content .= ":" . $episode['title'];
  1530. }
  1531. $content .= "\n";
  1532. // 处理分镜
  1533. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1534. foreach ($episode['segments'] as $segment) {
  1535. $content .= "分镜" . $episode['episode_number'] . '-' . $segment['segment_number'] . "\n";
  1536. $content .= $segment['segment_content'] . "\n\n";
  1537. }
  1538. }
  1539. }
  1540. }
  1541. return $content;
  1542. }
  1543. /**
  1544. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1545. *
  1546. * @param array $data 包含以下参数:
  1547. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1548. * - question: 用户问题(可选)
  1549. * - model: 使用的模型(r1 或 v3,默认 v3)
  1550. * @return \Generator 返回生成器,用于流式输出
  1551. */
  1552. public function addChat($data) {
  1553. $uid = Site::getUid();
  1554. $file = getProp($data, 'file');
  1555. $content = getProp($data, 'content', '');
  1556. $bid = getProp($data, 'bid', 0);
  1557. $question =getProp($data, 'question', "请根据实例格式完成剧本大纲");
  1558. $prompt = getProp($data, 'prompt', '帮我根据给出的内容生成短剧大纲');
  1559. $model = getProp($data, 'model', 'v3');
  1560. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1561. if (!$file && !$content && !$bid) {
  1562. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1563. }
  1564. // 提取文件内容
  1565. if ($content) {
  1566. $content = filterContent($content);
  1567. } elseif ($file) {
  1568. $content = $this->extractFileContent($file);
  1569. if (!$content) {
  1570. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1571. }
  1572. } elseif ($bid) {
  1573. $content = $this->getContentByBid($bid);
  1574. if (!$content) {
  1575. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1576. }
  1577. } else {
  1578. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1579. }
  1580. // 美术风格
  1581. $input_art_style = getProp($data, 'art_style');
  1582. // 构建消息
  1583. $messages = [
  1584. [
  1585. 'role' => 'system',
  1586. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1587. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  1588. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  1589. 3.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答\n
  1590. 示例如下:\n\n
  1591. ###剧本名:西昆仑
  1592. ###故事梗概
  1593. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1594. ###剧本亮点
  1595. 亮点1:绝境奇药,生死一线
  1596. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1597. 亮点2:结拜兄妹,化解尴尬
  1598. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1599. 亮点3:纤发夺命,情愫暗涌
  1600. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1601. ###人物关系
  1602. 阿雪与梁萧之间存在兄妹之情。
  1603. ###核心矛盾
  1604. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1605. ###主体列表
  1606. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1607. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1608. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1609. 阴阳球:天地异宝,能化生精气,救人于危难。
  1610. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1611. ###美术风格
  1612. 基础画风风格词:厚涂古风
  1613. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1614. ###场景列表
  1615. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"
  1616. ],
  1617. [
  1618. 'role' => 'user',
  1619. 'content' => "以下是文档内容:
  1620. {$content}
  1621. 用户问题:
  1622. {$question}"
  1623. ]
  1624. ];
  1625. $post_data = [
  1626. 'model' => $model,
  1627. 'messages' => $messages,
  1628. 'max_tokens' => 8192,
  1629. 'temperature' => 0.7,
  1630. 'frequency_penalty' => 0,
  1631. 'presence_penalty' => 0,
  1632. 'response_format' => ['type' => 'text'],
  1633. 'stream' => true // 启用流式输出
  1634. ];
  1635. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1636. $response = $client->post($this->url, [
  1637. 'json' => $post_data,
  1638. 'headers' => $this->headers,
  1639. 'stream' => true // 启用流式响应
  1640. ]);
  1641. $body = $response->getBody();
  1642. $fullContent = '';
  1643. $fullReasoningContent = '';
  1644. $usage = [];
  1645. $buffer = '';
  1646. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1647. // 逐行读取流式响应
  1648. while (!$body->eof()) {
  1649. $chunk = $body->read(1024); // 每次读取 1KB
  1650. $buffer .= $chunk;
  1651. // 按行分割
  1652. $lines = explode("\n", $buffer);
  1653. // 保留最后一个不完整的行
  1654. $buffer = array_pop($lines);
  1655. foreach ($lines as $line) {
  1656. $line = trim($line);
  1657. // 跳过空行
  1658. if (empty($line)) {
  1659. continue;
  1660. }
  1661. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  1662. // 检查是否是 SSE 数据行
  1663. if (strpos($line, 'data: ') !== 0) {
  1664. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1665. continue;
  1666. }
  1667. $data = substr($line, 6); // 移除 "data: " 前缀
  1668. if ($data === '[DONE]') {
  1669. dLog('deepseek')->info('收到结束标记');
  1670. break 2; // 跳出两层循环
  1671. }
  1672. try {
  1673. $json = json_decode($data, true);
  1674. if (json_last_error() !== JSON_ERROR_NONE) {
  1675. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1676. continue;
  1677. }
  1678. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1679. if (isset($json['choices'][0]['delta'])) {
  1680. $delta = $json['choices'][0]['delta'];
  1681. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1682. // 注释掉以下内容则不返回d思维链内容
  1683. if (isset($delta['reasoning_content'])) {
  1684. $fullReasoningContent .= $delta['reasoning_content'];
  1685. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1686. yield [
  1687. 'type' => 'reasoning',
  1688. 'content' => $delta['reasoning_content'],
  1689. 'full_reasoning' => $fullReasoningContent
  1690. ];
  1691. }
  1692. // 处理最终回答内容
  1693. if (isset($delta['content'])) {
  1694. $fullContent .= $delta['content'];
  1695. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  1696. yield [
  1697. 'type' => 'content',
  1698. 'content' => $delta['content'],
  1699. 'full_content' => $fullContent
  1700. ];
  1701. }
  1702. }
  1703. // 获取使用统计信息
  1704. if (isset($json['usage'])) {
  1705. $usage = $json['usage'];
  1706. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1707. }
  1708. } catch (\Exception $e) {
  1709. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1710. continue;
  1711. }
  1712. }
  1713. }
  1714. dLog('deepseek')->info('流式读取完成', [
  1715. 'content_length' => strlen($fullContent),
  1716. 'reasoning_length' => strlen($fullReasoningContent)
  1717. ]);
  1718. dLog('deepseek')->info('完整内容: '.$fullContent);
  1719. // 处理完整内容并返回最终结果
  1720. $script_arr = [];
  1721. if ($fullContent) {
  1722. $script_arr = handleScriptContent($fullContent);
  1723. }
  1724. // 替换美术风格
  1725. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  1726. if ($mappedArtStyle !== '') {
  1727. $script_arr['art_style'] = $mappedArtStyle;
  1728. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  1729. }
  1730. // 新建动漫
  1731. $anime_name = getProp($script_arr, 'script_name');
  1732. if (!$anime_name) {
  1733. yield [
  1734. 'type' => 'done',
  1735. 'answer' => $fullContent,
  1736. 'reasoning' => $fullReasoningContent,
  1737. 'usage' => $usage,
  1738. 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  1739. ];
  1740. }
  1741. // 确认对话名称唯一性
  1742. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  1743. $anime_name = $anime_name . '_' . date('YmdHis');
  1744. }
  1745. $table_data = [
  1746. 'user_id' => $uid,
  1747. 'anime_name' => $anime_name,
  1748. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1749. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1750. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1751. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1752. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1753. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1754. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1755. 'status' => '解析完成',
  1756. 'content' => $content,
  1757. // 'start_episode_sequence' => 1,
  1758. // 'end_episode_sequence' => count($script_arr['episodes']),
  1759. // 'episode_num' => count($script_arr['episodes']),
  1760. 'generate_status' => '待执行',
  1761. 'created_at' => date('Y-m-d H:i:s'),
  1762. 'updated_at' => date('Y-m-d H:i:s')
  1763. ];
  1764. try {
  1765. DB::beginTransaction();
  1766. // 新建动漫大纲
  1767. $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  1768. if (!$anime_id) {
  1769. dLog('deepseek')->info('对话保存失败', $table_data);
  1770. Utils::throwError('20003:对话保存失败');
  1771. }
  1772. // 保存对话记录
  1773. $recrods = [
  1774. [
  1775. 'uid' => $uid,
  1776. 'anime_id' => $anime_id,
  1777. 'sequence' => 0,
  1778. 'role' => 'user',
  1779. 'content' => "用户问题:\n
  1780. {$prompt}\n\n
  1781. 以下是文档内容:\n
  1782. {$content}",
  1783. 'created_at' => date('Y-m-d H:i:s'),
  1784. 'updated_at' => date('Y-m-d H:i:s')
  1785. ],
  1786. [
  1787. 'uid' => $uid,
  1788. 'anime_id' => $anime_id,
  1789. 'sequence' => 0,
  1790. 'role' => 'assistant',
  1791. 'content' => $fullContent,
  1792. 'created_at' => date('Y-m-d H:i:s'),
  1793. 'updated_at' => date('Y-m-d H:i:s')
  1794. ]
  1795. ];
  1796. // 保存对话记录
  1797. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  1798. if (!$boolen3) {
  1799. Utils::throwError('20003:对话记录保存失败');
  1800. }
  1801. }catch (\Exception $e) {
  1802. DB::rollBack();
  1803. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  1804. yield [
  1805. 'type' => 'done',
  1806. 'answer' => $fullContent,
  1807. 'reasoning' => $fullReasoningContent,
  1808. 'usage' => $usage,
  1809. 'error' => $e->getMessage(),
  1810. ];
  1811. }
  1812. DB::commit();
  1813. $table_data['anime_id'] = $anime_id;
  1814. $table_data['roles'] = json_decode($table_data['roles'], true);
  1815. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  1816. // $table_data['episodes'] = $script_arr['episodes'];
  1817. unset($table_data['created_at']);
  1818. unset($table_data['updated_at']);
  1819. unset($table_data['status']);
  1820. yield [
  1821. 'type' => 'done',
  1822. 'script' => $table_data,
  1823. 'answer' => $fullContent,
  1824. 'reasoning' => $fullReasoningContent,
  1825. 'usage' => $usage
  1826. ];
  1827. }
  1828. public function reGenerateAnime($data) {
  1829. $uid = Site::getUid();
  1830. $file = getProp($data, 'file');
  1831. $content = getProp($data, 'content', '');
  1832. $bid = getProp($data, 'bid', 0);
  1833. $anime_id = getProp($data, 'anime_id');
  1834. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1835. if (!$anime) {
  1836. Utils::throwError('20003:该对话不存在');
  1837. }
  1838. $question =getProp($data, 'question', "请根据实例格式完成剧本大纲");
  1839. $prompt = getProp($data, 'prompt', '帮我根据给出的内容生成短剧大纲');
  1840. $model = getProp($data, 'model', 'v3');
  1841. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1842. // 提取文件内容
  1843. if ($content) {
  1844. $content = filterContent($content);
  1845. } elseif ($file) {
  1846. $content = $this->extractFileContent($file);
  1847. if (!$content) {
  1848. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1849. }
  1850. } elseif ($bid) {
  1851. $content = $this->getContentByBid($bid);
  1852. if (!$content) {
  1853. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1854. }
  1855. } else {
  1856. $content = filterContent(getProp($anime, 'content'));
  1857. }
  1858. // 美术风格
  1859. $input_art_style = getProp($data, 'art_style');
  1860. $system_message = [
  1861. 'role' => 'system',
  1862. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1863. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  1864. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  1865. 3.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答\n
  1866. 示例如下:\n\n
  1867. ###剧本名:西昆仑
  1868. ###故事梗概
  1869. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1870. ###剧本亮点
  1871. 亮点1:绝境奇药,生死一线
  1872. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1873. 亮点2:结拜兄妹,化解尴尬
  1874. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1875. 亮点3:纤发夺命,情愫暗涌
  1876. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1877. ###人物关系
  1878. 阿雪与梁萧之间存在兄妹之情。
  1879. ###核心矛盾
  1880. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1881. ###主体列表
  1882. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1883. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1884. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1885. 阴阳球:天地异宝,能化生精气,救人于危难。
  1886. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1887. ###美术风格
  1888. 基础画风风格词:厚涂古风
  1889. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1890. ###场景列表
  1891. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"
  1892. ];
  1893. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  1894. $episode_count = $this->extractEpisodeNumber($prompt);
  1895. if ($episode_count) {
  1896. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  1897. $system_message = [
  1898. 'role' => 'system',
  1899. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  1900. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  1901. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  1902. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n
  1903. 4.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答\n
  1904. 示例如下:\n\n
  1905. ###剧本名:西昆仑
  1906. ###故事梗概
  1907. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1908. ###剧本亮点
  1909. 亮点1:绝境奇药,生死一线
  1910. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1911. 亮点2:结拜兄妹,化解尴尬
  1912. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1913. 亮点3:纤发夺命,情愫暗涌
  1914. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1915. ###人物关系
  1916. 阿雪与梁萧之间存在兄妹之情。
  1917. ###核心矛盾
  1918. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1919. ###主体列表
  1920. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1921. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1922. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1923. 阴阳球:天地异宝,能化生精气,救人于危难。
  1924. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1925. ###美术风格
  1926. 基础画风风格词:厚涂古风
  1927. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1928. ###场景列表
  1929. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  1930. ###分集详细内容
  1931. ##第1章 重生
  1932. 我重生了。
  1933. 源于一个男人偏执的暗恋。
  1934. ##第2章 相救
  1935. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  1936. 我眼睛扫向站在锅炉后的卞大伟。"
  1937. ];
  1938. // 构建消息
  1939. $messages = [
  1940. $system_message,
  1941. [
  1942. 'role' => 'user',
  1943. 'content' => "以下是文档内容:
  1944. {$content}
  1945. 用户问题:
  1946. {$question}"
  1947. ]
  1948. ];
  1949. }else {
  1950. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  1951. // 构建消息
  1952. $messages = [
  1953. $system_message,
  1954. [
  1955. 'role' => 'user',
  1956. 'content' => "以下是文档内容:
  1957. {$content}
  1958. 用户问题:
  1959. {$question}"
  1960. ]
  1961. ];
  1962. }else {
  1963. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  1964. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  1965. return (array)$value;
  1966. })->toArray();
  1967. array_unshift($messages, $system_message);
  1968. $messages[] = [
  1969. 'role' => 'user',
  1970. 'content' => $prompt
  1971. ];
  1972. }
  1973. }
  1974. $post_data = [
  1975. 'model' => $model,
  1976. 'messages' => $messages,
  1977. 'max_tokens' => 8192,
  1978. 'temperature' => 0.7,
  1979. 'frequency_penalty' => 0,
  1980. 'presence_penalty' => 0,
  1981. 'response_format' => ['type' => 'text'],
  1982. 'stream' => true // 启用流式输出
  1983. ];
  1984. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1985. $response = $client->post($this->url, [
  1986. 'json' => $post_data,
  1987. 'headers' => $this->headers,
  1988. 'stream' => true // 启用流式响应
  1989. ]);
  1990. $body = $response->getBody();
  1991. $fullContent = '';
  1992. $fullReasoningContent = '';
  1993. $usage = [];
  1994. $buffer = '';
  1995. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1996. // 逐行读取流式响应
  1997. while (!$body->eof()) {
  1998. $chunk = $body->read(1024); // 每次读取 1KB
  1999. $buffer .= $chunk;
  2000. // 按行分割
  2001. $lines = explode("\n", $buffer);
  2002. // 保留最后一个不完整的行
  2003. $buffer = array_pop($lines);
  2004. foreach ($lines as $line) {
  2005. $line = trim($line);
  2006. // 跳过空行
  2007. if (empty($line)) {
  2008. continue;
  2009. }
  2010. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  2011. // 检查是否是 SSE 数据行
  2012. if (strpos($line, 'data: ') !== 0) {
  2013. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2014. continue;
  2015. }
  2016. $data = substr($line, 6); // 移除 "data: " 前缀
  2017. if ($data === '[DONE]') {
  2018. dLog('deepseek')->info('收到结束标记');
  2019. break 2; // 跳出两层循环
  2020. }
  2021. try {
  2022. $json = json_decode($data, true);
  2023. if (json_last_error() !== JSON_ERROR_NONE) {
  2024. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2025. continue;
  2026. }
  2027. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  2028. if (isset($json['choices'][0]['delta'])) {
  2029. $delta = $json['choices'][0]['delta'];
  2030. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2031. // 注释掉以下内容则不返回d思维链内容
  2032. if (isset($delta['reasoning_content'])) {
  2033. $fullReasoningContent .= $delta['reasoning_content'];
  2034. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  2035. yield [
  2036. 'type' => 'reasoning',
  2037. 'content' => $delta['reasoning_content'],
  2038. 'full_reasoning' => $fullReasoningContent
  2039. ];
  2040. }
  2041. // 处理最终回答内容
  2042. if (isset($delta['content'])) {
  2043. $fullContent .= $delta['content'];
  2044. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  2045. yield [
  2046. 'type' => 'content',
  2047. 'content' => $delta['content'],
  2048. 'full_content' => $fullContent
  2049. ];
  2050. }
  2051. }
  2052. // 获取使用统计信息
  2053. if (isset($json['usage'])) {
  2054. $usage = $json['usage'];
  2055. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2056. }
  2057. } catch (\Exception $e) {
  2058. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2059. continue;
  2060. }
  2061. }
  2062. }
  2063. dLog('deepseek')->info('流式读取完成', [
  2064. 'content_length' => strlen($fullContent),
  2065. 'reasoning_length' => strlen($fullReasoningContent)
  2066. ]);
  2067. dLog('deepseek')->info('完整内容: '.$fullContent);
  2068. // 处理完整内容并返回最终结果
  2069. $script_arr = [];
  2070. if ($fullContent) {
  2071. $script_arr = handleScriptContent($fullContent);
  2072. }
  2073. // 替换美术风格
  2074. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2075. if ($mappedArtStyle !== '') {
  2076. $script_arr['art_style'] = $mappedArtStyle;
  2077. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2078. }
  2079. // // 新建动漫
  2080. // $anime_name = getProp($script_arr, 'script_name');
  2081. // if (!$anime_name) {
  2082. // yield [
  2083. // 'type' => 'done',
  2084. // 'answer' => $fullContent,
  2085. // 'reasoning' => $fullReasoningContent,
  2086. // 'usage' => $usage,
  2087. // 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  2088. // ];
  2089. // }
  2090. // // 确认对话名称唯一性
  2091. // if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2092. // $anime_name = $anime_name . '_' . date('YmdHis');
  2093. // }
  2094. $table_data = [
  2095. 'user_id' => $uid,
  2096. // 'anime_name' => $anime_name,
  2097. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2098. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2099. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2100. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2101. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2102. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2103. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2104. 'status' => '解析完成',
  2105. 'generate_status' => '待执行',
  2106. 'updated_at' => date('Y-m-d H:i:s')
  2107. ];
  2108. // 如果是修改集数,则将content内容更新(会改变原文)
  2109. if (isset($episode_count) && $episode_count > 0) {
  2110. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  2111. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  2112. }else {
  2113. $chapters = $this->splitContent($content);
  2114. $chapter_count = count($chapters);
  2115. if ($chapter_count > 0) {
  2116. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  2117. }
  2118. }
  2119. try {
  2120. DB::beginTransaction();
  2121. // 新建动漫大纲
  2122. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2123. if (!$boolen) {
  2124. dLog('deepseek')->info('对话修改失败', $table_data);
  2125. Utils::throwError('20003:对话修改失败');
  2126. }
  2127. // 保存对话记录
  2128. $recrods = [
  2129. [
  2130. 'uid' => $uid,
  2131. 'anime_id' => $anime_id,
  2132. 'sequence' => 0,
  2133. 'role' => 'user',
  2134. 'content' => $prompt,
  2135. 'created_at' => date('Y-m-d H:i:s'),
  2136. 'updated_at' => date('Y-m-d H:i:s')
  2137. ],
  2138. [
  2139. 'uid' => $uid,
  2140. 'anime_id' => $anime_id,
  2141. 'sequence' => 0,
  2142. 'role' => 'assistant',
  2143. 'content' => $fullContent,
  2144. 'created_at' => date('Y-m-d H:i:s'),
  2145. 'updated_at' => date('Y-m-d H:i:s')
  2146. ]
  2147. ];
  2148. // 保存对话记录
  2149. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  2150. if (!$boolen3) {
  2151. Utils::throwError('20003:对话记录保存失败');
  2152. }
  2153. }catch (\Exception $e) {
  2154. DB::rollBack();
  2155. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2156. yield [
  2157. 'type' => 'done',
  2158. 'answer' => $fullContent,
  2159. 'reasoning' => $fullReasoningContent,
  2160. 'usage' => $usage,
  2161. 'error' => $e->getMessage(),
  2162. ];
  2163. }
  2164. DB::commit();
  2165. $table_data['anime_id'] = $anime_id;
  2166. $table_data['roles'] = json_decode($table_data['roles'], true);
  2167. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2168. unset($table_data['updated_at']);
  2169. unset($table_data['status']);
  2170. yield [
  2171. 'type' => 'done',
  2172. 'script' => $table_data,
  2173. 'answer' => $fullContent,
  2174. 'reasoning' => $fullReasoningContent,
  2175. 'usage' => $usage
  2176. ];
  2177. }
  2178. public function chat($data) {
  2179. $uid = Site::getUid();
  2180. $anime_id = getProp($data, 'anime_id');
  2181. $episode_number = getProp($data, 'episode_number', 1);
  2182. $anime = DB::table('mp_animes')->where('id', $anime_id)->select('content', 'roles', 'scenes')->first();
  2183. if (!$anime) Utils::throwError('20003:该对话不存在!');
  2184. $roles = json_decode(getProp($anime, 'roles'), true);
  2185. $scenes = json_decode(getProp($anime, 'scenes'), true);
  2186. // 转换主体列表和场景列表的格式
  2187. $roles_content = '';
  2188. foreach ($roles as $role) {
  2189. $roles_content .= getProp($role, 'role').': '.getProp($role, 'description')."\n";
  2190. }
  2191. $scenes_content = '';
  2192. foreach($scenes as $scene) {
  2193. $scenes_content .= getProp($scene, 'scene').': '.getProp($scene, 'description')."\n";
  2194. }
  2195. $prompt = getProp($data, 'prompt', '确认分镜大纲');
  2196. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2197. 0.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答\n
  2198. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}
  2199. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$roles_content}\n
  2200. 3.<场景列表>必须在以下场景中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$scenes_content}\n
  2201. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”: \n
  2202. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。\n
  2203. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音音色”、“台词内容”和“画面类型”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。\n
  2204. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。\n
  2205. 4.4“分镜信息”中的“台词内容”需与原文中的台词完全一致,不得修改或添加任何内容。\n
  2206. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。\n
  2207. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)\n
  2208. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无\n
  2209. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面\n
  2210. 示例格式:\n\n
  2211. 第1集:隐形的守护者
  2212. ###故事梗概
  2213. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  2214. ###美术风格
  2215. 基础画风风格词:韩漫二次元
  2216. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  2217. ###主体列表
  2218. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。
  2219. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。
  2220. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。
  2221. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。
  2222. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。
  2223. ###场景列表
  2224. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  2225. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  2226. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  2227. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  2228. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  2229. ###分镜剧本
  2230. ##第1幕:徐家老旧厨房 白天 室内
  2231. 分镜1
  2232. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2233. 场景:徐家老旧厨房
  2234. 构图设计:全景,低角度仰视
  2235. 运镜调度:手持拍摄
  2236. 配音角色:旁白
  2237. 出镜角色:许芸-校服装、徐母
  2238. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2239. 画面类型:普通画面
  2240. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2241. 分镜2
  2242. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2243. 场景:徐家老旧厨房
  2244. 构图设计:近景,徐母面部特写
  2245. 运镜调度:固定镜头
  2246. 配音角色:徐母
  2247. 出镜角色:徐母
  2248. 台词内容:问我夜不归宿死哪儿去了。
  2249. 画面类型:对口型
  2250. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2251. ##第2幕:徐家简陋客厅 黄昏 室内
  2252. 分镜3
  2253. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2254. 场景:徐家简陋客厅
  2255. 构图设计:全景,景深虚化
  2256. 运镜调度:固定镜头
  2257. 配音角色:旁白
  2258. 出镜角色:无
  2259. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2260. 画面类型:普通画面
  2261. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2262. 分镜4
  2263. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2264. 场景:徐家简陋客厅
  2265. 构图设计:特写,火车票
  2266. 运镜调度:固定镜头
  2267. 配音角色:旁白
  2268. 出镜角色:无
  2269. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2270. 画面类型:普通画面
  2271. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  2272. \n\n";
  2273. // 获取章节内容
  2274. $full_content = getProp($anime, 'content');
  2275. // 根据章节内容拆分章节
  2276. $chapters = $this->splitContent($full_content);
  2277. if ($prompt == '确认分镜大纲') {
  2278. $content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2279. if (!$content) {
  2280. Utils::throwError('20003:章节内容无法获取,请确认');
  2281. }
  2282. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  2283. // 构建消息
  2284. $messages[] =
  2285. [
  2286. 'role' => 'user',
  2287. 'content' => $question
  2288. ];
  2289. }else if ($prompt == '继续策划下一集') {
  2290. $content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2291. if (!$content) {
  2292. Utils::throwError('20003:章节内容无法获取,请确认');
  2293. }
  2294. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  2295. // 获取上一集最后记录
  2296. $prev_sequence = $episode_number - 1;
  2297. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', $prev_sequence)
  2298. ->select('role', 'content')->orderBy('created_at', 'desc')->orderBy('id')->get()->map(function($value) {
  2299. return (array)$value;
  2300. })->toArray();
  2301. // 构建消息
  2302. $messages[] =
  2303. [
  2304. 'role' => 'user',
  2305. 'content' => $question
  2306. ];
  2307. }else {
  2308. $content = $full_content;
  2309. $question = $prompt;
  2310. $messages[] =
  2311. [
  2312. 'role' => 'user',
  2313. 'content' => $question
  2314. ];
  2315. }
  2316. $model = getProp($data, 'model', 'v3');
  2317. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2318. $post_data = [
  2319. 'model' => $model,
  2320. 'messages' => $messages,
  2321. 'max_tokens' => 8192,
  2322. 'temperature' => 0.7,
  2323. 'frequency_penalty' => 0,
  2324. 'presence_penalty' => 0,
  2325. 'response_format' => ['type' => 'text'],
  2326. 'stream' => true // 启用流式输出
  2327. ];
  2328. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2329. $response = $client->post($this->url, [
  2330. 'json' => $post_data,
  2331. 'headers' => $this->headers,
  2332. 'stream' => true // 启用流式响应
  2333. ]);
  2334. $body = $response->getBody();
  2335. $fullContent = '';
  2336. $fullReasoningContent = '';
  2337. $usage = [];
  2338. $buffer = '';
  2339. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2340. // 逐行读取流式响应
  2341. while (!$body->eof()) {
  2342. $chunk = $body->read(1024); // 每次读取 1KB
  2343. $buffer .= $chunk;
  2344. // 按行分割
  2345. $lines = explode("\n", $buffer);
  2346. // 保留最后一个不完整的行
  2347. $buffer = array_pop($lines);
  2348. foreach ($lines as $line) {
  2349. $line = trim($line);
  2350. // 跳过空行
  2351. if (empty($line)) {
  2352. continue;
  2353. }
  2354. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  2355. // 检查是否是 SSE 数据行
  2356. if (strpos($line, 'data: ') !== 0) {
  2357. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2358. continue;
  2359. }
  2360. $data = substr($line, 6); // 移除 "data: " 前缀
  2361. if ($data === '[DONE]') {
  2362. dLog('deepseek')->info('收到结束标记');
  2363. break 2; // 跳出两层循环
  2364. }
  2365. try {
  2366. $json = json_decode($data, true);
  2367. if (json_last_error() !== JSON_ERROR_NONE) {
  2368. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2369. continue;
  2370. }
  2371. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  2372. if (isset($json['choices'][0]['delta'])) {
  2373. $delta = $json['choices'][0]['delta'];
  2374. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2375. // 注释掉以下内容则不返回d思维链内容
  2376. if (isset($delta['reasoning_content'])) {
  2377. $fullReasoningContent .= $delta['reasoning_content'];
  2378. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  2379. yield [
  2380. 'type' => 'reasoning',
  2381. 'content' => $delta['reasoning_content'],
  2382. 'full_reasoning' => $fullReasoningContent
  2383. ];
  2384. }
  2385. // 处理最终回答内容
  2386. if (isset($delta['content'])) {
  2387. $fullContent .= $delta['content'];
  2388. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  2389. yield [
  2390. 'type' => 'content',
  2391. 'content' => $delta['content'],
  2392. 'full_content' => $fullContent
  2393. ];
  2394. }
  2395. }
  2396. // 获取使用统计信息
  2397. if (isset($json['usage'])) {
  2398. $usage = $json['usage'];
  2399. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2400. }
  2401. } catch (\Exception $e) {
  2402. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2403. continue;
  2404. }
  2405. }
  2406. }
  2407. dLog('deepseek')->info('流式读取完成', [
  2408. 'content_length' => strlen($fullContent),
  2409. 'reasoning_length' => strlen($fullReasoningContent)
  2410. ]);
  2411. // // $fullContent = '111';
  2412. // // $fullReasoningContent = [];
  2413. // // $usage = [];
  2414. // // $uid = 0;
  2415. // // $content = '';
  2416. // // $question = '';
  2417. // // $episode_number = 1;
  2418. // // $anime_id = 13;
  2419. // $fullContent = DB::table('mp_anime_records')->orderBy('id', 'desc')->value('content');
  2420. dLog('deepseek')->info('完整内容: '.$fullContent);
  2421. // 处理完整内容并返回最终结果
  2422. $episode_arr = handleEpisodeContent($fullContent);
  2423. try {
  2424. DB::beginTransaction();
  2425. // 新建动漫剧集
  2426. $episode = [
  2427. 'anime_id' => $anime_id,
  2428. 'episode_number' => $episode_number,
  2429. 'title' => $episode_arr['episode_title'],
  2430. 'content' => $content,
  2431. // 'content' => '',
  2432. 'intro' => $episode_arr['intro'],
  2433. 'art_style' => $episode_arr['art_style'],
  2434. 'roles' => json_encode($episode_arr['roles'], 256),
  2435. 'scenes' => json_encode($episode_arr['scenes'], 256),
  2436. 'sequence' => 1,
  2437. 'generate_status' => '待执行',
  2438. 'generate_at' => date('Y-m-d H:i:s'),
  2439. 'is_default' => 1,
  2440. 'updated_at' => date('Y-m-d H:i:s'),
  2441. ];
  2442. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->select('id', 'sequence')->first();
  2443. if ($current_episode) {
  2444. $episode['sequence'] = getProp($current_episode, 'sequence');
  2445. $episode_id = getProp($current_episode, 'id');
  2446. $boolen2 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->update($episode);
  2447. }else {
  2448. $episode['created_at'] = date('Y-m-d H:i:s');
  2449. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2450. $boolen2 = $episode_id ? true : false;
  2451. }
  2452. if (!$boolen2) {
  2453. dLog('deepseek')->info('分集内容保存失败', $episode);
  2454. Utils::throwError('20003:分集内容保存失败');
  2455. }
  2456. // 删除历史分集内容
  2457. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->delete();
  2458. $segments = [];
  2459. foreach($episode_arr['acts'] as $act) {
  2460. foreach($act['segments'] as $segment) {
  2461. $segments[] = [
  2462. 'anime_id' => $anime_id,
  2463. 'episode_id' => $episode_id,
  2464. 'episode_number' => $episode_number,
  2465. 'act_number' => $act['act_number'],
  2466. 'act_title' => $act['act_title'],
  2467. 'segment_id' => getProp($segment, 'segment_id'),
  2468. 'segment_number' => getProp($segment, 'segment_number'),
  2469. 'segment_content' => getProp($segment, 'segment_content'),
  2470. 'description' => getProp($segment, 'description'),
  2471. 'composition' => getProp($segment, 'composition'),
  2472. 'camera_movement' => getProp($segment, 'camera_movement'),
  2473. 'voice_actor' => getProp($segment, 'voice_actor'),
  2474. 'dialogue' => getProp($segment, 'dialogue'),
  2475. 'frame_type' => getProp($segment, 'frame_type'),
  2476. 'scene' => getProp($segment, 'scene'),
  2477. 'characters' => getProp($segment, 'characters'),
  2478. 'created_at' => date('Y-m-d H:i:s'),
  2479. 'updated_at' => date('Y-m-d H:i:s')
  2480. ];
  2481. }
  2482. }
  2483. $boolen3 = DB::table('mp_episode_segments')->insert($segments);
  2484. if (!$boolen3) {
  2485. dLog('deepseek')->info('分镜内容保存失败', $episode);
  2486. Utils::throwError('20003:分镜内容保存失败');
  2487. }
  2488. // 保存对话记录
  2489. $recrods = [
  2490. [
  2491. 'uid' => $uid,
  2492. 'anime_id' => $anime_id,
  2493. 'role' => 'user',
  2494. 'content' => $prompt,
  2495. 'sequence' => $episode_number,
  2496. 'created_at' => date('Y-m-d H:i:s'),
  2497. 'updated_at' => date('Y-m-d H:i:s')
  2498. ],
  2499. [
  2500. 'uid' => $uid,
  2501. 'anime_id' => $anime_id,
  2502. 'role' => 'assistant',
  2503. 'content' => $fullContent,
  2504. 'sequence' => $episode_number,
  2505. 'created_at' => date('Y-m-d H:i:s'),
  2506. 'updated_at' => date('Y-m-d H:i:s')
  2507. ]
  2508. ];
  2509. // 保存对话记录
  2510. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  2511. if (!$boolen3) {
  2512. Utils::throwError('20003:对话记录保存失败');
  2513. }
  2514. }catch (\Exception $e) {
  2515. DB::rollBack();
  2516. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2517. yield [
  2518. 'type' => 'done',
  2519. 'answer' => $fullContent,
  2520. 'reasoning' => $fullReasoningContent,
  2521. 'usage' => $usage,
  2522. 'error' => $e->getMessage(),
  2523. ];
  2524. }
  2525. DB::commit();
  2526. // dd('end');
  2527. $episode['episode_id'] = $episode_id;
  2528. $episode['roles'] = json_decode($episode['roles'], true);
  2529. $episode['scenes'] = json_decode($episode['scenes'], true);
  2530. $episode['acts'] = json_decode($episode['acts'], true);
  2531. yield [
  2532. 'type' => 'done',
  2533. 'episode' => $episode,
  2534. 'answer' => $fullContent,
  2535. 'reasoning' => $fullReasoningContent,
  2536. 'usage' => $usage
  2537. ];
  2538. }
  2539. public function chatChangeImg($data) {
  2540. $segment = getProp($data, 'segment');
  2541. $segment_content = getProp($segment, 'segment_content');
  2542. $prompt = getProp($data, 'prompt');
  2543. $ref_img = getProp($data, 'ref_img');
  2544. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  2545. $model = getProp($data, 'model', 'v3');
  2546. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2547. $messages[] =
  2548. [
  2549. 'role' => 'user',
  2550. 'content' => $question
  2551. ];
  2552. $post_data = [
  2553. 'model' => $model,
  2554. 'messages' => $messages,
  2555. 'max_tokens' => 8192,
  2556. 'temperature' => 0.7,
  2557. 'frequency_penalty' => 0,
  2558. 'presence_penalty' => 0,
  2559. 'response_format' => ['type' => 'text'],
  2560. 'stream' => false // 是否启用流式输出
  2561. ];
  2562. // 调用流式输出的deepseek
  2563. $chatResult = $this->chatOnly($post_data);
  2564. if (is_array($chatResult)) {
  2565. extract($chatResult);
  2566. }else {
  2567. Utils::throwError('20003: 接口调用失败!');
  2568. }
  2569. return [
  2570. 'type' => 'done',
  2571. // 'episode' => $episode,
  2572. 'answer' => $fullContent,
  2573. 'reasoning' => $fullReasoningContent,
  2574. 'usage' => $usage
  2575. ];
  2576. }
  2577. // 仅调用deepseek对话接口
  2578. private function chatOnly($post_data) {
  2579. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2580. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2581. $response = $result->getBody()->getContents();
  2582. $response_arr = json_decode($response, true);
  2583. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  2584. $fullContent = '';
  2585. $fullReasoningContent = [];
  2586. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  2587. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2588. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2589. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  2590. }
  2591. return [
  2592. 'fullContent' => $fullContent,
  2593. 'fullReasoningContent' => $fullReasoningContent,
  2594. 'usage' => $usage
  2595. ];
  2596. }
  2597. private function splitContent($content) {
  2598. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  2599. $chapters = [];
  2600. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  2601. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  2602. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  2603. foreach ($matches as $match) {
  2604. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  2605. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  2606. if (!empty($title) && !empty($chapterContent)) {
  2607. $chapters[] = [
  2608. 'title' => $title,
  2609. 'content' => $chapterContent
  2610. ];
  2611. }
  2612. }
  2613. }
  2614. return $chapters;
  2615. }
  2616. public function getContentByBid($bid) {
  2617. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  2618. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  2619. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  2620. $content = '';
  2621. foreach ($chapters as $chapter) {
  2622. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  2623. }
  2624. return $content;
  2625. }
  2626. /**
  2627. * 根据文件类型提取文本内容
  2628. *
  2629. * @param mixed $file 文件对象或文件路径
  2630. * @return string
  2631. */
  2632. public function extractFileContent($file) {
  2633. // 获取文件路径和扩展名
  2634. if (is_string($file)) {
  2635. $filePath = $file;
  2636. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  2637. } else {
  2638. // Laravel UploadedFile 对象
  2639. $filePath = $file->getRealPath();
  2640. $extension = strtolower($file->getClientOriginalExtension());
  2641. }
  2642. $content = '';
  2643. switch ($extension) {
  2644. case 'txt':
  2645. $content = $this->extractTxtContent($filePath);
  2646. break;
  2647. case 'pdf':
  2648. $content = $this->extractPdfContent($filePath);
  2649. break;
  2650. case 'doc':
  2651. case 'docx':
  2652. $content = $this->extractWordContent($filePath);
  2653. break;
  2654. // case 'jpg':
  2655. // case 'jpeg':
  2656. // case 'png':
  2657. // case 'gif':
  2658. // case 'bmp':
  2659. // case 'webp':
  2660. // $content = $this->extractImageContent($filePath);
  2661. // break;
  2662. default:
  2663. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  2664. }
  2665. return $content;
  2666. }
  2667. /**
  2668. * 提取 TXT 文件内容
  2669. */
  2670. private function extractTxtContent($filePath) {
  2671. if (!file_exists($filePath)) {
  2672. Utils::throwError('20003:文件不存在');
  2673. }
  2674. $content = file_get_contents($filePath);
  2675. // 尝试检测并转换编码
  2676. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  2677. if ($encoding && $encoding !== 'UTF-8') {
  2678. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  2679. }
  2680. return trim($content);
  2681. }
  2682. /**
  2683. * 提取 PDF 文件内容
  2684. */
  2685. private function extractPdfContent($filePath) {
  2686. if (!file_exists($filePath)) {
  2687. Utils::throwError('20003:文件不存在');
  2688. }
  2689. try {
  2690. $parser = new PdfParser();
  2691. $pdf = $parser->parseFile($filePath);
  2692. $content = $pdf->getText();
  2693. return trim($content);
  2694. } catch (\Exception $e) {
  2695. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  2696. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  2697. }
  2698. }
  2699. /**
  2700. * 提取 Word 文件内容(支持 doc 和 docx)
  2701. */
  2702. private function extractWordContent($filePath) {
  2703. if (!file_exists($filePath)) {
  2704. Utils::throwError('20003:文件不存在');
  2705. }
  2706. try {
  2707. $phpWord = WordIOFactory::load($filePath);
  2708. $content = '';
  2709. foreach ($phpWord->getSections() as $section) {
  2710. foreach ($section->getElements() as $element) {
  2711. $content .= $this->extractWordElementText($element);
  2712. }
  2713. }
  2714. return trim($content);
  2715. } catch (\Exception $e) {
  2716. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  2717. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  2718. }
  2719. }
  2720. /**
  2721. * 递归提取 Word 元素中的文本
  2722. */
  2723. private function extractWordElementText($element) {
  2724. $text = '';
  2725. if (method_exists($element, 'getText')) {
  2726. $text .= $element->getText() . "\n";
  2727. } elseif (method_exists($element, 'getElements')) {
  2728. foreach ($element->getElements() as $childElement) {
  2729. $text .= $this->extractWordElementText($childElement);
  2730. }
  2731. }
  2732. return $text;
  2733. }
  2734. /**
  2735. * 提取图片内容(使用火山引擎 OCR)
  2736. */
  2737. private function extractImageContent($filePath) {
  2738. if (!file_exists($filePath)) {
  2739. Utils::throwError('20003:文件不存在');
  2740. }
  2741. try {
  2742. // 读取图片并转换为 base64
  2743. $imageData = file_get_contents($filePath);
  2744. $base64Image = base64_encode($imageData);
  2745. // 调用火山引擎 OCR 服务
  2746. $content = $this->callVolcEngineOCR($base64Image);
  2747. return trim($content);
  2748. } catch (\Exception $e) {
  2749. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  2750. Utils::throwError('20003:图片识别失败');
  2751. }
  2752. }
  2753. /**
  2754. * 调用火山引擎 OCR 服务识别图片文字
  2755. *
  2756. * @param string $base64Image base64 编码的图片数据
  2757. * @return string 识别的文字内容
  2758. */
  2759. private function callVolcEngineOCR($base64Image) {
  2760. $method = 'POST';
  2761. $service = 'cv';
  2762. $host = 'visual.volcengineapi.com';
  2763. $region = env('VOLC_REGION', 'cn-north-1');
  2764. $access_key = env('VOLC_AK');
  2765. $secret_key = env('VOLC_SK');
  2766. $action = 'OCRNormal';
  2767. $version = '2020-08-26';
  2768. if (!$access_key || !$secret_key) {
  2769. Utils::throwError('20003:请配置火山引擎 AK/SK');
  2770. }
  2771. // 请求体
  2772. $body = json_encode([
  2773. 'image_base64' => $base64Image
  2774. ]);
  2775. // 生成签名
  2776. $headers = $this->getVolcEngineSignHeaders(
  2777. $method, $service, $host, $region,
  2778. "Action={$action}&Version={$version}",
  2779. $access_key, $secret_key, $body
  2780. );
  2781. $client = new Client(['timeout' => 60, 'verify' => false]);
  2782. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  2783. 'headers' => $headers,
  2784. 'body' => $body
  2785. ]);
  2786. $response_arr = json_decode($response->getBody()->getContents(), true);
  2787. // 提取识别的文字
  2788. $textLines = [];
  2789. if (isset($response_arr['data']['line_texts'])) {
  2790. $textLines = $response_arr['data']['line_texts'];
  2791. } elseif (isset($response_arr['data']['ocr_infos'])) {
  2792. foreach ($response_arr['data']['ocr_infos'] as $info) {
  2793. if (isset($info['text'])) {
  2794. $textLines[] = $info['text'];
  2795. }
  2796. }
  2797. }
  2798. if (empty($textLines)) {
  2799. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  2800. return '';
  2801. }
  2802. return implode("\n", $textLines);
  2803. }
  2804. /**
  2805. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  2806. */
  2807. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  2808. $contentType = 'application/json';
  2809. $accept = 'application/json';
  2810. // 获取当前UTC时间
  2811. $t = new DateTime('now', new DateTimeZone('UTC'));
  2812. $xDate = $t->format('Ymd\THis\Z');
  2813. $dateStamp = $t->format('Ymd');
  2814. // 计算 body 的 sha256 哈希
  2815. $payloadHash = hash('sha256', $body);
  2816. // 1. 拼接规范请求串
  2817. $canonicalUri = '/';
  2818. $canonicalQueryString = $queryString;
  2819. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  2820. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  2821. $canonicalRequest = implode("\n", [
  2822. $method,
  2823. $canonicalUri,
  2824. $canonicalQueryString,
  2825. $canonicalHeaders,
  2826. $signedHeaders,
  2827. $payloadHash
  2828. ]);
  2829. // 2. 拼接待签名字符串
  2830. $algorithm = 'HMAC-SHA256';
  2831. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  2832. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  2833. $stringToSign = implode("\n", [
  2834. $algorithm,
  2835. $xDate,
  2836. $credentialScope,
  2837. $hashedCanonicalRequest
  2838. ]);
  2839. // 3. 计算签名
  2840. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  2841. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  2842. // 4. 添加签名到请求头
  2843. $authorizationHeader = sprintf(
  2844. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2845. $algorithm,
  2846. $access_key,
  2847. $credentialScope,
  2848. $signedHeaders,
  2849. $signature
  2850. );
  2851. return [
  2852. 'Accept' => $accept,
  2853. 'Content-Type' => $contentType,
  2854. 'Host' => $host,
  2855. 'X-Date' => $xDate,
  2856. 'X-Content-Sha256'=> $payloadHash,
  2857. 'Authorization' => $authorizationHeader
  2858. ];
  2859. }
  2860. public function generateScriptWords($cid, $model = 'r1') {
  2861. ini_set('max_execution_time', 0);
  2862. if (!$cid) Utils::throwError('20003: 请选择章节!');
  2863. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  2864. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2865. $messages = [
  2866. [
  2867. 'role' => 'system',
  2868. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  2869. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  2870. 2.非对话部分请全部用旁白角色代替
  2871. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  2872. ],
  2873. [
  2874. 'role' => 'user',
  2875. 'content' => $content
  2876. ]
  2877. ];
  2878. $post_data = [
  2879. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  2880. 'messages' => $messages,
  2881. 'max_tokens' => 8192,
  2882. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  2883. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  2884. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  2885. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  2886. 'response_format' => [
  2887. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  2888. ],
  2889. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  2890. ];
  2891. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2892. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2893. $response = $result->getBody()->getContents();
  2894. $response_arr = json_decode($response, true);
  2895. $update_data = [];
  2896. $content = '';
  2897. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2898. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2899. $update_data = [
  2900. 'role' => 'assistant',
  2901. 'content' => $response_arr['choices'][0]['message']['content'],
  2902. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  2903. ];
  2904. }
  2905. return $content;
  2906. }
  2907. /**
  2908. * 智能化解析集数信息
  2909. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  2910. *
  2911. * @param string $prompt 用户输入的提示词
  2912. * @return int|null 解析出的集数,如果没有找到则返回null
  2913. */
  2914. private function extractEpisodeNumber($prompt)
  2915. {
  2916. if (empty($prompt)) {
  2917. return null;
  2918. }
  2919. // 定义各种可能的表达模式
  2920. $patterns = [
  2921. // 基本模式:改成N集、调整成N集、修改成N集
  2922. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  2923. // 扩展模式:分成N集、拆分成N集、分割成N集
  2924. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  2925. // 数量模式:N集、共N集、总共N集
  2926. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  2927. // 制作模式:制作N集、生成N集、创建N集
  2928. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  2929. // 计划模式:计划N集、预计N集、打算N集
  2930. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  2931. // 需要模式:需要N集、要N集
  2932. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  2933. // 中文数字模式:改成三集、调整成五集等
  2934. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  2935. // 英文数字模式
  2936. '/(?: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',
  2937. ];
  2938. // 中文数字转阿拉伯数字的映射
  2939. $chineseNumbers = [
  2940. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  2941. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  2942. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  2943. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  2944. ];
  2945. // 逐个尝试匹配模式
  2946. foreach ($patterns as $pattern) {
  2947. if (preg_match($pattern, $prompt, $matches)) {
  2948. $number = trim($matches[1]);
  2949. // 如果是中文数字,转换为阿拉伯数字
  2950. if (isset($chineseNumbers[$number])) {
  2951. return $chineseNumbers[$number];
  2952. }
  2953. // 如果是阿拉伯数字,直接返回
  2954. if (is_numeric($number)) {
  2955. $episodeNum = intval($number);
  2956. // 合理性检查:集数应该在1-100之间
  2957. if ($episodeNum >= 1 && $episodeNum <= 100) {
  2958. return $episodeNum;
  2959. }
  2960. }
  2961. }
  2962. }
  2963. return null;
  2964. }
  2965. }