DeepSeekService.php 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543
  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 $test_content;
  23. private $headers;
  24. public function __construct() {
  25. $this->url = 'https://api.deepseek.com/chat/completions';
  26. $this->api_key = env('DEEPSEEK_API_KEY');
  27. $this->headers = [
  28. 'Authorization' => 'Bearer '.$this->api_key,
  29. 'Content-Type' => 'application/json; charset=UTF-8'
  30. ];
  31. $this->sys_message = [
  32. 'role' => 'system',
  33. 'content' => '你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  34. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  35. 2.<分集剧本>要求包含“分集序号”、“分集标题”以及分镜信息,分镜信息需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。\n\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. $this->test_content = <<<'EOD'
  114. ###剧本名:看不见的守护者
  115. ###故事梗概
  116. 少女许芸重生回到悲剧发生前一个月,她本是豪门假千金,上辈子被真千金徐清遥报复,被迫联姻后惨死。一个暗恋她至深的陌生男人程景,用与系统交易的代价换她重生,代价是她永远看不见他。许芸利用先知改变命运,躲避了表哥卞大伟的侵犯,并试图回归平凡生活。在危机四伏的重生路上,那个“看不见”的守护者程景一次次救她于危难。许芸从恐惧、好奇到依赖,并主动追寻这个神秘存在。两人在“一个看得见,一个看不见”的荒诞设定下,发展出一段跨越生死、充满拉扯与救赎的深情。最终,许芸的执着冲破了系统规则,两人得以相见相守,共度余生。
  117. ###剧本亮点
  118. 亮点1:重生设定与“隐形”守护者的双重奇幻
  119. 开篇即用快速剪辑展现许芸上辈子的惨死与陌生男人程景为她下葬、与系统交易的画面,建立强烈的戏剧冲突与悬念。重生后,许芸视角中程景的“不存在”与观众视角(或通过环境互动)能感知的“存在”形成奇妙反差,如被无形力量救下车、凭空出现的面条、地上的血脚印等,视觉呈现新颖,情感张力十足。
  120. 亮点2:“看见”与“看不见”的极致情感拉扯
  121. 许芸对着一团空气说话、试探、甚至调情的场景,充满了戏剧性的孤独与浪漫。她努力感知程景的存在,通过细微痕迹(如血迹、水渍、移动的物品)与他“交流”。这种单向可见的互动,将暗恋的卑微与守护的深情推到极致,观众能深切共情两人近在咫尺却无法触及的煎熬与甜蜜。
  122. 亮点3:悬疑推进与身份揭秘的层层递进
  123. 剧本并非单纯恋爱,穿插着许芸对抗原生家庭伤害、智斗恶毒表哥卞大伟的主线。程景的“隐形”能力成为她破局的关键外挂,但也带来了新的危险。随着许芸通过学校花名册、资助信等线索一步步接近程景的真实身份,悬疑感与情感共鸣同步加深,直到最终高潮的“相见”时刻,情感得到彻底释放。
  124. ###人物关系
  125. 许芸与程景:被守护者与隐形守护者,后成为恋人、夫妻。许芸从依赖、好奇到深爱并主动追寻程景;程景则因感恩与深爱,默默守护许芸两世。
  126. 许芸与徐家父母:亲生父母,关系疏离冷漠。母亲重男轻女,偏袒侄子卞大伟;父亲怯懦,后期在许芸影响下有所改变。
  127. 许芸与卞大伟:表哥,施暴者与主要反派,对许芸有侵犯意图,是前期主要威胁。
  128. 许芸与徐清遥:身份互换的真假千金,上辈子是仇敌,这辈子因许芸提前归位身份而关系未彻底恶化,但存在潜在矛盾。
  129. 许芸与夏颜:高中同桌兼闺蜜,后期因同时喜欢程景而产生嫉妒与隔阂,是推动程景“分手”谎言的工具人。
  130. ###核心矛盾
  131. 1. **生存矛盾**:重生后的许芸需躲避上辈子的悲剧命运(被卞大伟侵犯、被家庭出卖联姻),在恶劣原生环境中挣扎求生。
  132. 2. **感知矛盾**:系统规则导致许芸无法看见、听见程景,而程景深爱并守护着她。两人之间存在极致的“接触”渴望与“隔绝”现实的矛盾。
  133. 3. **情感矛盾**:许芸在依赖与追寻程景的过程中渐生情愫,但程景因自卑(身份差距)、身体创伤(以为不育)及系统限制,一度选择逃避和“分手”,造成两人的情感拉扯。
  134. 4. **身份矛盾**:真假千金的错位人生带来的家庭伦理与社会地位冲突,是许芸前世悲剧的根源,也是她今生需要面对和化解的阴影。
  135. ###主体列表
  136. 许芸-重生迷茫:刚重生时,心怀恐惧与决绝,试图改变命运。
  137. 许芸-坚韧求生:面对原生家庭压迫,冷静周旋,努力读书改变命运。
  138. 许芸-主动追寻:对“空气人”程景从好奇到依赖,再到大胆主动地试探与追求。
  139. 程景-隐形守护:始终在许芸身边,默默保护、照顾她,情感深沉而克制。
  140. 程景-隐忍挣扎:因系统限制和自身顾虑,承受着无法被感知的孤独与爱而不得的痛苦。
  141. 卞大伟-阴狠施暴:对许芸心怀不轨,是具象化的危险来源。
  142. 徐母-偏执刻薄:重男轻女,维护侄子,是家庭伤害的主要施加者。
  143. 徐父-怯懦转变:前期麻木,后期在女儿影响下逐渐觉醒。
  144. 夏颜-闺蜜变情敌:前期提供帮助,后期因嫉妒程景而说谎离间。
  145. “系统”:无形的规则设定,制造了主角间“看不见”的核心障碍。
  146. ###美术风格
  147. 基础画风风格词:写实细腻的现代都市情感风格,带有轻微悬疑色彩。
  148. 整体采用电影质感的写实风格,色彩随情绪和剧情变化。许芸重生前的回忆片段使用冷峻、压抑的蓝灰色调,对比强烈。重生后的现实生活,色调偏向自然光感,但徐家馄饨店等场景色调偏暗、拥挤,体现压抑感。当“隐形”的程景互动时,画面注重细节特写(如自动移动的物体、凹陷的床垫、凭空出现的水杯),并辅以微妙的光影变化或轻柔的焦点虚化来暗示他的“存在”。许芸与程景的独处时光,尤其是阁楼场景,色调转为温暖、柔和的橙黄色,营造私密与暧昧氛围。最终相见时刻,光线明亮饱满,色彩鲜活,象征隔阂的打破与希望降临。
  149. ###场景列表
  150. 徐家馄饨店:拥挤、老旧、充满烟火气的小店,是许芸重生后的主要生活场景,也是危机发生地。
  151. 学校教室/走廊:青春校园环境,是许芸努力学习、与夏颜交流的主要场景。
  152. 网吧包间:许芸躲避第一夜危机的地点,嘈杂、昏暗。
  153. 城市街道/路口:多次发生危机(车祸、被卞大伟堵截)和程景隐形救援的场景。
  154. 程景的阁楼:狭小但整洁,是两人的秘密基地和情感发酵的主要空间,充满生活气息与私密感。
  155. 医院:程景受伤后治疗的地点,也是许芸感到无助与寻找他的地方。
  156. 法院门口:卞大伟宣判后,徐母闹事、许芸再次感知到程景存在的场景。
  157. ###分集剧本
  158. ##分集01
  159. 分集名:重生与隐形救援
  160. 分镜01
  161. 场景描述:徐家馄饨店后院卧室,清晨,光线昏暗。许芸从噩梦中惊醒,额头上全是冷汗。
  162. 运镜:特写许芸惊恐睁大的双眼,快速闪回上辈子被家暴、惨死、以及一个模糊男人背影为她下葬的碎片画面。
  163. 出场角色:许芸
  164. 台词内容:
  165. 许芸(内心独白,带着颤音):我重生了…源于一个男人偏执的暗恋。
  166. 分镜02
  167. 场景描述:馄饨店前厅,清晨。徐母穿戴整齐,对正在收拾书包的许芸吩咐。卞大伟在锅炉后假装忙碌,眼神阴鸷地偷瞄许芸。
  168. 运镜:中景,先聚焦徐母严厉的脸,然后镜头平移,扫过乖巧点头的许芸,最后落在卞大伟身上,给他一个眼神特写。
  169. 出场角色:许芸,徐母,卞大伟
  170. 台词内容:
  171. 徐母:今天店就交给你表哥看着,晚上一放学就回来帮他干活。
  172. 许芸:(低头)嗯。
  173. 徐母:(转身离开)
  174. (许芸目光扫向卞大伟,内心独白):上辈子,就是他侮辱了徐清遥…也是我一切悲剧的开始。
  175. 分镜03
  176. 场景描述:网吧包间,夜。许芸坐在电脑前,屏幕光映着她苍白的脸。周围烟雾缭绕,嘈杂。
  177. 运镜:固定机位,侧面拍摄许芸蜷缩在椅子里的身影,环境音突出键盘声和隐约的游戏音效。
  178. 出场角色:许芸
  179. 台词内容:
  180. 许芸(内心独白):我在这里躲了一夜…可脑子里全是上辈子的事。徐清遥的恨,养父母的冷漠,那个老畜生的折磨…还有,那个给我收尸的陌生男人…
  181. 分镜04
  182. 场景描述:城市街道,清晨。许芸背着书包,困倦地过马路。一辆车急速驶来。
  183. 运镜:主观镜头,许芸视线模糊地看向冲来的车。紧接着第三视角,许芸的卫衣后领突然向后一紧,她整个人被“拽”离原地,车子擦身而过。
  184. 出场角色:许芸,路人老奶奶
  185. 台词内容:
  186. (急刹车声)
  187. 老奶奶:(拄着拐走近)这司机开车横冲直撞,要不是小姑娘你反应快…
  188. 许芸:(惊魂未定,四下张望)不是我自己躲的…
  189. (内心独白):是他!他就在我身边!
  190. 分镜05
  191. 场景描述:馄饨店后屋,白天。许芸刚进门,徐母拿着扫帚劈头盖脸打来。卞大伟在门口阴沉地看着。
  192. 运镜:手持晃动镜头,模拟挨打的混乱感。穿插卞大伟站在逆光门口的阴沉中景。
  193. 出场角色:许芸,徐母,卞大伟
  194. 台词内容:
  195. 徐母:死丫头!夜不归宿死哪儿去了?
  196. 许芸:(躲闪)去许家让清遥给我补课了!
  197. 徐母:(打累了,扔下扫帚)去包馄饨!
  198. (许芸沉默地洗手,开始包馄饨,余光警惕着卞大伟)
  199. ##分集02
  200. 分集名:危机再现与阁楼初夜
  201. 分镜01
  202. 场景描述:馄饨店后屋,傍晚。许芸放学推门进来,被埋伏的卞大伟一把抓住手腕。
  203. 运镜:快速推近,特写许芸惊愕的脸和卞大伟狞笑的手。镜头跟随挣扎的两人摇晃,撞倒桌椅。
  204. 出场角色:许芸,卞大伟
  205. 台词内容:
  206. 许芸:你干什么?放开我!
  207. 卞大伟:(喘着粗气)今天可没人救你了!
  208. (许芸挣扎中摸出兜里的小刀)
  209. 分镜02
  210. 场景描述:同上场景。卞大伟正要压倒许芸,突然怪叫着向后仰倒,仿佛被无形力量击中。
  211. 运镜:慢镜头,卞大伟身体不自然地扭曲、摔倒。许芸趁机爬起,震惊地看着“空气”。
  212. 出场角色:许芸,卞大伟
  213. 台词内容:
  214. 卞大伟:(对着空气怒吼)你他妈谁啊?!
  215. 许芸:(心口狂跳,看向卞大伟扭打的方向)是他…只能是他!
  216. 许芸:(朝“空气”大喊)我们走!
  217. 分镜03
  218. 场景描述:老旧居民楼楼梯,傍晚。许芸跟着一串突然出现在地上的“血脚印”奔跑。
  219. 运镜:俯拍镜头,跟随许芸上楼的脚步和地上断断续续的血脚印。
  220. 出场角色:许芸
  221. 台词内容:
  222. 许芸:(对着前方的空气)你受伤了!
  223. (血脚印停住)
  224. 许芸:(执拗地)我要跟你在一起。
  225. 分镜04
  226. 场景描述:狭小阁楼内,夜。许芸坐在床边,好奇地打量房间。小矮几上凭空出现两碗热气腾腾的面条。
  227. 运镜:全景展示阁楼布局,然后聚焦到矮几上“自动出现”的面碗。对面碗里的面条开始“自动”减少。
  228. 出场角色:许芸
  229. 台词内容:
  230. 许芸:(看着对面“自动”减少的面条,眼泪突然掉下来)啪嗒…好惨…这男的太惨了…
  231. 分镜05
  232. 场景描述:阁楼床上,夜。许芸穿着宽大T恤躺在床上。她突然睁开眼,感觉嘴唇上有温热柔软的触感。
  233. 运镜:特写许芸猛然睁大的眼睛,和微微湿润的嘴唇。背景是浴室隐约的水声。
  234. 出场角色:许芸
  235. 台词内容:
  236. 许芸:(内心惊愕)他在偷吻我?我…感觉到了?
  237. (她闭眼假装睡着,感觉脖颈又被亲了一下,忍不住轻颤)
  238. (浴室水声再次响起)
  239. 许芸:(嘴角微微勾起)好像…发现了系统的BUG?
  240. ##分集03
  241. 分集名:身份追寻与最终相见
  242. 分镜01
  243. 场景描述:学校教室,白天。许芸拿着重点班花名册,请同桌夏颜念名字。夏颜念到第一个名字时,许芸一脸茫然。
  244. 运镜:过肩镜头,从许芸视角看夏颜的嘴在动,但配以表示“无声”或“雪花噪音”的音效和画面扭曲效果。
  245. 出场角色:许芸,夏颜
  246. 台词内容:
  247. 夏颜:(念名单)…
  248. 许芸:(打断,急切地)夏夏,等高考后,你能帮我打听一下1号同学报哪所大学吗?我想跟他一起。
  249. 夏颜:(皱眉,嘴巴张合——许芸听不清)
  250. 许芸:(自顾自点头,眼冒星星)对,我喜欢1号同学!
  251. 分镜02
  252. 场景描述:法院外台阶,白天。卞大伟宣判后被带走,徐母发疯般冲过来要打许芸,被徐父拦住。许芸下台阶时,突然停下,嗅了嗅空气。
  253. 运镜:中景拍摄混乱场面,然后特写许芸突然愣住、微微抽动鼻翼的表情。
  254. 出场角色:许芸,徐母,徐父
  255. 台词内容:
  256. 徐母:(尖叫)许芸!你毁了我的一切!
  257. 许芸:(对徐父)爸,拉住她!(下台阶,脚步一顿)…皂角味?
  258. (内心独白):他来了?为什么…
  259. 分镜03
  260. 场景描述:程景家楼下小平台,傍晚。许芸站在平台边缘,下面是草坪。
  261. 运镜:全景,许芸孤身站在平台边,风吹动她的头发。然后切换为她主观视角,看向下方。
  262. 出场角色:许芸
  263. 台词内容:
  264. 许芸:(环顾四周,大声说)1号同学,没有你,我不想活了!
  265. (作势要跳)
  266. 分镜04
  267. 场景描述:同上场景。许芸身体前倾跌落的瞬间,被一股无形的力量拦腰抱住,然后轻轻“丢”在平台地面上。
  268. 运镜:高速摄影,捕捉许芸跌落瞬间被“空气”拦截并缓缓放下的超现实画面。
  269. 出场角色:许芸
  270. 台词内容:
  271. 许芸:(被抱住时惊喜)1号同学!我就知道…(被丢到地上,屁股疼)哎哟!
  272. 许芸:(爬起来,对着空气喊)你非要这么折磨我吗?还是你和夏颜在一起了?!
  273. 分镜05
  274. 场景描述:阁楼内,夜。许芸被浴室水声吵醒,迷迷糊糊走过去,赫然看见一个裸身男人(程景)在洗澡。
  275. 运镜:从许芸迷糊的主观镜头,到看清浴室景象时猛地拉近、定格在程景背影的震惊视角。
  276. 出场角色:许芸,程景
  277. 台词内容:
  278. 许芸:(惊吓后退)啊!你…你是谁?!
  279. (程景转身,两人对视)
  280. 程景:(震惊,试探)许芸?你能看见我?
  281. 许芸:(警惕)我当然能看见你!变-态!
  282. (程景扯掉浴巾,许芸惊呼转身又转回)
  283. 程景:(快速穿裤子)我就是你的1号同学。
  284. 分镜06
  285. 场景描述:阁楼内,片刻后。许芸接着夏颜的电话,程景站在一旁。接完电话,许芸走向程景。
  286. 运镜:双人镜头,许芸一边接电话,一边目光复杂地看着程景。挂电话后,她主动靠近,镜头柔和。
  287. 出场角色:许芸,程景
  288. 台词内容:
  289. 许芸:(对电话)…这挺好,可以毫无顾忌了。(挂电话,走向程景)
  290. 许芸:(圈住程景脖子)夏颜说,你受伤了,可能做不了爸爸?
  291. 程景:(眼神一暗)…嗯。
  292. 许芸:(微笑)没关系。我只想跟你好好地在一起。
  293. (两人相拥,窗外天色渐亮)
  294. EOD;
  295. }
  296. // 与推理模型对话
  297. public function chatWithReasoner($data) {
  298. $content = getProp($data, 'content');
  299. $model = getProp($data, 'model', 'r1');
  300. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  301. // 获取可选情感(根据音色可支持情感选)
  302. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  303. $emotion_list = [];
  304. foreach ($timbre_emotion as $emotion) {
  305. $tmp = explode(',', $emotion);
  306. $emotion_list = array_merge($emotion_list, $tmp);
  307. }
  308. $emotion_list = array_unique($emotion_list);
  309. $emotion_str = implode('、', $emotion_list);
  310. // // 获取可选情感
  311. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  312. // $emotion_str = implode('、', $emotion_list);
  313. // 是否启用情感
  314. $enable_emotion = getProp($data, 'enable_emotion', 0);
  315. if ($enable_emotion) {
  316. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  317. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  318. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  319. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  320. }else {
  321. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  322. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  323. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  324. }
  325. $messages = [
  326. [
  327. 'role' => 'system',
  328. 'content' => $sys_content
  329. ],
  330. [
  331. 'role' => 'user',
  332. 'content' => $content
  333. ]
  334. ];
  335. $post_data = [
  336. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  337. 'messages' => $messages,
  338. 'max_tokens' => 8192,
  339. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  340. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  341. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  342. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  343. 'response_format' => [
  344. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  345. ],
  346. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  347. ];
  348. $client = new Client(['timeout' => 1200, 'verify' => false]);
  349. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  350. $response = $result->getBody()->getContents();
  351. $response_arr = json_decode($response, true);
  352. $update_data = [];
  353. $content = '';
  354. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  355. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  356. $update_data = [
  357. 'role' => 'assistant',
  358. 'content' => $response_arr['choices'][0]['message']['content'],
  359. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  360. ];
  361. }
  362. // 处理获取到的剧本数据
  363. $script_content = handleScriptWords($content, $enable_emotion);
  364. $result = [
  365. 'origin_content' => $content,
  366. 'roles' => getProp($script_content, 'roles'),
  367. 'words' => getProp($script_content, 'words'),
  368. ];
  369. return $result;
  370. }
  371. public function resetParagraphAudio($data) {
  372. $bid = getProp($data, 'bid');
  373. $cid = getProp($data, 'cid');
  374. $version_id = getProp($data, 'version_id');
  375. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  376. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  377. 'generate_status' => '待制作',
  378. 'updated_at' => date('Y-m-d H:i:s')
  379. ]);
  380. }
  381. public function saveParagraphAudio($data) {
  382. $bid = getProp($data, 'bid');
  383. $cid = getProp($data, 'cid');
  384. $version_id = getProp($data, 'version_id');
  385. $sequence = getProp($data, 'sequence');
  386. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  387. // 获取所有情感
  388. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  389. $emotion_list = array_flip($emotion_list);
  390. // 获取音色支持情感
  391. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  392. $timbre_emotion = explode(',', $timbre_emotion);
  393. $emotion = getProp($data, 'emotion');
  394. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  395. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  396. $list = [
  397. 'bid' => $bid,
  398. 'cid' => $cid,
  399. 'version_id' => $version_id,
  400. 'sequence' => $sequence,
  401. 'role' => getProp($data, 'role'),
  402. 'gender' => getProp($data, 'gender'),
  403. 'text' => trim(getProp($data, 'text')),
  404. 'emotion' => $emotion,
  405. 'emotion_type' => $emotion_type,
  406. 'voice_type' => getProp($data, 'voice_type'),
  407. 'voice_name' => getProp($data, 'voice_name'),
  408. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  409. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  410. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  411. 'pitch' => getProp($data, 'pitch', 0),
  412. // 'paragraph_audio_url' => '',
  413. 'generate_status' => '制作中',
  414. 'error_msg' => '',
  415. 'updated_at' => date('Y-m-d H:i:s')
  416. ];
  417. $continue = false;
  418. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  419. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  420. $list['generate_status'] = '制作成功';
  421. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  422. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  423. $continue = true;
  424. }
  425. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  426. if ($id) {
  427. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  428. }else {
  429. $list['created_at'] = date('Y-m-d H:i:s');
  430. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  431. $boolen = $id ? true : false;
  432. }
  433. // 如果更新成功则加入查询队列
  434. if ($boolen) {
  435. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  436. Redis::sadd($redis_key, $id);
  437. }
  438. if ($boolen && !$continue) {
  439. $boolen = false;
  440. $client = new Client(['timeout' => 300, 'verify' => false]);
  441. // 根据ID通过API通知合成音频
  442. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  443. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  444. $response = $result->getBody()->getContents();
  445. $response_arr = json_decode($response, true);
  446. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  447. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  448. Log::info('通知火山生成段落音频失败: '.$error_msg);
  449. Utils::throwError('20003:通知火山生成段落音频失败');
  450. }
  451. $boolen = true;
  452. }
  453. return $boolen;
  454. }
  455. public function insertAudioEffect($data) {
  456. $audio_id = getProp($data, 'audio_id');
  457. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  458. $bid = getProp($chapter_audio, 'bid');
  459. $version_id = getProp($chapter_audio, 'version_id');
  460. $cid = getProp($chapter_audio, 'cid');
  461. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  462. $audio_effect_json = getProp($data, 'audio_effect_json');
  463. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  464. try {
  465. DB::beginTransaction();
  466. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  467. if (!$count) {
  468. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  469. }else {
  470. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  471. }
  472. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  473. 'audio_effect_status' => '添加中',
  474. 'audio_effect_json' => $audio_effect_json,
  475. 'updated_at' => date('Y-m-d H:i:s')
  476. ]);
  477. if (!$boolen1) {
  478. DB::rollBack();
  479. Utils::throwError('20003:更新生成数据失败');
  480. }
  481. $id = DB::table('mp_audio_tasks')->insertGetId([
  482. 'audio_id' => $audio_id,
  483. 'generate_status' => '执行中',
  484. 'generate_json' => json_encode([], 256),
  485. 'bid' => $bid,
  486. 'book_name' => getProp($chapter_audio, 'book_name'),
  487. 'version_id' => $version_id,
  488. 'version_name' => getProp($chapter_audio, 'version_name'),
  489. 'cid' => $cid,
  490. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  491. 'task_name' => $task_name,
  492. 'created_at' => date('Y-m-d H:i:s'),
  493. 'updated_at' => date('Y-m-d H:i:s')
  494. ]);
  495. if (!$id) {
  496. DB::rollBack();
  497. Utils::throwError('20003:创建任务失败');
  498. }
  499. }catch (\Exception $e) {
  500. DB::rollBack();
  501. Utils::throwError('20003:'.$e->getMessage());
  502. }
  503. DB::commit();
  504. $client = new Client(['timeout' => 300, 'verify' => false]);
  505. // 根据ID通过API通知合成音频
  506. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  507. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  508. $response = $result->getBody()->getContents();
  509. $response_arr = json_decode($response, true);
  510. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  511. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  512. Log::info('通知火山插入音效失败: '.$error_msg);
  513. Utils::throwError('20003:通知火山插入音效失败');
  514. }
  515. return true;
  516. }
  517. public function insertBgm($data) {
  518. $audio_id = getProp($data, 'audio_id');
  519. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  520. $bid = getProp($chapter_audio, 'bid');
  521. $version_id = getProp($chapter_audio, 'version_id');
  522. $cid = getProp($chapter_audio, 'cid');
  523. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  524. $bgm_json = getProp($data, 'bgm_json');
  525. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  526. if (!$bgm_json) {
  527. $bgm_json = getProp($data, 'audio_effect_json');
  528. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  529. }
  530. try {
  531. DB::beginTransaction();
  532. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  533. if (!$count) {
  534. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  535. }else {
  536. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  537. }
  538. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  539. 'bgm_status' => '添加中',
  540. 'bgm_json' => $bgm_json,
  541. 'updated_at' => date('Y-m-d H:i:s')
  542. ]);
  543. if (!$boolen1) {
  544. DB::rollBack();
  545. Utils::throwError('20003:更新生成数据失败');
  546. }
  547. $id = DB::table('mp_audio_tasks')->insertGetId([
  548. 'audio_id' => $audio_id,
  549. 'generate_status' => '执行中',
  550. 'generate_json' => json_encode([], 256),
  551. 'bid' => $bid,
  552. 'book_name' => getProp($chapter_audio, 'book_name'),
  553. 'version_id' => $version_id,
  554. 'version_name' => getProp($chapter_audio, 'version_name'),
  555. 'cid' => $cid,
  556. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  557. 'task_name' => $task_name,
  558. 'created_at' => date('Y-m-d H:i:s'),
  559. 'updated_at' => date('Y-m-d H:i:s')
  560. ]);
  561. if (!$id) {
  562. DB::rollBack();
  563. Utils::throwError('20003:创建任务失败');
  564. }
  565. }catch (\Exception $e) {
  566. DB::rollBack();
  567. Utils::throwError('20003:'.$e->getMessage());
  568. }
  569. DB::commit();
  570. $client = new Client(['timeout' => 300, 'verify' => false]);
  571. // 根据ID通过API通知合成音频
  572. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  573. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  574. $response = $result->getBody()->getContents();
  575. $response_arr = json_decode($response, true);
  576. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  577. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  578. Log::info('通知火山插入bgm失败: '.$error_msg);
  579. Utils::throwError('20003:通知火山插入bgm失败');
  580. }
  581. return true;
  582. }
  583. public function getParagraphAudios($data) {
  584. $bid = getProp($data, 'bid');
  585. $cid = getProp($data, 'cid');
  586. $version_id = getProp($data, 'version_id');
  587. $sequence = getProp($data, 'sequence');
  588. // 获取已生成的音频
  589. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  590. if ($sequence) $query->where('sequence', $sequence);
  591. $paragraph_audios = $query->orderBy('sequence')->get();
  592. $result = [];
  593. foreach($paragraph_audios as $item) {
  594. $result[] = [
  595. 'sequence' => getProp($item, 'sequence'),
  596. 'role' => getProp($item, 'role'),
  597. 'gender' => getProp($item, 'gender'),
  598. 'text' => trim(getProp($item, 'text')),
  599. 'emotion' => getProp($item, 'emotion'),
  600. 'emotion_type' => getProp($item, 'emotion_type'),
  601. 'voice_type' => getProp($item, 'voice_type'),
  602. 'voice_name' => getProp($item, 'voice_name'),
  603. 'speed_ratio' => getProp($item, 'speed_ratio'),
  604. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  605. 'emotion_scale' => getProp($item, 'emotion_scale'),
  606. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  607. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  608. ];
  609. }
  610. return $result;
  611. }
  612. // 新增合成任务
  613. public function addGenerateTask($data) {
  614. $bid = getProp($data, 'bid');
  615. $cid = getProp($data, 'cid');
  616. $version_id = getProp($data, 'version_id');
  617. $generate_json = getProp($data, 'generate_json');
  618. // 获取已生成的音频
  619. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  620. $paragraph_list = [];
  621. foreach($paragraph_audios as $item) {
  622. $paragraph_list[getProp($item, 'sequence')] = [
  623. 'role' => getProp($item, 'role'),
  624. 'gender' => getProp($item, 'gender'),
  625. 'text' => trim(getProp($item, 'text')),
  626. 'emotion' => getProp($item, 'emotion'),
  627. 'emotion_type' => getProp($item, 'emotion_type'),
  628. 'voice_type' => getProp($item, 'voice_type'),
  629. 'voice_name' => getProp($item, 'voice_name'),
  630. 'speed_ratio' => getProp($item, 'speed_ratio'),
  631. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  632. 'emotion_scale' => getProp($item, 'emotion_scale'),
  633. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  634. ];
  635. }
  636. // 更新角色-音色信息
  637. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  638. $existed_role_info = json_decode($existed_role_info, true);
  639. if (!$existed_role_info) $existed_role_info = [];
  640. // 获取情感信息
  641. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  642. $emotion_list = array_flip($emotion_list);
  643. // 获取音色对应情感组
  644. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  645. $timbre_emotion_list = [];
  646. foreach($timbre_emotions as $item) {
  647. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  648. }
  649. // 构造生成音频的json
  650. $words = json_decode($generate_json, true);
  651. // 最终合成前的参数组
  652. $mp_chapter_paragraph_audios = [];
  653. $sequence = 1;
  654. $complete_paragraph_sequences = [];
  655. foreach($words as &$word) {
  656. 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:参数格式有误');
  657. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  658. $role = getProp($word, 'role');
  659. $word['gender'] = (int)$word['gender'];
  660. // 判断音色对应情感是否支持,不支持则调整为中性
  661. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  662. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  663. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  664. if (isset($emotion_list[getProp($word, 'emotion')])) {
  665. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  666. }else {
  667. $word['emotion'] = '中性';
  668. $word['emotion_type'] = 'neutral';
  669. }
  670. $existed_role_info[$role] = [
  671. 'timbre_type' => $word['voice_type'],
  672. 'timbre_name' => $word['voice_name'],
  673. 'emotion' => $word['emotion'],
  674. 'emotion_type' => $word['emotion_type'],
  675. 'speed_ratio' => $word['speed_ratio'],
  676. 'loudness_ratio'=> $word['loudness_ratio'],
  677. 'emotion_scale' => $word['emotion_scale'],
  678. 'pitch' => $word['pitch']
  679. ];
  680. $word['paragraph_audio_url'] = '';
  681. // 判断生成参数是否相同,相同则直接使用已生成的音频
  682. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  683. // 如果音频存在并且参数都未改变则使用已生成的音频
  684. if (getProp($paragraph, 'paragraph_audio_url')) {
  685. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  686. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  687. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  688. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  689. // {
  690. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  691. // }
  692. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  693. }
  694. $tmp = $word;
  695. // 组装章节分句音频数据
  696. // $tmp['sequence'] = getProp($word, 'sequence');
  697. // $tmp['text'] = getProp($word, 'text');
  698. // $tmp['emotion'] = getProp($word, 'emotion');
  699. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  700. // $tmp['voice_name'] = getProp($word, 'voice_name');
  701. // $tmp['voice_type'] = getProp($word, 'voice_type');
  702. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  703. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  704. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  705. $tmp['bid'] = $bid;
  706. $tmp['version_id'] = $version_id;
  707. $tmp['cid'] = $cid;
  708. $tmp['sequence'] = $sequence;
  709. $tmp['created_at'] = date('Y-m-d H:i:s');
  710. $tmp['updated_at'] = date('Y-m-d H:i:s');
  711. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  712. $mp_chapter_paragraph_audios[] = $tmp;
  713. $complete_paragraph_sequences[] = $sequence;
  714. $sequence++;
  715. }
  716. $generate_json = json_encode($words, 256);
  717. // 判断是否有未生成字幕的段落
  718. $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();
  719. if ($no_subtitle_sequences) {
  720. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  721. }
  722. try {
  723. DB::beginTransaction();
  724. $role_info = json_encode($existed_role_info, 256);
  725. $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')]);
  726. if (!$boolen) {
  727. DB::rollBack();
  728. Utils::throwError('20003:更新角色信息失败');
  729. }
  730. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  731. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  732. if (!$count) {
  733. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  734. }else {
  735. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  736. }
  737. $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')]);
  738. if (!$boolen1) {
  739. DB::rollBack();
  740. Utils::throwError('20003:更新生成数据失败');
  741. }
  742. $id = DB::table('mp_audio_tasks')->insertGetId([
  743. 'audio_id' => getProp($chapter_audio, 'id'),
  744. 'generate_status' => '执行中',
  745. 'generate_json' => $generate_json,
  746. 'bid' => $bid,
  747. 'book_name' => getProp($chapter_audio, 'book_name'),
  748. 'version_id' => $version_id,
  749. 'version_name' => getProp($chapter_audio, 'version_name'),
  750. 'cid' => $cid,
  751. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  752. 'task_name' => $task_name,
  753. 'created_at' => date('Y-m-d H:i:s'),
  754. 'updated_at' => date('Y-m-d H:i:s')
  755. ]);
  756. if (!$id) {
  757. DB::rollBack();
  758. Utils::throwError('20003:创建任务失败');
  759. }
  760. // 删除不在段落序号范围内的其他数据
  761. if ($complete_paragraph_sequences) {
  762. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  763. }
  764. // // 删除章节分句音频数据并重新插入
  765. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  766. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  767. // if (!$boolen3) {
  768. // DB::rollBack();
  769. // Utils::throwError('20003:更新章节分句音频失败');
  770. // }
  771. } catch (\Exception $e) {
  772. DB::rollBack();
  773. Utils::throwError('20003:'.$e->getMessage());
  774. }
  775. DB::commit();
  776. // 通知火山生成音频
  777. $client = new Client(['timeout' => 300, 'verify' => false]);
  778. // 根据ID通过API通知合成音频
  779. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  780. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  781. $response = $result->getBody()->getContents();
  782. $response_arr = json_decode($response, true);
  783. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  784. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  785. Log::info('通知火山生成音频失败: '.$error_msg);
  786. Utils::throwError('20003:通知火山生成音频失败');
  787. }
  788. return true;
  789. }
  790. public function timbreList($data) {
  791. $gender = getProp($data, 'gender');
  792. $timbre_name = getProp($data, 'voice_name');
  793. $category_id = getProp($data, 'category_id');
  794. $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');
  795. if ($gender) {
  796. $query->where('gender', $gender);
  797. }
  798. if ($timbre_name) {
  799. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  800. }
  801. if ($category_id) {
  802. $query->where(function ($query) use ($category_id) {
  803. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  804. });
  805. }
  806. $list = $query->get()->map(function ($value) {
  807. $value = (array)$value;
  808. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  809. return $value;
  810. })->toArray();
  811. return $list;
  812. }
  813. // 生成火山临时token
  814. public function setStsToken() {
  815. // ************* 配置参数 *************
  816. $method = 'GET';
  817. $service = 'sts';
  818. $host = 'open.volcengineapi.com';
  819. $region = env('VOLC_REGION');
  820. $endpoint = 'https://open.volcengineapi.com';
  821. // $endpoint = 'https://tos-cn-beijing.volces.com';
  822. $access_key = env('VOLC_AK');
  823. $secret_key = env('VOLC_SK');
  824. // 获取缓存中的token,如果没有则请求接口
  825. $token = Redis::get('volc_sts_token');
  826. if (!$token) {
  827. // 查询参数
  828. $query_parameters = [
  829. 'Action' => 'AssumeRole',
  830. 'RoleSessionName' => 'user@zw',
  831. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  832. 'Version' => '2018-01-01'
  833. ];
  834. // 生成URL编码的查询字符串
  835. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  836. // 获取签名头信息
  837. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  838. // 构建完整URL
  839. $request_url = $endpoint . '?' . $request_parameters;
  840. $client = new Client(['verify' => false]);
  841. $response = $client->get($request_url, ['headers' => $headers]);
  842. $response_arr = json_decode($response->getBody()->getContents(), true);
  843. $result = [
  844. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  845. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  846. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  847. 'Region' => env('VOLC_REGION'),
  848. 'Endpoint' => env('VOLC_END_POINT'),
  849. 'Bucket' => env('VOLC_BUCKET'),
  850. ];
  851. // 缓存token
  852. Redis::setex('volc_sts_token', 3000, json_encode($result));
  853. return $result;
  854. } else {
  855. return json_decode($token, true);
  856. }
  857. // $response = $response['Response'];
  858. // $access_key = $response['Credentials']['AccessKeyId'];
  859. // $secret_key = $response['Credentials']['AccessKeySecret'];
  860. // $security_token = $response['Credentials']['SecurityToken'];
  861. // $expiration = $response['Credentials']['Expiration'];
  862. // dd($response_arr);
  863. }
  864. public function emotionGroups($data) {
  865. $id = getProp($data, 'group_id');
  866. $group_name = getProp($data, 'group_name');
  867. $voice_type = getProp($data, 'voice_type');
  868. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  869. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  870. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  871. if ($group_name) {
  872. $query->where('group_name', 'like', "%{$group_name}%");
  873. }
  874. if ($id) {
  875. $query->where('id', $id);
  876. }
  877. if ($voice_type) {
  878. $query->where('voice_type', $voice_type);
  879. }
  880. return $query->orderBy('id')->get()->map(function ($value) {
  881. return (array)$value;
  882. })->toArray();
  883. }
  884. private function sign($key, $msg) {
  885. return hash_hmac('sha256', $msg, $key, true);
  886. }
  887. // 生成签名密钥
  888. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  889. $kDate = $this->sign($key, $dateStamp);
  890. $kRegion = $this->sign($kDate, $regionName);
  891. $kService = $this->sign($kRegion, $serviceName);
  892. $kSigning = $this->sign($kService, 'request');
  893. return $kSigning;
  894. }
  895. // 获取签名头信息
  896. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  897. $contenttype = 'application/x-www-form-urlencoded';
  898. $accept = 'application/json';
  899. // 获取当前UTC时间
  900. $t = new DateTime('now', new DateTimeZone('UTC'));
  901. $xdate = $t->format('Ymd\THis\Z');
  902. $datestamp = $t->format('Ymd');
  903. // 1. 拼接规范请求串
  904. $canonical_uri = '/';
  905. $canonical_querystring = $request_parameters;
  906. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  907. $signed_headers = 'content-type;host;x-date';
  908. // 空请求体的SHA256哈希
  909. $payload_hash = hash('sha256', '');
  910. $canonical_request = implode("\n", [
  911. $method,
  912. $canonical_uri,
  913. $canonical_querystring,
  914. $canonical_headers,
  915. $signed_headers,
  916. $payload_hash
  917. ]);
  918. // 2. 拼接待签名字符串
  919. $algorithm = 'HMAC-SHA256';
  920. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  921. $hashed_canonical_request = hash('sha256', $canonical_request);
  922. $string_to_sign = implode("\n", [
  923. $algorithm,
  924. $xdate,
  925. $credential_scope,
  926. $hashed_canonical_request
  927. ]);
  928. // 3. 计算签名
  929. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  930. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  931. // 4. 添加签名到请求头
  932. $authorization_header = sprintf(
  933. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  934. $algorithm,
  935. $access_key,
  936. $credential_scope,
  937. $signed_headers,
  938. $signature
  939. );
  940. return [
  941. 'Accept' => $accept,
  942. 'Content-Type' => $contenttype,
  943. 'X-Date' => $xdate,
  944. 'Authorization' => $authorization_header
  945. ];
  946. }
  947. // 文字合成语音(火山引擎)
  948. public function tts($data) {
  949. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  950. $headers = [
  951. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  952. 'Content-Type' => 'application/json; charset=UTF-8'
  953. ];
  954. $post_data = [
  955. 'app' => [
  956. 'appid' => env('VOLC_APPID'),
  957. 'token' => env('VOLC_TOKEN'),
  958. 'cluster' => 'volcano_tts'
  959. ],
  960. 'user' => [
  961. 'uid' => 'mp_audio'
  962. ],
  963. // 'audio' => [
  964. // 'voice_type' =>
  965. // ],
  966. ];
  967. }
  968. public function scriptList($data) {
  969. $script_id = getProp($data, 'script_id');
  970. $script_name = getProp($data, 'script_name');
  971. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  972. if ($script_id) {
  973. $query->where('id', $script_id);
  974. }
  975. if ($script_name) {
  976. $query->where('script_name', 'like', "%{$script_name}%");
  977. }
  978. return $query->orderBy('created_at', 'desc')->paginate(12);
  979. }
  980. public function scriptInfo($data) {
  981. $script_id = getProp($data, 'script_id');
  982. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  983. ->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();
  984. if (!$script) Utils::throwError('20003:该剧本不存在!');
  985. $script = (array)$script;
  986. $script['roles'] = json_decode($script['roles']);
  987. $script['scenes'] = json_decode($script['scenes']);
  988. // 获取分集信息
  989. $episodes = DB::table('mp_script_episodes')->where('script_id', $script_id)->orderBy('episode_number')
  990. ->select('id', 'episode_number', 'title', 'content', 'segment_number', 'segment_content')
  991. ->orderBy('episode_number')->orderBy('segment_number')->get()->map(function ($value) {
  992. return (array)$value;
  993. })->toArray();
  994. $return_episodes = [];
  995. foreach($episodes as $episode) {
  996. $episode_number = getProp($episode, 'episode_number');
  997. if (isset($return_episodes[$episode_number])) {
  998. $return_episodes[$episode_number]['segments'][] = [
  999. 'segment_number' => getProp($episode, 'segment_number'),
  1000. 'segment_content' => getProp($episode, 'segment_content')
  1001. ];
  1002. }else {
  1003. $return_episodes[$episode_number] = [
  1004. 'episode_number' => $episode_number,
  1005. 'title' => getProp($episode, 'title'),
  1006. 'segments' => [
  1007. [
  1008. 'segment_number' => getProp($episode, 'segment_number'),
  1009. 'segment_content' => getProp($episode, 'segment_content')
  1010. ]
  1011. ]
  1012. ];
  1013. }
  1014. }
  1015. $script['episodes'] = array_values($return_episodes);
  1016. return $script;
  1017. }
  1018. public function createScript($data) {
  1019. $script_name = getProp($data, 'script_name');
  1020. $uid = Site::getUid(); // 获取当前用户ID
  1021. if (!$script_name) Utils::throwError('20001:剧本名称不能为空');
  1022. return DB::table('mp_scripts')->insertGetId([
  1023. 'script_name' => $script_name,
  1024. 'user_id' => $uid,
  1025. 'created_at' => date('Y-m-d H:i:s'),
  1026. 'updated_at' => date('Y-m-d H:i:s')
  1027. ]);
  1028. }
  1029. /**
  1030. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1031. *
  1032. * @param array $data 包含以下参数:
  1033. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1034. * - question: 用户问题(可选)
  1035. * - model: 使用的模型(r1 或 v3,默认 v3)
  1036. * @return \Generator 返回生成器,用于流式输出
  1037. */
  1038. public function chatWithFileStream($data) {
  1039. $script_id = getProp($data, 'script_id');
  1040. $file = getProp($data, 'file');
  1041. $content = getProp($data, 'content', '');
  1042. $bid = getProp($data, 'bid', 0);
  1043. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1044. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1045. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1046. $model = getProp($data, 'model', 'v3');
  1047. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1048. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1049. if (!$script) {
  1050. Utils::throwError('20003:剧本不存在');
  1051. }
  1052. if (!$file && !$content && !$bid) {
  1053. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1054. }
  1055. // 提取文件内容
  1056. if ($content) {
  1057. $content = filterContent($content);
  1058. } elseif ($file) {
  1059. $content = $this->extractFileContent($file);
  1060. if (!$content) {
  1061. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1062. }
  1063. } elseif ($bid) {
  1064. $content = $this->getContentByBid($bid);
  1065. if (!$content) {
  1066. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1067. }
  1068. } else {
  1069. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1070. }
  1071. // 构建消息
  1072. $messages = [
  1073. $this->sys_message,
  1074. [
  1075. 'role' => 'user',
  1076. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1077. ]
  1078. ];
  1079. $post_data = [
  1080. 'model' => $model,
  1081. 'messages' => $messages,
  1082. 'max_tokens' => 8192,
  1083. 'temperature' => 0.7,
  1084. 'frequency_penalty' => 0,
  1085. 'presence_penalty' => 0,
  1086. 'response_format' => ['type' => 'text'],
  1087. 'stream' => true // 启用流式输出
  1088. ];
  1089. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1090. $response = $client->post($this->url, [
  1091. 'json' => $post_data,
  1092. 'headers' => $this->headers,
  1093. 'stream' => true // 启用流式响应
  1094. ]);
  1095. $body = $response->getBody();
  1096. $fullContent = '';
  1097. $fullReasoningContent = '';
  1098. $usage = [];
  1099. $buffer = '';
  1100. Log::info('开始读取 DeepSeek 流式响应');
  1101. // 逐行读取流式响应
  1102. while (!$body->eof()) {
  1103. $chunk = $body->read(1024); // 每次读取 1KB
  1104. $buffer .= $chunk;
  1105. // 按行分割
  1106. $lines = explode("\n", $buffer);
  1107. // 保留最后一个不完整的行
  1108. $buffer = array_pop($lines);
  1109. foreach ($lines as $line) {
  1110. $line = trim($line);
  1111. // 跳过空行
  1112. if (empty($line)) {
  1113. continue;
  1114. }
  1115. // Log::info('收到原始行数据', ['line' => $line]);
  1116. // 检查是否是 SSE 数据行
  1117. if (strpos($line, 'data: ') !== 0) {
  1118. Log::warning('非 SSE 数据行', ['line' => $line]);
  1119. continue;
  1120. }
  1121. $data = substr($line, 6); // 移除 "data: " 前缀
  1122. if ($data === '[DONE]') {
  1123. Log::info('收到结束标记');
  1124. break 2; // 跳出两层循环
  1125. }
  1126. try {
  1127. $json = json_decode($data, true);
  1128. if (json_last_error() !== JSON_ERROR_NONE) {
  1129. Log::warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1130. continue;
  1131. }
  1132. // Log::info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1133. if (isset($json['choices'][0]['delta'])) {
  1134. $delta = $json['choices'][0]['delta'];
  1135. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1136. // 注释掉以下内容则不返回d思维链内容
  1137. if (isset($delta['reasoning_content'])) {
  1138. $fullReasoningContent .= $delta['reasoning_content'];
  1139. // Log::info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1140. yield [
  1141. 'type' => 'reasoning',
  1142. 'content' => $delta['reasoning_content'],
  1143. 'full_reasoning' => $fullReasoningContent
  1144. ];
  1145. }
  1146. // 处理最终回答内容
  1147. if (isset($delta['content'])) {
  1148. $fullContent .= $delta['content'];
  1149. // Log::info('输出回答内容', ['length' => strlen($delta['content'])]);
  1150. yield [
  1151. 'type' => 'content',
  1152. 'content' => $delta['content'],
  1153. 'full_content' => $fullContent
  1154. ];
  1155. }
  1156. }
  1157. // 获取使用统计信息
  1158. if (isset($json['usage'])) {
  1159. $usage = $json['usage'];
  1160. Log::info('收到使用统计', ['usage' => $usage]);
  1161. }
  1162. } catch (\Exception $e) {
  1163. Log::error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1164. continue;
  1165. }
  1166. }
  1167. }
  1168. Log::info('流式读取完成', [
  1169. 'content_length' => strlen($fullContent),
  1170. 'reasoning_length' => strlen($fullReasoningContent)
  1171. ]);
  1172. // 处理完整内容并返回最终结果
  1173. $script_arr = [];
  1174. if ($fullContent) {
  1175. $script_arr = handleScriptContent($fullContent);
  1176. }
  1177. yield [
  1178. 'type' => 'done',
  1179. 'script' => $script_arr,
  1180. 'answer' => $fullContent,
  1181. 'reasoning' => $fullReasoningContent,
  1182. 'usage' => $usage
  1183. ];
  1184. }
  1185. /**
  1186. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1187. *
  1188. * @param array $data 包含以下参数:
  1189. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1190. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1191. * - model: 使用的模型(r1 或 v3,默认 v3)
  1192. * @return array
  1193. */
  1194. public function chatWithFile($data) {
  1195. // dd(handleScriptContent(''));
  1196. $script_id = getProp($data, 'script_id');
  1197. $file = getProp($data, 'file');
  1198. $content = getProp($data, 'content', '');
  1199. $bid = getProp($data, 'bid', 0);
  1200. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1201. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1202. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1203. $model = getProp($data, 'model', 'v3');
  1204. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1205. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1206. if (!$script) {
  1207. Utils::throwError('20003:剧本不存在');
  1208. }
  1209. if (!$file && !$content && !$bid) {
  1210. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1211. }
  1212. // 提取文件内容
  1213. if ($content) {
  1214. $content = filterContent($content);
  1215. } elseif ($file) {
  1216. $content = $this->extractFileContent($file);
  1217. if (!$content) {
  1218. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1219. }
  1220. } elseif ($bid) {
  1221. $content = $this->getContentByBid($bid);
  1222. if (!$content) {
  1223. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1224. }
  1225. } else {
  1226. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1227. }
  1228. // 构建消息
  1229. $messages = [
  1230. $this->sys_message,
  1231. [
  1232. 'role' => 'user',
  1233. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1234. ]
  1235. ];
  1236. $post_data = [
  1237. 'model' => $model,
  1238. 'messages' => $messages,
  1239. 'max_tokens' => 8192,
  1240. 'temperature' => 0.7,
  1241. 'frequency_penalty' => 0,
  1242. 'presence_penalty' => 0,
  1243. 'response_format' => ['type' => 'text'],
  1244. 'stream' => false
  1245. ];
  1246. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1247. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  1248. $response = $result->getBody()->getContents();
  1249. $response_arr = json_decode($response, true);
  1250. $content = '';
  1251. $usage = [];
  1252. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  1253. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  1254. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  1255. }
  1256. // \Log::info('返回值内容: '.$content);
  1257. $script_arr = [];
  1258. // 处理结果
  1259. if ($content) {
  1260. $script_arr = handleScriptContent($content);
  1261. }
  1262. return [
  1263. 'script' => $script_arr,
  1264. 'answer' => $content,
  1265. 'usage' => $usage
  1266. ];
  1267. }
  1268. public function saveScript($data) {
  1269. $script_arr =getProp($data, 'script', []);
  1270. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1271. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1272. $script_id = getProp($data, 'script_id');
  1273. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1274. try {
  1275. DB::beginTransaction();
  1276. $update_data = [
  1277. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1278. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1279. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1280. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1281. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1282. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1283. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1284. 'status' => 3,
  1285. 'start_episode_sequence' => $start_episode_sequence,
  1286. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1287. 'episode_num' => count($script_arr['episodes']),
  1288. 'updated_at' => date('Y-m-d H:i:s')
  1289. ];
  1290. // 保存剧本内容
  1291. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1292. if (!$boolen) {
  1293. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1294. Utils::throwError('20003:剧本内容保存失败');
  1295. }
  1296. // 保存分集内容
  1297. // 删除历史分集内容
  1298. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1299. $episodes = [];
  1300. $sequence = 1;
  1301. foreach ($script_arr['episodes'] as $episode) {
  1302. $segment_number = 1;
  1303. foreach($episode['segments'] as $segment) {
  1304. $episodes[] = [
  1305. 'script_id' => $script_id,
  1306. 'episode_number' => $episode['episode_number'],
  1307. 'title' => $episode['title'],
  1308. // 'content' => $episode['content'],
  1309. 'content' => '',
  1310. 'segment_number' => $segment_number,
  1311. 'segment_content' => $segment['segment_content'],
  1312. 'sequence' => $sequence,
  1313. 'created_at' => date('Y-m-d H:i:s'),
  1314. 'updated_at' => date('Y-m-d H:i:s')
  1315. ];
  1316. $sequence++;
  1317. $segment_number++;
  1318. }
  1319. }
  1320. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1321. if (!$boolen2) {
  1322. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1323. Utils::throwError('20003:分集内容保存失败');
  1324. }
  1325. } catch (\Exception $e) {
  1326. DB::rollBack();
  1327. Utils::throwError('20003:'.$e->getMessage());
  1328. }
  1329. DB::commit();
  1330. return true;
  1331. }
  1332. public function exportScript($data) {
  1333. $script = $this->scriptInfo($data);
  1334. $export_type = getProp($data, 'export_type', 'txt');
  1335. // 生成文件名
  1336. $filename = $script['script_name'] . '_' . date('YmdHis');
  1337. // 根据导出类型生成不同格式的文件
  1338. switch ($export_type) {
  1339. case 'txt':
  1340. return $this->exportScriptAsTxt($script, $filename);
  1341. case 'pdf':
  1342. return $this->exportScriptAsPdf($script, $filename);
  1343. default:
  1344. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  1345. }
  1346. }
  1347. /**
  1348. * 导出剧本为TXT格式
  1349. */
  1350. private function exportScriptAsTxt($script, $filename) {
  1351. // 构建TXT内容
  1352. $content = $this->buildScriptContent($script);
  1353. // 设置响应头,直接下载
  1354. header('Content-Type: text/plain; charset=utf-8');
  1355. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  1356. header('Content-Length: ' . strlen($content));
  1357. // 输出内容并结束
  1358. echo $content;
  1359. exit();
  1360. }
  1361. /**
  1362. * 导出剧本为PDF格式
  1363. */
  1364. private function exportScriptAsPdf($script, $filename) {
  1365. // 使用HTML转PDF的方式来更好地支持中文
  1366. $htmlContent = $this->buildScriptHtmlForPdf($script);
  1367. // 创建PDF实例
  1368. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1369. // 设置文档信息
  1370. $pdf->SetCreator('剧本导出系统');
  1371. $pdf->SetAuthor('系统');
  1372. $pdf->SetTitle($script['script_name']);
  1373. $pdf->SetSubject('剧本导出');
  1374. // 设置边距
  1375. $pdf->SetMargins(15, 15, 15);
  1376. $pdf->SetAutoPageBreak(TRUE, 15);
  1377. // 添加页面
  1378. $pdf->AddPage();
  1379. // 注册并使用 simsun.ttf 字体
  1380. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  1381. // 使用HTML内容生成PDF
  1382. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  1383. // 直接输出PDF文件供下载
  1384. header('Content-Type: application/pdf');
  1385. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  1386. // 直接输出PDF内容
  1387. $pdf->Output($filename . '.pdf', 'D');
  1388. exit();
  1389. }
  1390. /**
  1391. * 构建用于PDF的HTML内容
  1392. */
  1393. private function buildScriptHtmlForPdf($script) {
  1394. $html = '<style>
  1395. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  1396. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  1397. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  1398. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  1399. .info { margin-bottom: 8px; }
  1400. .episode { margin-bottom: 20px; page-break-inside: avoid; }
  1401. .segment { margin-bottom: 10px; margin-left: 20px; }
  1402. </style>';
  1403. // 标题
  1404. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  1405. // 剧本简介
  1406. if (!empty($script['intro'])) {
  1407. $html .= '<h2>剧本简介</h2>';
  1408. $html .= '<p>' . nl2br(htmlspecialchars($script['intro'])) . '</p>';
  1409. }
  1410. // 亮点
  1411. if (!empty($script['highlights'])) {
  1412. $html .= '<h2>亮点</h2>';
  1413. $html .= '<p>' . nl2br(htmlspecialchars($script['highlights'])) . '</p>';
  1414. }
  1415. // 核心矛盾
  1416. if (!empty($script['core_contradiction'])) {
  1417. $html .= '<h2>核心矛盾</h2>';
  1418. $html .= '<p>' . nl2br(htmlspecialchars($script['core_contradiction'])) . '</p>';
  1419. }
  1420. // 艺术风格
  1421. if (!empty($script['art_style'])) {
  1422. $html .= '<h2>艺术风格</h2>';
  1423. $html .= '<p>' . nl2br(htmlspecialchars($script['art_style'])) . '</p>';
  1424. }
  1425. // 角色列表
  1426. if (!empty($script['roles']) && is_array($script['roles'])) {
  1427. $html .= '<h2>角色列表</h2>';
  1428. $html .= '<ul>';
  1429. foreach ($script['roles'] as $role) {
  1430. if (is_array($role) || is_object($role)) {
  1431. $html .= '<li>' . htmlspecialchars(getProp($role, 'role', '')) . ':' . htmlspecialchars(getProp($role, 'description', '')) . '</li>';
  1432. } else {
  1433. $html .= '<li>' . htmlspecialchars($role) . '</li>';
  1434. }
  1435. }
  1436. $html .= '</ul>';
  1437. }
  1438. // 角色关系
  1439. if (!empty($script['role_relationship'])) {
  1440. $html .= '<h2>角色关系</h2>';
  1441. $html .= '<p>' . nl2br(htmlspecialchars($script['role_relationship'])) . '</p>';
  1442. }
  1443. // 场景列表
  1444. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1445. $html .= '<h2>场景列表</h2>';
  1446. $html .= '<ul>';
  1447. foreach ($script['scenes'] as $scene) {
  1448. if (is_array($scene) || is_object($scene)) {
  1449. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene', '')) . ':' . htmlspecialchars(getProp($scene, 'description', '')) . '</li>';
  1450. } else {
  1451. $html .= '<li>' . htmlspecialchars($scene) . '</li>';
  1452. }
  1453. }
  1454. $html .= '</ul>';
  1455. }
  1456. // 分集内容
  1457. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1458. $html .= '<h2>分集内容</h2>';
  1459. foreach ($script['episodes'] as $episode) {
  1460. $html .= '<div class="episode">';
  1461. $html .= '<h3>第' . htmlspecialchars($episode['episode_number']) . '集';
  1462. if (!empty($episode['title'])) {
  1463. $html .= ':' . htmlspecialchars($episode['title']);
  1464. }
  1465. $html .= '</h3>';
  1466. // 处理分段内容
  1467. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1468. foreach ($episode['segments'] as $segment) {
  1469. if (!empty($segment['segment_content'])) {
  1470. $html .= '<div class="segment">';
  1471. if (!empty($segment['segment_number'])) {
  1472. $html .= '<strong>第' . htmlspecialchars($segment['segment_number']) . '段</strong><br>';
  1473. }
  1474. $html .= nl2br(htmlspecialchars($segment['segment_content']));
  1475. $html .= '</div>';
  1476. }
  1477. }
  1478. }
  1479. $html .= '</div>';
  1480. }
  1481. }
  1482. return $html;
  1483. }
  1484. /**
  1485. * 构建PDF内容
  1486. */
  1487. private function buildPdfContent($pdf, $script) {
  1488. // 标题
  1489. $pdf->SetFont('dejavusans', 'B', 18);
  1490. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  1491. $pdf->Ln(5);
  1492. // 基本信息
  1493. $pdf->SetFont('dejavusans', '', 12);
  1494. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  1495. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  1496. $pdf->Ln(5);
  1497. // 剧本简介
  1498. if (!empty($script['intro'])) {
  1499. $pdf->SetFont('dejavusans', 'B', 14);
  1500. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  1501. $pdf->SetFont('dejavusans', '', 12);
  1502. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  1503. $pdf->Ln(3);
  1504. }
  1505. // 亮点
  1506. if (!empty($script['highlights'])) {
  1507. $pdf->SetFont('dejavusans', 'B', 14);
  1508. $pdf->Cell(0, 10, '亮点', 0, 1);
  1509. $pdf->SetFont('dejavusans', '', 12);
  1510. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  1511. $pdf->Ln(3);
  1512. }
  1513. // 核心矛盾
  1514. if (!empty($script['core_contradiction'])) {
  1515. $pdf->SetFont('dejavusans', 'B', 14);
  1516. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  1517. $pdf->SetFont('dejavusans', '', 12);
  1518. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  1519. $pdf->Ln(3);
  1520. }
  1521. // 艺术风格
  1522. if (!empty($script['art_style'])) {
  1523. $pdf->SetFont('dejavusans', 'B', 14);
  1524. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  1525. $pdf->SetFont('dejavusans', '', 12);
  1526. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  1527. $pdf->Ln(3);
  1528. }
  1529. // 备注
  1530. if (!empty($script['remark'])) {
  1531. $pdf->SetFont('dejavusans', 'B', 14);
  1532. $pdf->Cell(0, 10, '备注', 0, 1);
  1533. $pdf->SetFont('dejavusans', '', 12);
  1534. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  1535. $pdf->Ln(3);
  1536. }
  1537. // 角色列表
  1538. if (!empty($script['roles']) && is_array($script['roles'])) {
  1539. $pdf->SetFont('dejavusans', 'B', 14);
  1540. $pdf->Cell(0, 10, '角色列表', 0, 1);
  1541. $pdf->SetFont('dejavusans', '', 12);
  1542. foreach ($script['roles'] as $index => $role) {
  1543. if (is_array($role) || is_object($role)) {
  1544. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  1545. } else {
  1546. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  1547. }
  1548. }
  1549. $pdf->Ln(3);
  1550. }
  1551. // 角色关系
  1552. if (!empty($script['role_relationship'])) {
  1553. $pdf->SetFont('dejavusans', 'B', 14);
  1554. $pdf->Cell(0, 10, '角色关系', 0, 1);
  1555. $pdf->SetFont('dejavusans', '', 12);
  1556. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  1557. $pdf->Ln(3);
  1558. }
  1559. // 场景列表
  1560. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1561. $pdf->SetFont('dejavusans', 'B', 14);
  1562. $pdf->Cell(0, 10, '场景列表', 0, 1);
  1563. $pdf->SetFont('dejavusans', '', 12);
  1564. foreach ($script['scenes'] as $index => $scene) {
  1565. if (is_array($scene) || is_object($scene)) {
  1566. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  1567. } else {
  1568. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  1569. }
  1570. }
  1571. $pdf->Ln(5);
  1572. }
  1573. // 分集内容
  1574. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1575. $pdf->SetFont('dejavusans', 'B', 16);
  1576. $pdf->Cell(0, 12, '分集内容', 0, 1);
  1577. $pdf->Ln(3);
  1578. foreach ($script['episodes'] as $episode) {
  1579. // 检查是否需要新页面
  1580. if ($pdf->GetY() > 250) {
  1581. $pdf->AddPage();
  1582. }
  1583. $pdf->SetFont('dejavusans', 'B', 14);
  1584. $episodeTitle = '第' . $episode['episode_number'] . '集';
  1585. if (!empty($episode['title'])) {
  1586. $episodeTitle .= ':' . $episode['title'];
  1587. }
  1588. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  1589. // 处理分段内容
  1590. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1591. $pdf->SetFont('dejavusans', '', 12);
  1592. foreach ($episode['segments'] as $segment) {
  1593. if (!empty($segment['segment_content'])) {
  1594. // 如果有分段编号,显示分段标题
  1595. if (!empty($segment['segment_number'])) {
  1596. $pdf->SetFont('dejavusans', 'B', 12);
  1597. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  1598. $pdf->SetFont('dejavusans', '', 12);
  1599. }
  1600. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  1601. $pdf->Ln(2);
  1602. }
  1603. }
  1604. }
  1605. $pdf->Ln(5);
  1606. }
  1607. }
  1608. }
  1609. /**
  1610. * 构建剧本文本内容
  1611. */
  1612. private function buildScriptContent($script) {
  1613. $content = '';
  1614. // 剧本基本信息
  1615. if (!empty($script['intro'])) {
  1616. $content .= "###故事梗概\n" . $script['intro'] . "\n\n";
  1617. }
  1618. if (!empty($script['highlights'])) {
  1619. $content .= "###剧本亮点\n" . $script['highlights'] . "\n\n";
  1620. }
  1621. if (!empty($script['role_relationship'])) {
  1622. $content .= "###人物关系\n" . $script['role_relationship'] . "\n\n";
  1623. }
  1624. if (!empty($script['core_contradiction'])) {
  1625. $content .= "###核心矛盾\n" . $script['core_contradiction'] . "\n\n";
  1626. }
  1627. if (!empty($script['roles']) && is_array($script['roles'])) {
  1628. $content .= "###主体列表\n";
  1629. foreach ($script['roles'] as $role) {
  1630. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  1631. }
  1632. $content .= "\n\n";
  1633. }
  1634. if (!empty($script['art_style'])) {
  1635. $content .= "###美术风格\n" . $script['art_style'] . "\n\n";
  1636. }
  1637. // 场景信息
  1638. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  1639. $content .= "###场景列表\n";
  1640. foreach ($script['scenes'] as $scene) {
  1641. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  1642. }
  1643. $content .= "\n\n";
  1644. }
  1645. // 分集内容
  1646. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  1647. $content .= "###分集剧本\n";
  1648. foreach ($script['episodes'] as $episode) {
  1649. $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  1650. if (!empty($episode['title'])) {
  1651. $content .= ":" . $episode['title'];
  1652. }
  1653. $content .= "\n";
  1654. // 处理分镜
  1655. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  1656. foreach ($episode['segments'] as $segment) {
  1657. $content .= "分镜" . $episode['episode_number'] . '-' . $segment['segment_number'] . "\n";
  1658. $content .= $segment['segment_content'] . "\n\n";
  1659. }
  1660. }
  1661. }
  1662. }
  1663. return $content;
  1664. }
  1665. /**
  1666. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1667. *
  1668. * @param array $data 包含以下参数:
  1669. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1670. * - question: 用户问题(可选)
  1671. * - model: 使用的模型(r1 或 v3,默认 v3)
  1672. * @return \Generator 返回生成器,用于流式输出
  1673. */
  1674. public function addChat($data) {
  1675. $uid = Site::getUid();
  1676. $file = getProp($data, 'file');
  1677. $content = getProp($data, 'content', '');
  1678. $bid = getProp($data, 'bid', 0);
  1679. $question = getProp($data, 'question', "请根据实例完成一个剧本分析,要求: 1.从第1集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。");
  1680. $model = getProp($data, 'model', 'v3');
  1681. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1682. if (!$file && !$content && !$bid) {
  1683. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1684. }
  1685. // 提取文件内容
  1686. if ($content) {
  1687. $content = filterContent($content);
  1688. } elseif ($file) {
  1689. $content = $this->extractFileContent($file);
  1690. if (!$content) {
  1691. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1692. }
  1693. } elseif ($bid) {
  1694. $content = $this->getContentByBid($bid);
  1695. if (!$content) {
  1696. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1697. }
  1698. } else {
  1699. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1700. }
  1701. // 构建消息
  1702. $messages = [
  1703. $this->sys_message,
  1704. [
  1705. 'role' => 'user',
  1706. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1707. ]
  1708. ];
  1709. $post_data = [
  1710. 'model' => $model,
  1711. 'messages' => $messages,
  1712. 'max_tokens' => 8192,
  1713. 'temperature' => 0.7,
  1714. 'frequency_penalty' => 0,
  1715. 'presence_penalty' => 0,
  1716. 'response_format' => ['type' => 'text'],
  1717. 'stream' => true // 启用流式输出
  1718. ];
  1719. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1720. $response = $client->post($this->url, [
  1721. 'json' => $post_data,
  1722. 'headers' => $this->headers,
  1723. 'stream' => true // 启用流式响应
  1724. ]);
  1725. $body = $response->getBody();
  1726. $fullContent = '';
  1727. $fullReasoningContent = '';
  1728. $usage = [];
  1729. $buffer = '';
  1730. Log::info('开始读取 DeepSeek 流式响应');
  1731. // 逐行读取流式响应
  1732. while (!$body->eof()) {
  1733. $chunk = $body->read(1024); // 每次读取 1KB
  1734. $buffer .= $chunk;
  1735. // 按行分割
  1736. $lines = explode("\n", $buffer);
  1737. // 保留最后一个不完整的行
  1738. $buffer = array_pop($lines);
  1739. foreach ($lines as $line) {
  1740. $line = trim($line);
  1741. // 跳过空行
  1742. if (empty($line)) {
  1743. continue;
  1744. }
  1745. // Log::info('收到原始行数据', ['line' => $line]);
  1746. // 检查是否是 SSE 数据行
  1747. if (strpos($line, 'data: ') !== 0) {
  1748. Log::warning('非 SSE 数据行', ['line' => $line]);
  1749. continue;
  1750. }
  1751. $data = substr($line, 6); // 移除 "data: " 前缀
  1752. if ($data === '[DONE]') {
  1753. Log::info('收到结束标记');
  1754. break 2; // 跳出两层循环
  1755. }
  1756. try {
  1757. $json = json_decode($data, true);
  1758. if (json_last_error() !== JSON_ERROR_NONE) {
  1759. Log::warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1760. continue;
  1761. }
  1762. // Log::info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1763. if (isset($json['choices'][0]['delta'])) {
  1764. $delta = $json['choices'][0]['delta'];
  1765. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1766. // 注释掉以下内容则不返回d思维链内容
  1767. if (isset($delta['reasoning_content'])) {
  1768. $fullReasoningContent .= $delta['reasoning_content'];
  1769. // Log::info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1770. yield [
  1771. 'type' => 'reasoning',
  1772. 'content' => $delta['reasoning_content'],
  1773. 'full_reasoning' => $fullReasoningContent
  1774. ];
  1775. }
  1776. // 处理最终回答内容
  1777. if (isset($delta['content'])) {
  1778. $fullContent .= $delta['content'];
  1779. // Log::info('输出回答内容', ['length' => strlen($delta['content'])]);
  1780. yield [
  1781. 'type' => 'content',
  1782. 'content' => $delta['content'],
  1783. 'full_content' => $fullContent
  1784. ];
  1785. }
  1786. }
  1787. // 获取使用统计信息
  1788. if (isset($json['usage'])) {
  1789. $usage = $json['usage'];
  1790. Log::info('收到使用统计', ['usage' => $usage]);
  1791. }
  1792. } catch (\Exception $e) {
  1793. Log::error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1794. continue;
  1795. }
  1796. }
  1797. }
  1798. Log::info('流式读取完成', [
  1799. 'content_length' => strlen($fullContent),
  1800. 'reasoning_length' => strlen($fullReasoningContent)
  1801. ]);
  1802. $fullContent = $this->test_content;
  1803. // $fullReasoningContent = [];
  1804. // $usage = [];
  1805. // $uid = 0;
  1806. // $content = '';
  1807. // $question = '';
  1808. // $anime_id = 10;
  1809. // 处理完整内容并返回最终结果
  1810. $script_arr = [];
  1811. if ($fullContent) {
  1812. $script_arr = handleScriptContent($fullContent);
  1813. }
  1814. // 新建动漫
  1815. $anime_name = getProp($script_arr, 'script_name');
  1816. if (!$anime_name) {
  1817. yield [
  1818. 'type' => 'done',
  1819. 'answer' => $fullContent,
  1820. 'reasoning' => $fullReasoningContent,
  1821. 'usage' => $usage,
  1822. 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  1823. ];
  1824. }
  1825. // 确认对话名称唯一性
  1826. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  1827. $anime_name = $anime_name . '_' . date('YmdHis');
  1828. }
  1829. $table_data = [
  1830. 'user_id' => $uid,
  1831. 'anime_name' => $anime_name,
  1832. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1833. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1834. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1835. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1836. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1837. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1838. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1839. 'status' => '解析完成',
  1840. 'start_episode_sequence' => 1,
  1841. 'end_episode_sequence' => count($script_arr['episodes']),
  1842. 'episode_num' => count($script_arr['episodes']),
  1843. 'created_at' => date('Y-m-d H:i:s'),
  1844. 'updated_at' => date('Y-m-d H:i:s')
  1845. ];
  1846. try {
  1847. DB::beginTransaction();
  1848. // 新建动漫大纲
  1849. $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  1850. if (!$anime_id) {
  1851. dLog('deepseek')->info('对话保存失败', $table_data);
  1852. Utils::throwError('20003:对话保存失败');
  1853. }
  1854. // 新建动漫剧集
  1855. // 删除历史分集内容
  1856. $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  1857. $episodes = [];
  1858. $sequence = 1;
  1859. foreach ($script_arr['episodes'] as $episode) {
  1860. $segment_number = 1;
  1861. foreach($episode['segments'] as $segment) {
  1862. $episodes[] = [
  1863. 'anime_id' => $anime_id,
  1864. 'episode_number' => $episode['episode_number'],
  1865. 'title' => $episode['title'],
  1866. // 'content' => $episode['content'],
  1867. 'content' => '',
  1868. 'segment_number' => $segment_number,
  1869. 'segment_content' => $segment['segment_content'],
  1870. 'sequence' => $sequence,
  1871. 'created_at' => date('Y-m-d H:i:s'),
  1872. 'updated_at' => date('Y-m-d H:i:s')
  1873. ];
  1874. $sequence++;
  1875. $segment_number++;
  1876. }
  1877. }
  1878. $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  1879. if (!$boolen2) {
  1880. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1881. Utils::throwError('20003:分集内容保存失败');
  1882. }
  1883. // 保存对话记录
  1884. $recrods = [
  1885. [
  1886. 'uid' => $uid,
  1887. 'anime_id' => $anime_id,
  1888. 'role' => 'user',
  1889. 'content' => "以下是文档内容:\n\n{$content}
  1890. \n\n用户问题:{$question}",
  1891. 'created_at' => date('Y-m-d H:i:s'),
  1892. 'updated_at' => date('Y-m-d H:i:s')
  1893. ],
  1894. [
  1895. 'uid' => $uid,
  1896. 'anime_id' => $anime_id,
  1897. 'role' => 'assistant',
  1898. 'content' => $fullContent,
  1899. 'created_at' => date('Y-m-d H:i:s'),
  1900. 'updated_at' => date('Y-m-d H:i:s')
  1901. ]
  1902. ];
  1903. // 保存对话记录
  1904. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  1905. if (!$boolen3) {
  1906. Utils::throwError('20003:对话记录保存失败');
  1907. }
  1908. }catch (\Exception $e) {
  1909. DB::rollBack();
  1910. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  1911. yield [
  1912. 'type' => 'done',
  1913. 'answer' => $fullContent,
  1914. 'reasoning' => $fullReasoningContent,
  1915. 'usage' => $usage,
  1916. 'error' => $e->getMessage(),
  1917. ];
  1918. }
  1919. // DB::commit();
  1920. $table_data['anime_id'] = $anime_id;
  1921. $table_data['roles'] = json_decode($table_data['roles'], true);
  1922. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  1923. $table_data['episodes'] = $script_arr['episodes'];
  1924. unset($table_data['created_at']);
  1925. unset($table_data['updated_at']);
  1926. unset($table_data['status']);
  1927. yield [
  1928. 'type' => 'done',
  1929. 'script' => $table_data,
  1930. 'answer' => $fullContent,
  1931. 'reasoning' => $fullReasoningContent,
  1932. 'usage' => $usage
  1933. ];
  1934. }
  1935. public function getContentByBid($bid) {
  1936. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  1937. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  1938. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  1939. $content = '';
  1940. foreach ($chapters as $chapter) {
  1941. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  1942. }
  1943. return $content;
  1944. }
  1945. /**
  1946. * 根据文件类型提取文本内容
  1947. *
  1948. * @param mixed $file 文件对象或文件路径
  1949. * @return string
  1950. */
  1951. public function extractFileContent($file) {
  1952. // 获取文件路径和扩展名
  1953. if (is_string($file)) {
  1954. $filePath = $file;
  1955. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  1956. } else {
  1957. // Laravel UploadedFile 对象
  1958. $filePath = $file->getRealPath();
  1959. $extension = strtolower($file->getClientOriginalExtension());
  1960. }
  1961. $content = '';
  1962. switch ($extension) {
  1963. case 'txt':
  1964. $content = $this->extractTxtContent($filePath);
  1965. break;
  1966. case 'pdf':
  1967. $content = $this->extractPdfContent($filePath);
  1968. break;
  1969. case 'doc':
  1970. case 'docx':
  1971. $content = $this->extractWordContent($filePath);
  1972. break;
  1973. // case 'jpg':
  1974. // case 'jpeg':
  1975. // case 'png':
  1976. // case 'gif':
  1977. // case 'bmp':
  1978. // case 'webp':
  1979. // $content = $this->extractImageContent($filePath);
  1980. // break;
  1981. default:
  1982. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  1983. }
  1984. return $content;
  1985. }
  1986. /**
  1987. * 提取 TXT 文件内容
  1988. */
  1989. private function extractTxtContent($filePath) {
  1990. if (!file_exists($filePath)) {
  1991. Utils::throwError('20003:文件不存在');
  1992. }
  1993. $content = file_get_contents($filePath);
  1994. // 尝试检测并转换编码
  1995. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  1996. if ($encoding && $encoding !== 'UTF-8') {
  1997. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  1998. }
  1999. return trim($content);
  2000. }
  2001. /**
  2002. * 提取 PDF 文件内容
  2003. */
  2004. private function extractPdfContent($filePath) {
  2005. if (!file_exists($filePath)) {
  2006. Utils::throwError('20003:文件不存在');
  2007. }
  2008. try {
  2009. $parser = new PdfParser();
  2010. $pdf = $parser->parseFile($filePath);
  2011. $content = $pdf->getText();
  2012. return trim($content);
  2013. } catch (\Exception $e) {
  2014. Log::error('PDF解析失败: ' . $e->getMessage());
  2015. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  2016. }
  2017. }
  2018. /**
  2019. * 提取 Word 文件内容(支持 doc 和 docx)
  2020. */
  2021. private function extractWordContent($filePath) {
  2022. if (!file_exists($filePath)) {
  2023. Utils::throwError('20003:文件不存在');
  2024. }
  2025. try {
  2026. $phpWord = WordIOFactory::load($filePath);
  2027. $content = '';
  2028. foreach ($phpWord->getSections() as $section) {
  2029. foreach ($section->getElements() as $element) {
  2030. $content .= $this->extractWordElementText($element);
  2031. }
  2032. }
  2033. return trim($content);
  2034. } catch (\Exception $e) {
  2035. Log::error('Word解析失败: ' . $e->getMessage());
  2036. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  2037. }
  2038. }
  2039. /**
  2040. * 递归提取 Word 元素中的文本
  2041. */
  2042. private function extractWordElementText($element) {
  2043. $text = '';
  2044. if (method_exists($element, 'getText')) {
  2045. $text .= $element->getText() . "\n";
  2046. } elseif (method_exists($element, 'getElements')) {
  2047. foreach ($element->getElements() as $childElement) {
  2048. $text .= $this->extractWordElementText($childElement);
  2049. }
  2050. }
  2051. return $text;
  2052. }
  2053. /**
  2054. * 提取图片内容(使用火山引擎 OCR)
  2055. */
  2056. private function extractImageContent($filePath) {
  2057. if (!file_exists($filePath)) {
  2058. Utils::throwError('20003:文件不存在');
  2059. }
  2060. try {
  2061. // 读取图片并转换为 base64
  2062. $imageData = file_get_contents($filePath);
  2063. $base64Image = base64_encode($imageData);
  2064. // 调用火山引擎 OCR 服务
  2065. $content = $this->callVolcEngineOCR($base64Image);
  2066. return trim($content);
  2067. } catch (\Exception $e) {
  2068. Log::error('图片OCR识别失败: ' . $e->getMessage());
  2069. Utils::throwError('20003:图片识别失败');
  2070. }
  2071. }
  2072. /**
  2073. * 调用火山引擎 OCR 服务识别图片文字
  2074. *
  2075. * @param string $base64Image base64 编码的图片数据
  2076. * @return string 识别的文字内容
  2077. */
  2078. private function callVolcEngineOCR($base64Image) {
  2079. $method = 'POST';
  2080. $service = 'cv';
  2081. $host = 'visual.volcengineapi.com';
  2082. $region = env('VOLC_REGION', 'cn-north-1');
  2083. $access_key = env('VOLC_AK');
  2084. $secret_key = env('VOLC_SK');
  2085. $action = 'OCRNormal';
  2086. $version = '2020-08-26';
  2087. if (!$access_key || !$secret_key) {
  2088. Utils::throwError('20003:请配置火山引擎 AK/SK');
  2089. }
  2090. // 请求体
  2091. $body = json_encode([
  2092. 'image_base64' => $base64Image
  2093. ]);
  2094. // 生成签名
  2095. $headers = $this->getVolcEngineSignHeaders(
  2096. $method, $service, $host, $region,
  2097. "Action={$action}&Version={$version}",
  2098. $access_key, $secret_key, $body
  2099. );
  2100. $client = new Client(['timeout' => 60, 'verify' => false]);
  2101. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  2102. 'headers' => $headers,
  2103. 'body' => $body
  2104. ]);
  2105. $response_arr = json_decode($response->getBody()->getContents(), true);
  2106. // 提取识别的文字
  2107. $textLines = [];
  2108. if (isset($response_arr['data']['line_texts'])) {
  2109. $textLines = $response_arr['data']['line_texts'];
  2110. } elseif (isset($response_arr['data']['ocr_infos'])) {
  2111. foreach ($response_arr['data']['ocr_infos'] as $info) {
  2112. if (isset($info['text'])) {
  2113. $textLines[] = $info['text'];
  2114. }
  2115. }
  2116. }
  2117. if (empty($textLines)) {
  2118. Log::warning('OCR识别结果为空', ['response' => $response_arr]);
  2119. return '';
  2120. }
  2121. return implode("\n", $textLines);
  2122. }
  2123. /**
  2124. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  2125. */
  2126. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  2127. $contentType = 'application/json';
  2128. $accept = 'application/json';
  2129. // 获取当前UTC时间
  2130. $t = new DateTime('now', new DateTimeZone('UTC'));
  2131. $xDate = $t->format('Ymd\THis\Z');
  2132. $dateStamp = $t->format('Ymd');
  2133. // 计算 body 的 sha256 哈希
  2134. $payloadHash = hash('sha256', $body);
  2135. // 1. 拼接规范请求串
  2136. $canonicalUri = '/';
  2137. $canonicalQueryString = $queryString;
  2138. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  2139. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  2140. $canonicalRequest = implode("\n", [
  2141. $method,
  2142. $canonicalUri,
  2143. $canonicalQueryString,
  2144. $canonicalHeaders,
  2145. $signedHeaders,
  2146. $payloadHash
  2147. ]);
  2148. // 2. 拼接待签名字符串
  2149. $algorithm = 'HMAC-SHA256';
  2150. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  2151. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  2152. $stringToSign = implode("\n", [
  2153. $algorithm,
  2154. $xDate,
  2155. $credentialScope,
  2156. $hashedCanonicalRequest
  2157. ]);
  2158. // 3. 计算签名
  2159. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  2160. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  2161. // 4. 添加签名到请求头
  2162. $authorizationHeader = sprintf(
  2163. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2164. $algorithm,
  2165. $access_key,
  2166. $credentialScope,
  2167. $signedHeaders,
  2168. $signature
  2169. );
  2170. return [
  2171. 'Accept' => $accept,
  2172. 'Content-Type' => $contentType,
  2173. 'Host' => $host,
  2174. 'X-Date' => $xDate,
  2175. 'X-Content-Sha256'=> $payloadHash,
  2176. 'Authorization' => $authorizationHeader
  2177. ];
  2178. }
  2179. public function generateScriptWords($cid, $model = 'r1') {
  2180. ini_set('max_execution_time', 0);
  2181. if (!$cid) Utils::throwError('20003: 请选择章节!');
  2182. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  2183. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2184. $messages = [
  2185. [
  2186. 'role' => 'system',
  2187. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  2188. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  2189. 2.非对话部分请全部用旁白角色代替
  2190. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  2191. ],
  2192. [
  2193. 'role' => 'user',
  2194. 'content' => $content
  2195. ]
  2196. ];
  2197. $post_data = [
  2198. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  2199. 'messages' => $messages,
  2200. 'max_tokens' => 8192,
  2201. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  2202. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  2203. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  2204. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  2205. 'response_format' => [
  2206. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  2207. ],
  2208. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  2209. ];
  2210. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2211. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2212. $response = $result->getBody()->getContents();
  2213. $response_arr = json_decode($response, true);
  2214. $update_data = [];
  2215. $content = '';
  2216. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2217. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2218. $update_data = [
  2219. 'role' => 'assistant',
  2220. 'content' => $response_arr['choices'][0]['message']['content'],
  2221. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  2222. ];
  2223. }
  2224. return $content;
  2225. }
  2226. }