DeepSeekService.php 329 KB

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