DeepSeekService.php 264 KB

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