DeepSeekService.php 220 KB

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