DeepSeekService.php 182 KB

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