DeepSeekService.php 288 KB

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