DeepSeekService.php 284 KB

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