DeepSeekService.php 363 KB

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