DeepSeekService.php 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548
  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', "请根据实例格式完成剧本大纲");
  1680. $prompt = getProp($data, 'prompt', '帮我根据给出的内容生成短剧大纲');
  1681. $model = getProp($data, 'model', 'v3');
  1682. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1683. if (!$file && !$content && !$bid) {
  1684. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1685. }
  1686. // 提取文件内容
  1687. if ($content) {
  1688. $content = filterContent($content);
  1689. } elseif ($file) {
  1690. $content = $this->extractFileContent($file);
  1691. if (!$content) {
  1692. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1693. }
  1694. } elseif ($bid) {
  1695. $content = $this->getContentByBid($bid);
  1696. if (!$content) {
  1697. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1698. }
  1699. } else {
  1700. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1701. }
  1702. // 构建消息
  1703. $messages = [
  1704. [
  1705. 'role' => 'system',
  1706. 'content' => '你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  1707. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  1708. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  1709. 示例如下:\n\n
  1710. ###剧本名:西昆仑
  1711. ###故事梗概
  1712. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1713. ###剧本亮点
  1714. 亮点1:绝境奇药,生死一线
  1715. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1716. 亮点2:结拜兄妹,化解尴尬
  1717. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1718. 亮点3:纤发夺命,情愫暗涌
  1719. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1720. ###人物关系
  1721. 阿雪与梁萧之间存在兄妹之情。
  1722. ###核心矛盾
  1723. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1724. ###主体列表
  1725. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1726. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1727. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1728. 阴阳球:天地异宝,能化生精气,救人于危难。
  1729. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1730. ###美术风格
  1731. 基础画风风格词:厚涂古风
  1732. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1733. ###场景列表
  1734. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。'
  1735. ],
  1736. [
  1737. 'role' => 'user',
  1738. 'content' => "以下是文档内容:
  1739. {$content}
  1740. 用户问题:
  1741. {$question}"
  1742. ]
  1743. ];
  1744. $post_data = [
  1745. 'model' => $model,
  1746. 'messages' => $messages,
  1747. 'max_tokens' => 8192,
  1748. 'temperature' => 0.7,
  1749. 'frequency_penalty' => 0,
  1750. 'presence_penalty' => 0,
  1751. 'response_format' => ['type' => 'text'],
  1752. 'stream' => true // 启用流式输出
  1753. ];
  1754. $client = new Client(['timeout' => 1200, 'verify' => false]);
  1755. $response = $client->post($this->url, [
  1756. 'json' => $post_data,
  1757. 'headers' => $this->headers,
  1758. 'stream' => true // 启用流式响应
  1759. ]);
  1760. $body = $response->getBody();
  1761. $fullContent = '';
  1762. $fullReasoningContent = '';
  1763. $usage = [];
  1764. $buffer = '';
  1765. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1766. // 逐行读取流式响应
  1767. while (!$body->eof()) {
  1768. $chunk = $body->read(1024); // 每次读取 1KB
  1769. $buffer .= $chunk;
  1770. // 按行分割
  1771. $lines = explode("\n", $buffer);
  1772. // 保留最后一个不完整的行
  1773. $buffer = array_pop($lines);
  1774. foreach ($lines as $line) {
  1775. $line = trim($line);
  1776. // 跳过空行
  1777. if (empty($line)) {
  1778. continue;
  1779. }
  1780. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  1781. // 检查是否是 SSE 数据行
  1782. if (strpos($line, 'data: ') !== 0) {
  1783. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1784. continue;
  1785. }
  1786. $data = substr($line, 6); // 移除 "data: " 前缀
  1787. if ($data === '[DONE]') {
  1788. dLog('deepseek')->info('收到结束标记');
  1789. break 2; // 跳出两层循环
  1790. }
  1791. try {
  1792. $json = json_decode($data, true);
  1793. if (json_last_error() !== JSON_ERROR_NONE) {
  1794. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1795. continue;
  1796. }
  1797. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  1798. if (isset($json['choices'][0]['delta'])) {
  1799. $delta = $json['choices'][0]['delta'];
  1800. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1801. // 注释掉以下内容则不返回d思维链内容
  1802. if (isset($delta['reasoning_content'])) {
  1803. $fullReasoningContent .= $delta['reasoning_content'];
  1804. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  1805. yield [
  1806. 'type' => 'reasoning',
  1807. 'content' => $delta['reasoning_content'],
  1808. 'full_reasoning' => $fullReasoningContent
  1809. ];
  1810. }
  1811. // 处理最终回答内容
  1812. if (isset($delta['content'])) {
  1813. $fullContent .= $delta['content'];
  1814. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  1815. yield [
  1816. 'type' => 'content',
  1817. 'content' => $delta['content'],
  1818. 'full_content' => $fullContent
  1819. ];
  1820. }
  1821. }
  1822. // 获取使用统计信息
  1823. if (isset($json['usage'])) {
  1824. $usage = $json['usage'];
  1825. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1826. }
  1827. } catch (\Exception $e) {
  1828. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1829. continue;
  1830. }
  1831. }
  1832. }
  1833. dLog('deepseek')->info('流式读取完成', [
  1834. 'content_length' => strlen($fullContent),
  1835. 'reasoning_length' => strlen($fullReasoningContent)
  1836. ]);
  1837. dLog('deepseek')->info('完整内容: '.$fullContent);
  1838. // $fullContent = $this->test_content;
  1839. // $fullReasoningContent = [];
  1840. // $usage = [];
  1841. // $uid = 0;
  1842. // $content = '';
  1843. // $question = '';
  1844. // $anime_id = 10;
  1845. // $fullContent = '###剧本名:看不见的守护者
  1846. // ###故事梗概
  1847. // 假千金许芸重生回到悲剧发生前一个月,为改变被养父母逼迫联姻、最终家暴致死的命运,她提前与真千金徐清遥身份归位,回到亲生父母家。然而,亲生母亲重男轻女,表哥卞大伟对她虎视眈眈。在危机时刻,一个因系统规则而无法被她看见、听见的“空气人”屡次救她于危难。许芸逐渐发现,“空气人”竟是高中时她曾资助过的学霸程景,他因感恩与暗恋,用自己的一切换她重生。两人在“看不见”的困境中相互试探、彼此救赎。许芸勇敢反击原生家庭的伤害,并执着地追寻程景的存在。最终,她的坚持冲破了系统限制,两人得以相见相守,共度余生。
  1848. // ###剧本亮点
  1849. // 亮点1:无形守护,生死相随
  1850. // 开场即用蒙太奇手法快速闪回许芸上辈子惨死、陌生男人(程景)为她收尸下葬的悲凉画面,与重生后她在车流中被“无形力量”猛然拉回的惊险瞬间形成强烈对比。通过许芸茫然四顾、观众却能看到空气中隐约波动的特效,营造出“守护者无处不在却不可见”的悬疑与浪漫感,奠定故事独特基调。
  1851. // 亮点2:阁楼共生,暧昧无声
  1852. // 狭小阁楼内,许芸与“看不见”的程景共处。画面聚焦于两碗面条自动减少、带血纸巾莫名出现、深夜有人喂水等细节,通过许芸的独角戏表演和空镜头的巧妙运用,将无形的陪伴与克制的欲望可视化。尤其是许芸主动“挑衅”、程景流鼻血的幽默桥段,在压抑中迸发甜涩的青春悸动,情感张力十足。
  1853. // 亮点3:真相撕裂,破障重逢
  1854. // 当许芸从徐清遥处得知程景是她曾资助的男孩时,记忆碎片如潮水般涌入脑海的视觉呈现。高潮在于许芸为逼程景现身而“跳楼”,程景下意识抱住她却被“看见”的瞬间。镜头从许芸视角切换为全知视角,程景英俊却惊慌的脸首次清晰展现,两人对视间,长达十年的暗恋、守护与挣扎在此刻爆发,极具情感冲击力。
  1855. // ###人物关系
  1856. // 许芸与程景:从被资助者与资助者,发展为被守护者与隐形守护者,最终成为恋人、夫妻。
  1857. // 许芸与徐母(生母):对抗关系,徐母重男轻女,偏袒侄子卞大伟,是许芸前期的主要压力源。
  1858. // 许芸与卞大伟:受害者与加害者,卞大伟是许芸人身安全的直接威胁。
  1859. // 许芸与徐清遥(真千金):身份互换的复杂关系,前期存在潜在对立,后期因共同遭遇(被卞大伟侵害威胁)而产生微妙共鸣。
  1860. // 程景与夏颜:同学关系,夏颜单恋程景,并因嫉妒成为许芸与程景关系中的短暂阻碍。
  1861. // ###核心矛盾
  1862. // 许芸渴望看见并拥抱用生命守护她的程景,却受系统规则所限,无法感知他的存在;程景深爱许芸,愿为她付出一切,却因自卑、身体受损(以为不育)及系统限制,一度选择逃避和“分手”。两人在“看不见的爱”与“触不到的恋人”困境中,进行一场关于勇气、坚持与相互救赎的博弈。
  1863. // ###主体列表
  1864. // 许芸-高中生(重生初期):17岁,面容清丽但带着重生后的疲惫与警觉。身形纤细,常穿着洗得发白的校服或简单卫衣,眼神时而脆弱时而坚定。
  1865. // 许芸-大学生/成年:20-30岁,气质逐渐成熟温婉,衣着简约大方,笑容增多,眼中有了被爱滋养的光彩。
  1866. // 程景-隐形状态(高中至大学):观众可见其模糊轮廓或行动痕迹(如血脚印、空气波动),实际为18-22岁,身高约185cm,肩宽腿长,习惯穿干净的白衬衫或棉质T恤,身上有淡淡的皂角清香。
  1867. // 程景-显形状态(大学后):面容英俊,眉眼深邃,鼻梁高挺,下颌线清晰。身材挺拔,有清晰的肌肉线条。初期显形时略带羞涩与不安,后期沉稳深情。
  1868. // 卞大伟:20岁出头,身材粗壮,皮肤油腻,小眼睛透着阴沉与邪气,常穿脏旧的背心或夹克。
  1869. // 徐母:40多岁,面容刻薄,身材微胖,烫着过时的卷发,穿着艳俗的碎花衬衫,眼神势利。
  1870. // 徐父:40多岁,身材佝偻,面容愁苦,穿着沾满污渍的工装,眼神怯懦。
  1871. // 夏颜:17-20岁,齐肩短发,长相清秀,穿着得体,前期是开朗学霸,后期面对程景时眼神充满倾慕与嫉妒。
  1872. // 徐清遥:17岁,与许芸有几分相似,但气质更冷冽倔强,穿着普通但整洁。
  1873. // ###美术风格
  1874. // 基础画风风格词:现实主义的细腻光影与超现实元素结合
  1875. // 整体采用现实主义基调,色彩饱和度较低,前期以灰蓝、暗绿色调为主,渲染重生后的压抑感与危机感。许芸在徐家的场景光线昏暗、拥挤;程景的阁楼则色调偏暖黄,营造狭小但安全的港湾感。“隐形”程景存在的场景,通过细微的空气扭曲、光影异常、物品无故移动等超现实特效来表现。后期两人相见后,画面色彩逐渐明亮、温暖,尤其婚后生活场景,充满柔和的日光与温馨的家居细节。人物造型追求真实感,服装、环境道具都需体现年代与阶层特征。
  1876. // ###场景列表
  1877. // 徐家馄饨店:老旧居民楼底层店铺,门面窄小,招牌褪色。店内狭窄拥挤,墙壁被油烟熏得发黄,摆放着简陋的桌椅和包馄饨的案板。光线主要来自门口和一台昏黄的吊灯,整体氛围压抑脏乱。
  1878. // 程景的阁楼:位于老式居民楼顶层,空间低矮狭小,斜屋顶开着一扇小窗。室内仅有一张单人床、一张旧书桌和一个矮几。书桌上堆满高中课本与试卷,床单整洁但洗得发白。阳光透过小窗形成光柱,灰尘在光中飞舞,环境简陋但充满生活气息与书卷气。
  1879. // 学校走廊与教室:典型的县级高中环境,走廊墙壁斑驳,贴满励志标语。教室拥挤,课桌堆满书本。重点班教室略显整洁,氛围紧张有序。
  1880. // 街边与巷口:许芸被卞大伟堵截的地点,位于老旧街区,墙壁布满涂鸦和小广告,路边有臭水沟,环境杂乱,危机四伏。
  1881. // 医院病房:多人间病房,设施陈旧,光线苍白冰冷。2号病床空无一物(观众可见程景,许芸看不见),与周围形成诡异对比,突出许芸的孤独与无助。
  1882. // 婚后家居:十年后,许芸与程景的家。宽敞明亮的客厅,装修简约温馨,有绿植和照片墙,阳光充足,与之前的压抑环境形成鲜明对比,象征苦尽甘来。 ';
  1883. // 处理完整内容并返回最终结果
  1884. $script_arr = [];
  1885. if ($fullContent) {
  1886. $script_arr = handleScriptContent($fullContent);
  1887. }
  1888. // 新建动漫
  1889. $anime_name = getProp($script_arr, 'script_name');
  1890. if (!$anime_name) {
  1891. yield [
  1892. 'type' => 'done',
  1893. 'answer' => $fullContent,
  1894. 'reasoning' => $fullReasoningContent,
  1895. 'usage' => $usage,
  1896. 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  1897. ];
  1898. }
  1899. // 确认对话名称唯一性
  1900. if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  1901. $anime_name = $anime_name . '_' . date('YmdHis');
  1902. }
  1903. $table_data = [
  1904. 'user_id' => $uid,
  1905. 'anime_name' => $anime_name,
  1906. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1907. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1908. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1909. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1910. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1911. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1912. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1913. 'status' => '解析完成',
  1914. 'content' => $content,
  1915. // 'start_episode_sequence' => 1,
  1916. // 'end_episode_sequence' => count($script_arr['episodes']),
  1917. // 'episode_num' => count($script_arr['episodes']),
  1918. 'generate_status' => '待执行',
  1919. 'created_at' => date('Y-m-d H:i:s'),
  1920. 'updated_at' => date('Y-m-d H:i:s')
  1921. ];
  1922. try {
  1923. DB::beginTransaction();
  1924. // 新建动漫大纲
  1925. $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  1926. if (!$anime_id) {
  1927. dLog('deepseek')->info('对话保存失败', $table_data);
  1928. Utils::throwError('20003:对话保存失败');
  1929. }
  1930. // 保存对话记录
  1931. $recrods = [
  1932. [
  1933. 'uid' => $uid,
  1934. 'anime_id' => $anime_id,
  1935. 'sequence' => 0,
  1936. 'role' => 'user',
  1937. 'content' => "用户问题:\n
  1938. {$prompt}\n\n
  1939. 以下是文档内容:\n
  1940. {$content}",
  1941. 'created_at' => date('Y-m-d H:i:s'),
  1942. 'updated_at' => date('Y-m-d H:i:s')
  1943. ],
  1944. [
  1945. 'uid' => $uid,
  1946. 'anime_id' => $anime_id,
  1947. 'sequence' => 0,
  1948. 'role' => 'assistant',
  1949. 'content' => $fullContent,
  1950. 'created_at' => date('Y-m-d H:i:s'),
  1951. 'updated_at' => date('Y-m-d H:i:s')
  1952. ]
  1953. ];
  1954. // 保存对话记录
  1955. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  1956. if (!$boolen3) {
  1957. Utils::throwError('20003:对话记录保存失败');
  1958. }
  1959. }catch (\Exception $e) {
  1960. DB::rollBack();
  1961. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  1962. yield [
  1963. 'type' => 'done',
  1964. 'answer' => $fullContent,
  1965. 'reasoning' => $fullReasoningContent,
  1966. 'usage' => $usage,
  1967. 'error' => $e->getMessage(),
  1968. ];
  1969. }
  1970. DB::commit();
  1971. $table_data['anime_id'] = $anime_id;
  1972. $table_data['roles'] = json_decode($table_data['roles'], true);
  1973. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  1974. // $table_data['episodes'] = $script_arr['episodes'];
  1975. unset($table_data['created_at']);
  1976. unset($table_data['updated_at']);
  1977. unset($table_data['status']);
  1978. yield [
  1979. 'type' => 'done',
  1980. 'script' => $table_data,
  1981. 'answer' => $fullContent,
  1982. 'reasoning' => $fullReasoningContent,
  1983. 'usage' => $usage
  1984. ];
  1985. }
  1986. public function reGenerateAnime($data) {
  1987. $uid = Site::getUid();
  1988. $anime_id = getProp($data, 'anime_id');
  1989. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1990. if (!$anime) {
  1991. Utils::throwError('20003:该对话不存在');
  1992. }
  1993. $question =getProp($data, 'question', "请根据实例格式完成剧本大纲");
  1994. $prompt = getProp($data, 'prompt', '帮我根据给出的内容生成短剧大纲');
  1995. $model = getProp($data, 'model', 'v3');
  1996. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  1997. $content = filterContent(getProp($anime, 'content'));
  1998. $system_message = [
  1999. 'role' => 'system',
  2000. 'content' => '你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  2001. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2002. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2003. 示例如下:\n\n
  2004. ###剧本名:西昆仑
  2005. ###故事梗概
  2006. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2007. ###剧本亮点
  2008. 亮点1:绝境奇药,生死一线
  2009. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2010. 亮点2:结拜兄妹,化解尴尬
  2011. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2012. 亮点3:纤发夺命,情愫暗涌
  2013. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2014. ###人物关系
  2015. 阿雪与梁萧之间存在兄妹之情。
  2016. ###核心矛盾
  2017. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2018. ###主体列表
  2019. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2020. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2021. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2022. 阴阳球:天地异宝,能化生精气,救人于危难。
  2023. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2024. ###美术风格
  2025. 基础画风风格词:厚涂古风
  2026. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2027. ###场景列表
  2028. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。'
  2029. ];
  2030. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  2031. $episode_count = $this->extractEpisodeNumber($prompt);
  2032. if ($episode_count) {
  2033. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  2034. $system_message = [
  2035. 'role' => 'system',
  2036. 'content' => '你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  2037. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2038. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2039. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题
  2040. 示例如下:\n\n
  2041. ###剧本名:西昆仑
  2042. ###故事梗概
  2043. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2044. ###剧本亮点
  2045. 亮点1:绝境奇药,生死一线
  2046. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2047. 亮点2:结拜兄妹,化解尴尬
  2048. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2049. 亮点3:纤发夺命,情愫暗涌
  2050. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2051. ###人物关系
  2052. 阿雪与梁萧之间存在兄妹之情。
  2053. ###核心矛盾
  2054. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2055. ###主体列表
  2056. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2057. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2058. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2059. 阴阳球:天地异宝,能化生精气,救人于危难。
  2060. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2061. ###美术风格
  2062. 基础画风风格词:厚涂古风
  2063. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2064. ###场景列表
  2065. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2066. ###分集详细内容
  2067. ##第1章 重生
  2068. 我重生了。
  2069. 源于一个男人偏执的暗恋。
  2070. ##第2章 相救
  2071. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  2072. 我眼睛扫向站在锅炉后的卞大伟。'
  2073. ];
  2074. // 构建消息
  2075. $messages = [
  2076. $system_message,
  2077. [
  2078. 'role' => 'user',
  2079. 'content' => "以下是文档内容:
  2080. {$content}
  2081. 用户问题:
  2082. {$question}"
  2083. ]
  2084. ];
  2085. }else {
  2086. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  2087. // 构建消息
  2088. $messages = [
  2089. $system_message,
  2090. [
  2091. 'role' => 'user',
  2092. 'content' => "以下是文档内容:
  2093. {$content}
  2094. 用户问题:
  2095. {$question}"
  2096. ]
  2097. ];
  2098. }else {
  2099. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  2100. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  2101. return (array)$value;
  2102. })->toArray();
  2103. array_unshift($messages, $system_message);
  2104. $messages[] = [
  2105. 'role' => 'user',
  2106. 'content' => $prompt
  2107. ];
  2108. }
  2109. }
  2110. $post_data = [
  2111. 'model' => $model,
  2112. 'messages' => $messages,
  2113. 'max_tokens' => 8192,
  2114. 'temperature' => 0.7,
  2115. 'frequency_penalty' => 0,
  2116. 'presence_penalty' => 0,
  2117. 'response_format' => ['type' => 'text'],
  2118. 'stream' => true // 启用流式输出
  2119. ];
  2120. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2121. $response = $client->post($this->url, [
  2122. 'json' => $post_data,
  2123. 'headers' => $this->headers,
  2124. 'stream' => true // 启用流式响应
  2125. ]);
  2126. $body = $response->getBody();
  2127. $fullContent = '';
  2128. $fullReasoningContent = '';
  2129. $usage = [];
  2130. $buffer = '';
  2131. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2132. // 逐行读取流式响应
  2133. while (!$body->eof()) {
  2134. $chunk = $body->read(1024); // 每次读取 1KB
  2135. $buffer .= $chunk;
  2136. // 按行分割
  2137. $lines = explode("\n", $buffer);
  2138. // 保留最后一个不完整的行
  2139. $buffer = array_pop($lines);
  2140. foreach ($lines as $line) {
  2141. $line = trim($line);
  2142. // 跳过空行
  2143. if (empty($line)) {
  2144. continue;
  2145. }
  2146. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  2147. // 检查是否是 SSE 数据行
  2148. if (strpos($line, 'data: ') !== 0) {
  2149. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2150. continue;
  2151. }
  2152. $data = substr($line, 6); // 移除 "data: " 前缀
  2153. if ($data === '[DONE]') {
  2154. dLog('deepseek')->info('收到结束标记');
  2155. break 2; // 跳出两层循环
  2156. }
  2157. try {
  2158. $json = json_decode($data, true);
  2159. if (json_last_error() !== JSON_ERROR_NONE) {
  2160. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2161. continue;
  2162. }
  2163. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  2164. if (isset($json['choices'][0]['delta'])) {
  2165. $delta = $json['choices'][0]['delta'];
  2166. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2167. // 注释掉以下内容则不返回d思维链内容
  2168. if (isset($delta['reasoning_content'])) {
  2169. $fullReasoningContent .= $delta['reasoning_content'];
  2170. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  2171. yield [
  2172. 'type' => 'reasoning',
  2173. 'content' => $delta['reasoning_content'],
  2174. 'full_reasoning' => $fullReasoningContent
  2175. ];
  2176. }
  2177. // 处理最终回答内容
  2178. if (isset($delta['content'])) {
  2179. $fullContent .= $delta['content'];
  2180. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  2181. yield [
  2182. 'type' => 'content',
  2183. 'content' => $delta['content'],
  2184. 'full_content' => $fullContent
  2185. ];
  2186. }
  2187. }
  2188. // 获取使用统计信息
  2189. if (isset($json['usage'])) {
  2190. $usage = $json['usage'];
  2191. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2192. }
  2193. } catch (\Exception $e) {
  2194. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2195. continue;
  2196. }
  2197. }
  2198. }
  2199. dLog('deepseek')->info('流式读取完成', [
  2200. 'content_length' => strlen($fullContent),
  2201. 'reasoning_length' => strlen($fullReasoningContent)
  2202. ]);
  2203. dLog('deepseek')->info('完整内容: '.$fullContent);
  2204. // 处理完整内容并返回最终结果
  2205. $script_arr = [];
  2206. if ($fullContent) {
  2207. $script_arr = handleScriptContent($fullContent);
  2208. }
  2209. // // 新建动漫
  2210. // $anime_name = getProp($script_arr, 'script_name');
  2211. // if (!$anime_name) {
  2212. // yield [
  2213. // 'type' => 'done',
  2214. // 'answer' => $fullContent,
  2215. // 'reasoning' => $fullReasoningContent,
  2216. // 'usage' => $usage,
  2217. // 'error' => '未能识别到剧本名称,请确认内容是否符合要求'
  2218. // ];
  2219. // }
  2220. // // 确认对话名称唯一性
  2221. // if (DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2222. // $anime_name = $anime_name . '_' . date('YmdHis');
  2223. // }
  2224. $table_data = [
  2225. 'user_id' => $uid,
  2226. // 'anime_name' => $anime_name,
  2227. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2228. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2229. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2230. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2231. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2232. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2233. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2234. 'status' => '解析完成',
  2235. 'generate_status' => '待执行',
  2236. 'updated_at' => date('Y-m-d H:i:s')
  2237. ];
  2238. // 如果是修改集数,则将content内容更新(会改变原文)
  2239. if (isset($episode_count) && $episode_count > 0) {
  2240. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  2241. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  2242. }else {
  2243. $chapters = $this->splitContent($content);
  2244. $chapter_count = count($chapters);
  2245. if ($chapter_count > 0) {
  2246. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  2247. }
  2248. }
  2249. try {
  2250. DB::beginTransaction();
  2251. // 新建动漫大纲
  2252. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2253. if (!$boolen) {
  2254. dLog('deepseek')->info('对话修改失败', $table_data);
  2255. Utils::throwError('20003:对话修改失败');
  2256. }
  2257. // 保存对话记录
  2258. $recrods = [
  2259. [
  2260. 'uid' => $uid,
  2261. 'anime_id' => $anime_id,
  2262. 'sequence' => 0,
  2263. 'role' => 'user',
  2264. 'content' => $prompt,
  2265. 'created_at' => date('Y-m-d H:i:s'),
  2266. 'updated_at' => date('Y-m-d H:i:s')
  2267. ],
  2268. [
  2269. 'uid' => $uid,
  2270. 'anime_id' => $anime_id,
  2271. 'sequence' => 0,
  2272. 'role' => 'assistant',
  2273. 'content' => $fullContent,
  2274. 'created_at' => date('Y-m-d H:i:s'),
  2275. 'updated_at' => date('Y-m-d H:i:s')
  2276. ]
  2277. ];
  2278. // 保存对话记录
  2279. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  2280. if (!$boolen3) {
  2281. Utils::throwError('20003:对话记录保存失败');
  2282. }
  2283. }catch (\Exception $e) {
  2284. DB::rollBack();
  2285. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2286. yield [
  2287. 'type' => 'done',
  2288. 'answer' => $fullContent,
  2289. 'reasoning' => $fullReasoningContent,
  2290. 'usage' => $usage,
  2291. 'error' => $e->getMessage(),
  2292. ];
  2293. }
  2294. DB::commit();
  2295. $table_data['anime_id'] = $anime_id;
  2296. $table_data['roles'] = json_decode($table_data['roles'], true);
  2297. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2298. unset($table_data['updated_at']);
  2299. unset($table_data['status']);
  2300. yield [
  2301. 'type' => 'done',
  2302. 'script' => $table_data,
  2303. 'answer' => $fullContent,
  2304. 'reasoning' => $fullReasoningContent,
  2305. 'usage' => $usage
  2306. ];
  2307. }
  2308. public function chat($data) {
  2309. $uid = Site::getUid();
  2310. $anime_id = getProp($data, 'anime_id');
  2311. $episode_number = getProp($data, 'episode_number', 1);
  2312. $anime = DB::table('mp_animes')->where('id', $anime_id)->select('content', 'roles', 'scenes')->first();
  2313. if (!$anime) Utils::throwError('20003:该对话不存在!');
  2314. $roles = json_decode(getProp($anime, 'roles'), true);
  2315. $scenes = json_decode(getProp($anime, 'scenes'), true);
  2316. // 转换主体列表和场景列表的格式
  2317. $roles_content = '';
  2318. foreach ($roles as $role) {
  2319. $roles_content .= getProp($role, 'role').': '.getProp($role, 'description')."\n";
  2320. }
  2321. $scenes_content = '';
  2322. foreach($scenes as $scene) {
  2323. $scenes_content .= getProp($scene, 'scene').': '.getProp($scene, 'description')."\n";
  2324. }
  2325. $prompt = getProp($data, 'prompt', '确认分镜大纲');
  2326. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n\n
  2327. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}
  2328. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$roles_content}\n\n
  2329. 3.<场景列表>必须在以下场景中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$scenes_content}\n\n
  2330. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”: \n\n
  2331. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2332. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音音色”、“台词内容”和“画面类型”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2333. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2334. 4.4“分镜信息”中的“台词内容”需与原文中的台词完全一致,不得修改或添加任何内容。
  2335. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2336. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)
  2337. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无
  2338. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面
  2339. 示例格式:\n\n
  2340. 第1集:隐形的守护者
  2341. ###故事梗概
  2342. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  2343. ###美术风格
  2344. 基础画风风格词:韩漫二次元
  2345. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  2346. ###主体列表
  2347. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。
  2348. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。
  2349. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。
  2350. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。
  2351. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。
  2352. ###场景列表
  2353. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  2354. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  2355. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  2356. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  2357. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  2358. ###分镜剧本
  2359. ##第1幕:徐家老旧厨房 白天 室内
  2360. 分镜1
  2361. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2362. 场景:徐家老旧厨房
  2363. 构图设计:全景,低角度仰视
  2364. 运镜调度:手持拍摄
  2365. 配音角色:旁白
  2366. 出镜角色:许芸-校服装、徐母
  2367. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2368. 画面类型:普通画面
  2369. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2370. 分镜2
  2371. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2372. 场景:徐家老旧厨房
  2373. 构图设计:近景,徐母面部特写
  2374. 运镜调度:固定镜头
  2375. 配音角色:徐母
  2376. 出镜角色:徐母
  2377. 台词内容:问我夜不归宿死哪儿去了。
  2378. 画面类型:对口型
  2379. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2380. ##第2幕:徐家简陋客厅 黄昏 室内
  2381. 分镜3
  2382. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2383. 场景:徐家简陋客厅
  2384. 构图设计:全景,景深虚化
  2385. 运镜调度:固定镜头
  2386. 配音角色:旁白
  2387. 出镜角色:无
  2388. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2389. 画面类型:普通画面
  2390. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2391. 分镜4
  2392. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2393. 场景:徐家简陋客厅
  2394. 构图设计:特写,火车票
  2395. 运镜调度:固定镜头
  2396. 配音角色:旁白
  2397. 出镜角色:无
  2398. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2399. 画面类型:普通画面
  2400. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  2401. \n\n";
  2402. // 获取章节内容
  2403. $full_content = getProp($anime, 'content');
  2404. // 根据章节内容拆分章节
  2405. $chapters = $this->splitContent($full_content);
  2406. if ($prompt == '确认分镜大纲') {
  2407. $content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2408. if (!$content) {
  2409. Utils::throwError('20003:章节内容无法获取,请确认');
  2410. }
  2411. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  2412. // 构建消息
  2413. $messages[] =
  2414. [
  2415. 'role' => 'user',
  2416. 'content' => $question
  2417. ];
  2418. }else if ($prompt == '继续策划下一集') {
  2419. $content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2420. if (!$content) {
  2421. Utils::throwError('20003:章节内容无法获取,请确认');
  2422. }
  2423. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  2424. // 获取上一集最后记录
  2425. $prev_sequence = $episode_number - 1;
  2426. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', $prev_sequence)
  2427. ->select('role', 'content')->orderBy('created_at', 'desc')->orderBy('id')->get()->map(function($value) {
  2428. return (array)$value;
  2429. })->toArray();
  2430. // 构建消息
  2431. $messages[] =
  2432. [
  2433. 'role' => 'user',
  2434. 'content' => $question
  2435. ];
  2436. }else {
  2437. $content = $full_content;
  2438. $question = $prompt;
  2439. $messages[] =
  2440. [
  2441. 'role' => 'user',
  2442. 'content' => $question
  2443. ];
  2444. }
  2445. $model = getProp($data, 'model', 'v3');
  2446. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2447. $post_data = [
  2448. 'model' => $model,
  2449. 'messages' => $messages,
  2450. 'max_tokens' => 8192,
  2451. 'temperature' => 0.7,
  2452. 'frequency_penalty' => 0,
  2453. 'presence_penalty' => 0,
  2454. 'response_format' => ['type' => 'text'],
  2455. 'stream' => true // 启用流式输出
  2456. ];
  2457. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2458. $response = $client->post($this->url, [
  2459. 'json' => $post_data,
  2460. 'headers' => $this->headers,
  2461. 'stream' => true // 启用流式响应
  2462. ]);
  2463. $body = $response->getBody();
  2464. $fullContent = '';
  2465. $fullReasoningContent = '';
  2466. $usage = [];
  2467. $buffer = '';
  2468. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2469. // 逐行读取流式响应
  2470. while (!$body->eof()) {
  2471. $chunk = $body->read(1024); // 每次读取 1KB
  2472. $buffer .= $chunk;
  2473. // 按行分割
  2474. $lines = explode("\n", $buffer);
  2475. // 保留最后一个不完整的行
  2476. $buffer = array_pop($lines);
  2477. foreach ($lines as $line) {
  2478. $line = trim($line);
  2479. // 跳过空行
  2480. if (empty($line)) {
  2481. continue;
  2482. }
  2483. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  2484. // 检查是否是 SSE 数据行
  2485. if (strpos($line, 'data: ') !== 0) {
  2486. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2487. continue;
  2488. }
  2489. $data = substr($line, 6); // 移除 "data: " 前缀
  2490. if ($data === '[DONE]') {
  2491. dLog('deepseek')->info('收到结束标记');
  2492. break 2; // 跳出两层循环
  2493. }
  2494. try {
  2495. $json = json_decode($data, true);
  2496. if (json_last_error() !== JSON_ERROR_NONE) {
  2497. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2498. continue;
  2499. }
  2500. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  2501. if (isset($json['choices'][0]['delta'])) {
  2502. $delta = $json['choices'][0]['delta'];
  2503. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2504. // 注释掉以下内容则不返回d思维链内容
  2505. if (isset($delta['reasoning_content'])) {
  2506. $fullReasoningContent .= $delta['reasoning_content'];
  2507. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  2508. yield [
  2509. 'type' => 'reasoning',
  2510. 'content' => $delta['reasoning_content'],
  2511. 'full_reasoning' => $fullReasoningContent
  2512. ];
  2513. }
  2514. // 处理最终回答内容
  2515. if (isset($delta['content'])) {
  2516. $fullContent .= $delta['content'];
  2517. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  2518. yield [
  2519. 'type' => 'content',
  2520. 'content' => $delta['content'],
  2521. 'full_content' => $fullContent
  2522. ];
  2523. }
  2524. }
  2525. // 获取使用统计信息
  2526. if (isset($json['usage'])) {
  2527. $usage = $json['usage'];
  2528. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2529. }
  2530. } catch (\Exception $e) {
  2531. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2532. continue;
  2533. }
  2534. }
  2535. }
  2536. dLog('deepseek')->info('流式读取完成', [
  2537. 'content_length' => strlen($fullContent),
  2538. 'reasoning_length' => strlen($fullReasoningContent)
  2539. ]);
  2540. // // $fullContent = '111';
  2541. // // $fullReasoningContent = [];
  2542. // // $usage = [];
  2543. // // $uid = 0;
  2544. // // $content = '';
  2545. // // $question = '';
  2546. // // $episode_number = 1;
  2547. // // $anime_id = 13;
  2548. // $fullContent = DB::table('mp_anime_records')->orderBy('id', 'desc')->value('content');
  2549. dLog('deepseek')->info('完整内容: '.$fullContent);
  2550. // 处理完整内容并返回最终结果
  2551. $episode_arr = handleEpisodeContent($fullContent);
  2552. try {
  2553. DB::beginTransaction();
  2554. // 新建动漫剧集
  2555. $episode = [
  2556. 'anime_id' => $anime_id,
  2557. 'episode_number' => $episode_number,
  2558. 'title' => $episode_arr['episode_title'],
  2559. 'content' => $content,
  2560. // 'content' => '',
  2561. 'intro' => $episode_arr['intro'],
  2562. 'art_style' => $episode_arr['art_style'],
  2563. 'roles' => json_encode($episode_arr['roles'], 256),
  2564. 'scenes' => json_encode($episode_arr['scenes'], 256),
  2565. 'sequence' => 1,
  2566. 'generate_status' => '待执行',
  2567. 'generate_at' => date('Y-m-d H:i:s'),
  2568. 'is_default' => 1,
  2569. 'updated_at' => date('Y-m-d H:i:s'),
  2570. ];
  2571. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->select('id', 'sequence')->first();
  2572. if ($current_episode) {
  2573. $episode['sequence'] = getProp($current_episode, 'sequence');
  2574. $episode_id = getProp($current_episode, 'id');
  2575. $boolen2 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->update($episode);
  2576. }else {
  2577. $episode['created_at'] = date('Y-m-d H:i:s');
  2578. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2579. $boolen2 = $episode_id ? true : false;
  2580. }
  2581. if (!$boolen2) {
  2582. dLog('deepseek')->info('分集内容保存失败', $episode);
  2583. Utils::throwError('20003:分集内容保存失败');
  2584. }
  2585. // 删除历史分集内容
  2586. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->delete();
  2587. $segments = [];
  2588. foreach($episode_arr['acts'] as $act) {
  2589. foreach($act['segments'] as $segment) {
  2590. $segments[] = [
  2591. 'anime_id' => $anime_id,
  2592. 'episode_id' => $episode_id,
  2593. 'episode_number' => $episode_number,
  2594. 'act_number' => $act['act_number'],
  2595. 'act_title' => $act['act_title'],
  2596. 'segment_id' => getProp($segment, 'segment_id'),
  2597. 'segment_number' => getProp($segment, 'segment_number'),
  2598. 'segment_content' => getProp($segment, 'segment_content'),
  2599. 'description' => getProp($segment, 'description'),
  2600. 'composition' => getProp($segment, 'composition'),
  2601. 'camera_movement' => getProp($segment, 'camera_movement'),
  2602. 'voice_actor' => getProp($segment, 'voice_actor'),
  2603. 'dialogue' => getProp($segment, 'dialogue'),
  2604. 'frame_type' => getProp($segment, 'frame_type'),
  2605. 'scene' => getProp($segment, 'scene'),
  2606. 'characters' => getProp($segment, 'characters'),
  2607. 'created_at' => date('Y-m-d H:i:s'),
  2608. 'updated_at' => date('Y-m-d H:i:s')
  2609. ];
  2610. }
  2611. }
  2612. $boolen3 = DB::table('mp_episode_segments')->insert($segments);
  2613. if (!$boolen3) {
  2614. dLog('deepseek')->info('分镜内容保存失败', $episode);
  2615. Utils::throwError('20003:分镜内容保存失败');
  2616. }
  2617. // 保存对话记录
  2618. $recrods = [
  2619. [
  2620. 'uid' => $uid,
  2621. 'anime_id' => $anime_id,
  2622. 'role' => 'user',
  2623. 'content' => $prompt,
  2624. 'sequence' => $episode_number,
  2625. 'created_at' => date('Y-m-d H:i:s'),
  2626. 'updated_at' => date('Y-m-d H:i:s')
  2627. ],
  2628. [
  2629. 'uid' => $uid,
  2630. 'anime_id' => $anime_id,
  2631. 'role' => 'assistant',
  2632. 'content' => $fullContent,
  2633. 'sequence' => $episode_number,
  2634. 'created_at' => date('Y-m-d H:i:s'),
  2635. 'updated_at' => date('Y-m-d H:i:s')
  2636. ]
  2637. ];
  2638. // 保存对话记录
  2639. $boolen3 = DB::table('mp_anime_records')->insert($recrods);
  2640. if (!$boolen3) {
  2641. Utils::throwError('20003:对话记录保存失败');
  2642. }
  2643. }catch (\Exception $e) {
  2644. DB::rollBack();
  2645. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2646. yield [
  2647. 'type' => 'done',
  2648. 'answer' => $fullContent,
  2649. 'reasoning' => $fullReasoningContent,
  2650. 'usage' => $usage,
  2651. 'error' => $e->getMessage(),
  2652. ];
  2653. }
  2654. DB::commit();
  2655. // dd('end');
  2656. $episode['episode_id'] = $episode_id;
  2657. $episode['roles'] = json_decode($episode['roles'], true);
  2658. $episode['scenes'] = json_decode($episode['scenes'], true);
  2659. $episode['acts'] = json_decode($episode['acts'], true);
  2660. yield [
  2661. 'type' => 'done',
  2662. 'episode' => $episode,
  2663. 'answer' => $fullContent,
  2664. 'reasoning' => $fullReasoningContent,
  2665. 'usage' => $usage
  2666. ];
  2667. }
  2668. public function chatChangeImg($data) {
  2669. $segment = getProp($data, 'segment');
  2670. $segment_content = getProp($segment, 'segment_content');
  2671. $prompt = getProp($data, 'prompt');
  2672. $ref_img = getProp($data, 'ref_img');
  2673. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  2674. $model = getProp($data, 'model', 'v3');
  2675. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2676. $messages[] =
  2677. [
  2678. 'role' => 'user',
  2679. 'content' => $question
  2680. ];
  2681. $post_data = [
  2682. 'model' => $model,
  2683. 'messages' => $messages,
  2684. 'max_tokens' => 8192,
  2685. 'temperature' => 0.7,
  2686. 'frequency_penalty' => 0,
  2687. 'presence_penalty' => 0,
  2688. 'response_format' => ['type' => 'text'],
  2689. 'stream' => false // 是否启用流式输出
  2690. ];
  2691. // 调用流式输出的deepseek
  2692. $chatResult = $this->chatOnly($post_data);
  2693. if (is_array($chatResult)) {
  2694. extract($chatResult);
  2695. }else {
  2696. Utils::throwError('20003: 接口调用失败!');
  2697. }
  2698. return [
  2699. 'type' => 'done',
  2700. // 'episode' => $episode,
  2701. 'answer' => $fullContent,
  2702. 'reasoning' => $fullReasoningContent,
  2703. 'usage' => $usage
  2704. ];
  2705. }
  2706. // 仅调用deepseek对话接口
  2707. private function chatOnly($post_data) {
  2708. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2709. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2710. $response = $result->getBody()->getContents();
  2711. $response_arr = json_decode($response, true);
  2712. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  2713. $fullContent = '';
  2714. $fullReasoningContent = [];
  2715. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  2716. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2717. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2718. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  2719. }
  2720. return [
  2721. 'fullContent' => $fullContent,
  2722. 'fullReasoningContent' => $fullReasoningContent,
  2723. 'usage' => $usage
  2724. ];
  2725. }
  2726. private function splitContent($content) {
  2727. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  2728. $chapters = [];
  2729. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  2730. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  2731. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  2732. foreach ($matches as $match) {
  2733. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  2734. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  2735. if (!empty($title) && !empty($chapterContent)) {
  2736. $chapters[] = [
  2737. 'title' => $title,
  2738. 'content' => $chapterContent
  2739. ];
  2740. }
  2741. }
  2742. }
  2743. return $chapters;
  2744. }
  2745. public function getContentByBid($bid) {
  2746. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  2747. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  2748. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  2749. $content = '';
  2750. foreach ($chapters as $chapter) {
  2751. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  2752. }
  2753. return $content;
  2754. }
  2755. /**
  2756. * 根据文件类型提取文本内容
  2757. *
  2758. * @param mixed $file 文件对象或文件路径
  2759. * @return string
  2760. */
  2761. public function extractFileContent($file) {
  2762. // 获取文件路径和扩展名
  2763. if (is_string($file)) {
  2764. $filePath = $file;
  2765. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  2766. } else {
  2767. // Laravel UploadedFile 对象
  2768. $filePath = $file->getRealPath();
  2769. $extension = strtolower($file->getClientOriginalExtension());
  2770. }
  2771. $content = '';
  2772. switch ($extension) {
  2773. case 'txt':
  2774. $content = $this->extractTxtContent($filePath);
  2775. break;
  2776. case 'pdf':
  2777. $content = $this->extractPdfContent($filePath);
  2778. break;
  2779. case 'doc':
  2780. case 'docx':
  2781. $content = $this->extractWordContent($filePath);
  2782. break;
  2783. // case 'jpg':
  2784. // case 'jpeg':
  2785. // case 'png':
  2786. // case 'gif':
  2787. // case 'bmp':
  2788. // case 'webp':
  2789. // $content = $this->extractImageContent($filePath);
  2790. // break;
  2791. default:
  2792. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  2793. }
  2794. return $content;
  2795. }
  2796. /**
  2797. * 提取 TXT 文件内容
  2798. */
  2799. private function extractTxtContent($filePath) {
  2800. if (!file_exists($filePath)) {
  2801. Utils::throwError('20003:文件不存在');
  2802. }
  2803. $content = file_get_contents($filePath);
  2804. // 尝试检测并转换编码
  2805. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  2806. if ($encoding && $encoding !== 'UTF-8') {
  2807. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  2808. }
  2809. return trim($content);
  2810. }
  2811. /**
  2812. * 提取 PDF 文件内容
  2813. */
  2814. private function extractPdfContent($filePath) {
  2815. if (!file_exists($filePath)) {
  2816. Utils::throwError('20003:文件不存在');
  2817. }
  2818. try {
  2819. $parser = new PdfParser();
  2820. $pdf = $parser->parseFile($filePath);
  2821. $content = $pdf->getText();
  2822. return trim($content);
  2823. } catch (\Exception $e) {
  2824. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  2825. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  2826. }
  2827. }
  2828. /**
  2829. * 提取 Word 文件内容(支持 doc 和 docx)
  2830. */
  2831. private function extractWordContent($filePath) {
  2832. if (!file_exists($filePath)) {
  2833. Utils::throwError('20003:文件不存在');
  2834. }
  2835. try {
  2836. $phpWord = WordIOFactory::load($filePath);
  2837. $content = '';
  2838. foreach ($phpWord->getSections() as $section) {
  2839. foreach ($section->getElements() as $element) {
  2840. $content .= $this->extractWordElementText($element);
  2841. }
  2842. }
  2843. return trim($content);
  2844. } catch (\Exception $e) {
  2845. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  2846. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  2847. }
  2848. }
  2849. /**
  2850. * 递归提取 Word 元素中的文本
  2851. */
  2852. private function extractWordElementText($element) {
  2853. $text = '';
  2854. if (method_exists($element, 'getText')) {
  2855. $text .= $element->getText() . "\n";
  2856. } elseif (method_exists($element, 'getElements')) {
  2857. foreach ($element->getElements() as $childElement) {
  2858. $text .= $this->extractWordElementText($childElement);
  2859. }
  2860. }
  2861. return $text;
  2862. }
  2863. /**
  2864. * 提取图片内容(使用火山引擎 OCR)
  2865. */
  2866. private function extractImageContent($filePath) {
  2867. if (!file_exists($filePath)) {
  2868. Utils::throwError('20003:文件不存在');
  2869. }
  2870. try {
  2871. // 读取图片并转换为 base64
  2872. $imageData = file_get_contents($filePath);
  2873. $base64Image = base64_encode($imageData);
  2874. // 调用火山引擎 OCR 服务
  2875. $content = $this->callVolcEngineOCR($base64Image);
  2876. return trim($content);
  2877. } catch (\Exception $e) {
  2878. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  2879. Utils::throwError('20003:图片识别失败');
  2880. }
  2881. }
  2882. /**
  2883. * 调用火山引擎 OCR 服务识别图片文字
  2884. *
  2885. * @param string $base64Image base64 编码的图片数据
  2886. * @return string 识别的文字内容
  2887. */
  2888. private function callVolcEngineOCR($base64Image) {
  2889. $method = 'POST';
  2890. $service = 'cv';
  2891. $host = 'visual.volcengineapi.com';
  2892. $region = env('VOLC_REGION', 'cn-north-1');
  2893. $access_key = env('VOLC_AK');
  2894. $secret_key = env('VOLC_SK');
  2895. $action = 'OCRNormal';
  2896. $version = '2020-08-26';
  2897. if (!$access_key || !$secret_key) {
  2898. Utils::throwError('20003:请配置火山引擎 AK/SK');
  2899. }
  2900. // 请求体
  2901. $body = json_encode([
  2902. 'image_base64' => $base64Image
  2903. ]);
  2904. // 生成签名
  2905. $headers = $this->getVolcEngineSignHeaders(
  2906. $method, $service, $host, $region,
  2907. "Action={$action}&Version={$version}",
  2908. $access_key, $secret_key, $body
  2909. );
  2910. $client = new Client(['timeout' => 60, 'verify' => false]);
  2911. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  2912. 'headers' => $headers,
  2913. 'body' => $body
  2914. ]);
  2915. $response_arr = json_decode($response->getBody()->getContents(), true);
  2916. // 提取识别的文字
  2917. $textLines = [];
  2918. if (isset($response_arr['data']['line_texts'])) {
  2919. $textLines = $response_arr['data']['line_texts'];
  2920. } elseif (isset($response_arr['data']['ocr_infos'])) {
  2921. foreach ($response_arr['data']['ocr_infos'] as $info) {
  2922. if (isset($info['text'])) {
  2923. $textLines[] = $info['text'];
  2924. }
  2925. }
  2926. }
  2927. if (empty($textLines)) {
  2928. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  2929. return '';
  2930. }
  2931. return implode("\n", $textLines);
  2932. }
  2933. /**
  2934. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  2935. */
  2936. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  2937. $contentType = 'application/json';
  2938. $accept = 'application/json';
  2939. // 获取当前UTC时间
  2940. $t = new DateTime('now', new DateTimeZone('UTC'));
  2941. $xDate = $t->format('Ymd\THis\Z');
  2942. $dateStamp = $t->format('Ymd');
  2943. // 计算 body 的 sha256 哈希
  2944. $payloadHash = hash('sha256', $body);
  2945. // 1. 拼接规范请求串
  2946. $canonicalUri = '/';
  2947. $canonicalQueryString = $queryString;
  2948. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  2949. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  2950. $canonicalRequest = implode("\n", [
  2951. $method,
  2952. $canonicalUri,
  2953. $canonicalQueryString,
  2954. $canonicalHeaders,
  2955. $signedHeaders,
  2956. $payloadHash
  2957. ]);
  2958. // 2. 拼接待签名字符串
  2959. $algorithm = 'HMAC-SHA256';
  2960. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  2961. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  2962. $stringToSign = implode("\n", [
  2963. $algorithm,
  2964. $xDate,
  2965. $credentialScope,
  2966. $hashedCanonicalRequest
  2967. ]);
  2968. // 3. 计算签名
  2969. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  2970. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  2971. // 4. 添加签名到请求头
  2972. $authorizationHeader = sprintf(
  2973. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2974. $algorithm,
  2975. $access_key,
  2976. $credentialScope,
  2977. $signedHeaders,
  2978. $signature
  2979. );
  2980. return [
  2981. 'Accept' => $accept,
  2982. 'Content-Type' => $contentType,
  2983. 'Host' => $host,
  2984. 'X-Date' => $xDate,
  2985. 'X-Content-Sha256'=> $payloadHash,
  2986. 'Authorization' => $authorizationHeader
  2987. ];
  2988. }
  2989. public function generateScriptWords($cid, $model = 'r1') {
  2990. ini_set('max_execution_time', 0);
  2991. if (!$cid) Utils::throwError('20003: 请选择章节!');
  2992. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  2993. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2994. $messages = [
  2995. [
  2996. 'role' => 'system',
  2997. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  2998. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  2999. 2.非对话部分请全部用旁白角色代替
  3000. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  3001. ],
  3002. [
  3003. 'role' => 'user',
  3004. 'content' => $content
  3005. ]
  3006. ];
  3007. $post_data = [
  3008. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  3009. 'messages' => $messages,
  3010. 'max_tokens' => 8192,
  3011. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  3012. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  3013. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  3014. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  3015. 'response_format' => [
  3016. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  3017. ],
  3018. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  3019. ];
  3020. $client = new Client(['timeout' => 1200, 'verify' => false]);
  3021. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  3022. $response = $result->getBody()->getContents();
  3023. $response_arr = json_decode($response, true);
  3024. $update_data = [];
  3025. $content = '';
  3026. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  3027. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  3028. $update_data = [
  3029. 'role' => 'assistant',
  3030. 'content' => $response_arr['choices'][0]['message']['content'],
  3031. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  3032. ];
  3033. }
  3034. return $content;
  3035. }
  3036. /**
  3037. * 智能化解析集数信息
  3038. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  3039. *
  3040. * @param string $prompt 用户输入的提示词
  3041. * @return int|null 解析出的集数,如果没有找到则返回null
  3042. */
  3043. private function extractEpisodeNumber($prompt)
  3044. {
  3045. if (empty($prompt)) {
  3046. return null;
  3047. }
  3048. // 定义各种可能的表达模式
  3049. $patterns = [
  3050. // 基本模式:改成N集、调整成N集、修改成N集
  3051. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  3052. // 扩展模式:分成N集、拆分成N集、分割成N集
  3053. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  3054. // 数量模式:N集、共N集、总共N集
  3055. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  3056. // 制作模式:制作N集、生成N集、创建N集
  3057. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  3058. // 计划模式:计划N集、预计N集、打算N集
  3059. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  3060. // 需要模式:需要N集、要N集
  3061. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  3062. // 中文数字模式:改成三集、调整成五集等
  3063. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  3064. // 英文数字模式
  3065. '/(?:change\s+to|adjust\s+to|modify\s+to|set\s+to|make\s+it|split\s+into|divide\s+into)\s*(\d+)\s*(?:episodes?|eps?)/i',
  3066. ];
  3067. // 中文数字转阿拉伯数字的映射
  3068. $chineseNumbers = [
  3069. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  3070. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  3071. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  3072. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  3073. ];
  3074. // 逐个尝试匹配模式
  3075. foreach ($patterns as $pattern) {
  3076. if (preg_match($pattern, $prompt, $matches)) {
  3077. $number = trim($matches[1]);
  3078. // 如果是中文数字,转换为阿拉伯数字
  3079. if (isset($chineseNumbers[$number])) {
  3080. return $chineseNumbers[$number];
  3081. }
  3082. // 如果是阿拉伯数字,直接返回
  3083. if (is_numeric($number)) {
  3084. $episodeNum = intval($number);
  3085. // 合理性检查:集数应该在1-100之间
  3086. if ($episodeNum >= 1 && $episodeNum <= 100) {
  3087. return $episodeNum;
  3088. }
  3089. }
  3090. }
  3091. }
  3092. return null;
  3093. }
  3094. }