DeepSeekService.php 728 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. protected $aiImageGenerationService;
  29. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  30. $this->aiImageGenerationService = $aiImageGenerationService;
  31. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  32. $this->api_key = env('DEEPSEEK_API_KEY');
  33. $this->headers = [
  34. 'Authorization' => 'Bearer '.$this->api_key,
  35. 'Content-Type' => 'application/json; charset=UTF-8'
  36. ];
  37. // 火山引擎模型列表
  38. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  39. // GPT文本模型列表
  40. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  41. $this->sys_message = [
  42. 'role' => 'system',
  43. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  44. 强制要求:\n
  45. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  46. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  47. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  48. 普通要求:\n
  49. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  50. 2.<分集剧本>的要求如下:
  51.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  52.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  53.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  54.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  55. \n\n
  56. 示例如下:\n
  57. ###剧本名:西昆仑
  58. ###故事梗概
  59. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  60. ###剧本亮点
  61. 亮点1:绝境奇药,生死一线
  62. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  63. 亮点2:结拜兄妹,化解尴尬
  64. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  65. 亮点3:纤发夺命,情愫暗涌
  66. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  67. ###人物关系
  68. 阿雪与梁萧之间存在兄妹之情。
  69. ###核心矛盾
  70. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  71. ###主体列表
  72. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  73. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  74. 阴阳球:天地异宝,能化生精气,救人于危难。
  75. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  76. ###美术风格
  77. 基础画风风格词:厚涂古风
  78. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  79. ###场景列表
  80. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  81. ###分集剧本
  82. ##分集01
  83. 第1集: 第一集的标题
  84. 场景描述:地点、时间、场景
  85. 运镜:固定近距离
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 第2集: 第二集的标题
  94. 场景描述:地点、时间、场景
  95. 运镜:固定近距离
  96. 出场角色:男主、女主
  97. 台词内容:
  98. 女主: 女主对话
  99. 男主:男主对话
  100. 女主: 女主对话
  101. 男主: 男主对话"
  102. ];
  103. }
  104. /**
  105. * 通用文生文方法 - 支持多模型流式输出和图片输入
  106. *
  107. * @param array $data 请求参数
  108. * @return \Generator 返回生成器,用于流式输出
  109. */
  110. public function generateText($data) {
  111. // 获取请求参数
  112. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  113. $messages = getProp($data, 'messages', []);
  114. $systemPrompt = getProp($data, 'system_prompt', '');
  115. $prompt = getProp($data, 'prompt', '');
  116. $images = getProp($data, 'images', []); // 支持多张图片
  117. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  118. // 如果没有提供messages,则根据system_prompt、content和images构建
  119. if (empty($messages)) {
  120. $messages = [];
  121. // 添加系统提示词
  122. if (!empty($systemPrompt)) {
  123. $messages[] = [
  124. 'role' => 'system',
  125. 'content' => $systemPrompt
  126. ];
  127. }
  128. // 构建用户消息内容(支持文本+图片)
  129. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  130. $userMessage = [
  131. 'role' => 'user',
  132. 'content' => []
  133. ];
  134. // 添加文本内容
  135. if (!empty($prompt)) {
  136. $userMessage['content'][] = [
  137. 'type' => 'text',
  138. 'text' => $prompt
  139. ];
  140. }
  141. // 处理上传的图片文件
  142. if (!empty($images)) {
  143. if (!is_array($images)) {
  144. $images = [$images];
  145. }
  146. foreach ($images as $image) {
  147. $imageBase64 = $this->processImageToBase64($image);
  148. if ($imageBase64) {
  149. $userMessage['content'][] = [
  150. 'type' => 'image_url',
  151. 'image_url' => [
  152. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  153. ]
  154. ];
  155. }
  156. }
  157. }
  158. // 处理图片URL
  159. if (!empty($imageUrls)) {
  160. if (!is_array($imageUrls)) {
  161. $imageUrls = [$imageUrls];
  162. }
  163. foreach ($imageUrls as $url) {
  164. if (!empty($url)) {
  165. $userMessage['content'][] = [
  166. 'type' => 'image_url',
  167. 'image_url' => [
  168. 'url' => $url
  169. ]
  170. ];
  171. }
  172. }
  173. }
  174. // 如果只有文本内容,简化为字符串格式
  175. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  176. $userMessage['content'] = $userMessage['content'][0]['text'];
  177. }
  178. $messages[] = $userMessage;
  179. }
  180. }
  181. // 验证messages不为空
  182. if (empty($messages)) {
  183. Utils::throwError('20003:请提供有效的对话内容');
  184. }
  185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  188. if ($model === 'deepseek-chat') {
  189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  190. $model = 'deepseek-v4-flash';
  191. $thinkingMode = 'disabled';
  192. } elseif ($model === 'deepseek-reasoner') {
  193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  194. $model = 'deepseek-v4-flash';
  195. $thinkingMode = 'enabled';
  196. }
  197. // 构建请求参数
  198. $post_data = [
  199. 'model' => $model,
  200. 'messages' => $messages,
  201. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  202. 'temperature' => getProp($data, 'temperature', 1),
  203. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  204. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  205. 'thinking' => ['type' => $thinkingMode],
  206. 'stream' => true // 启用流式输出
  207. ];
  208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  209. // 添加可选参数
  210. if (isset($data['top_p'])) {
  211. $post_data['top_p'] = $data['top_p'];
  212. }
  213. if (isset($data['response_format'])) {
  214. $post_data['response_format'] = $data['response_format'];
  215. }
  216. // 根据模型类型选择调用方法
  217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  218. // DeepSeek 官方模型使用 DeepSeek API
  219. return $this->deepSeekStreamResponse($post_data);
  220. } else if (in_array($model, $this->gpt_text_models)) {
  221. // GPT 模型使用 TokenRouter API
  222. return $this->gpt54StreamResponse($post_data);
  223. } else if (in_array($model, $this->valid_text_models)) {
  224. // 火山引擎支持的模型使用火山引擎 API
  225. return $this->volcEngineChatCompletion($post_data);
  226. } else {
  227. Utils::throwError('20003:不支持的模型: ' . $model);
  228. }
  229. }
  230. public function createGenerateText($data) {
  231. $file = getProp($data, 'file');
  232. $uid = Site::getUid();
  233. $cpid = Site::getCpid();
  234. if (!$file) {
  235. Utils::throwError('20003:请上传文件');
  236. }
  237. // 提取文件内容
  238. $content = $this->extractFileContent($file);
  239. if (!$content) {
  240. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  241. }
  242. // 获取原始文件名(不含扩展名)作为script_name
  243. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  244. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  245. // 字节安全剥离,不依赖服务器locale设置
  246. $originalName = $file->getClientOriginalName();
  247. $extension = $file->getClientOriginalExtension();
  248. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  249. ? substr($originalName, 0, -strlen($extension) - 1)
  250. : $originalName;
  251. if ($script_name === '') {
  252. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  253. }
  254. // 如果同一用户的剧本名存在则提示
  255. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  256. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  257. }
  258. // 插入数据到mp_scripts表
  259. $script_id = DB::table('mp_scripts')->insertGetId([
  260. 'script_name' => $script_name,
  261. 'user_id' => $uid,
  262. 'cpid' => $cpid,
  263. 'content' => $content,
  264. 'created_at' => date('Y-m-d H:i:s'),
  265. 'updated_at' => date('Y-m-d H:i:s')
  266. ]);
  267. return [
  268. 'script_id' => $script_id,
  269. 'script_name' => $script_name
  270. ];
  271. }
  272. /**
  273. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  274. *
  275. * @param array $data 请求参数
  276. * @return array 返回结果数组
  277. */
  278. public function newGenerateText($data) {
  279. // 获取请求参数
  280. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  281. $messages = getProp($data, 'messages', []);
  282. $systemPrompt = getProp($data, 'system_prompt', '');
  283. $prompt = getProp($data, 'prompt', '');
  284. $images = getProp($data, 'images', []); // 支持多张图片
  285. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  286. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  287. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  288. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  289. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  290. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  291. $generateTaskId = 0;
  292. if ($script_id > 0) {
  293. $uid = Site::getUid();
  294. $existingTask = DB::table('mp_script_generate_tasks')
  295. ->where('uid', $uid)
  296. ->where('script_id', $script_id)
  297. ->orderByDesc('id')
  298. ->first();
  299. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  300. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  301. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  302. }
  303. }
  304. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  305. $originalContent = '';
  306. if ($script_id > 0) {
  307. $script = DB::table('mp_scripts')
  308. ->where('id', $script_id)
  309. ->where('is_deleted', 0)
  310. ->first();
  311. if (!$script) {
  312. Utils::throwError('20003:剧本不存在或已删除');
  313. }
  314. $originalContent = $script->content ?? '';
  315. if (empty($originalContent)) {
  316. Utils::throwError('20003:剧本内容为空');
  317. }
  318. // 将剧本内容添加到提示词前面
  319. if (!empty($originalContent)) {
  320. if (!empty($prompt)) {
  321. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  322. } else {
  323. $prompt = "原文内容:\n" . $originalContent;
  324. }
  325. }
  326. }
  327. // 新增: 如果提供了template_id,从数据库获取template_prompt
  328. if ($templateId > 0) {
  329. $template = DB::table('mp_prompt_templates')
  330. ->where('id', $templateId)
  331. ->where('is_deleted', 0)
  332. ->first();
  333. if (!$template) {
  334. Utils::throwError('20003:模板不存在或已删除');
  335. }
  336. $templatePrompt = $template->template_prompt ?? '';
  337. // 将模板提示词和用户输入的prompt组合
  338. // 模板为准,用户输入作为补充要求
  339. if (!empty($templatePrompt)) {
  340. if (!empty($prompt)) {
  341. $prompt = $templatePrompt . "\n\n" . $prompt;
  342. } else {
  343. $prompt = $templatePrompt;
  344. }
  345. }
  346. }
  347. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  348. if (empty($messages)) {
  349. $messages = [];
  350. // 添加系统提示词
  351. if (!empty($systemPrompt)) {
  352. $messages[] = [
  353. 'role' => 'system',
  354. 'content' => $systemPrompt
  355. ];
  356. }
  357. // 构建用户消息内容(支持文本+图片)
  358. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  359. $userMessage = [
  360. 'role' => 'user',
  361. 'content' => []
  362. ];
  363. // 添加文本内容
  364. if (!empty($prompt)) {
  365. $userMessage['content'][] = [
  366. 'type' => 'text',
  367. 'text' => $prompt
  368. ];
  369. }
  370. // 处理上传的图片文件
  371. if (!empty($images)) {
  372. if (!is_array($images)) {
  373. $images = [$images];
  374. }
  375. foreach ($images as $image) {
  376. $imageBase64 = $this->processImageToBase64($image);
  377. if ($imageBase64) {
  378. $userMessage['content'][] = [
  379. 'type' => 'image_url',
  380. 'image_url' => [
  381. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  382. ]
  383. ];
  384. }
  385. }
  386. }
  387. // 处理图片URL
  388. if (!empty($imageUrls)) {
  389. if (!is_array($imageUrls)) {
  390. $imageUrls = [$imageUrls];
  391. }
  392. foreach ($imageUrls as $url) {
  393. if (!empty($url)) {
  394. $userMessage['content'][] = [
  395. 'type' => 'image_url',
  396. 'image_url' => [
  397. 'url' => $url
  398. ]
  399. ];
  400. }
  401. }
  402. }
  403. // 如果只有文本内容,简化为字符串格式
  404. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  405. $userMessage['content'] = $userMessage['content'][0]['text'];
  406. }
  407. $messages[] = $userMessage;
  408. }
  409. }
  410. // 验证messages不为空
  411. if (empty($messages)) {
  412. Utils::throwError('20003:请提供有效的对话内容');
  413. }
  414. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  415. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  416. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  417. if ($model === 'deepseek-chat') {
  418. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  419. $model = 'deepseek-v4-flash';
  420. $thinkingMode = 'disabled';
  421. } elseif ($model === 'deepseek-reasoner') {
  422. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  423. $model = 'deepseek-v4-flash';
  424. $thinkingMode = 'enabled';
  425. }
  426. // 构建请求参数(非流式)
  427. $post_data = [
  428. 'model' => $model,
  429. 'messages' => $messages,
  430. 'temperature' => getProp($data, 'temperature', 1),
  431. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  432. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  433. 'thinking' => ['type' => $thinkingMode],
  434. 'stream' => false // 非流式输出
  435. ];
  436. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  437. // 添加可选参数
  438. if (isset($data['top_p'])) {
  439. $post_data['top_p'] = $data['top_p'];
  440. }
  441. // 新增: 根据response_format设置响应格式
  442. if ($responseFormat === 'json') {
  443. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  444. $hasJsonKeyword = false;
  445. foreach ($post_data['messages'] as $message) {
  446. if (isset($message['content'])) {
  447. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  448. if (stripos($content, 'json') !== false) {
  449. $hasJsonKeyword = true;
  450. break;
  451. }
  452. }
  453. }
  454. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  455. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  456. if (!$hasJsonKeyword) {
  457. $lastMessageIndex = count($post_data['messages']) - 1;
  458. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  459. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  460. // 如果content是字符串,直接追加
  461. if (is_string($lastContent)) {
  462. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  463. }
  464. // 如果content是数组(包含文本和图片),在文本部分追加
  465. else if (is_array($lastContent)) {
  466. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  467. if ($contentPart['type'] === 'text') {
  468. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  469. break;
  470. }
  471. }
  472. }
  473. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  474. }
  475. }
  476. // 设置response_format参数(所有支持的模型)
  477. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  478. // DeepSeek模型
  479. $post_data['response_format'] = ['type' => 'json_object'];
  480. } else if (in_array($model, $this->gpt_text_models)) {
  481. // GPT模型
  482. $post_data['response_format'] = ['type' => 'json_object'];
  483. } else if (in_array($model, $this->valid_text_models)) {
  484. // 火山引擎模型
  485. $post_data['response_format'] = ['type' => 'json_object'];
  486. }
  487. }
  488. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  489. if ($script_id > 0) {
  490. $uid = Site::getUid();
  491. // 创建新的生成任务
  492. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  493. 'uid' => $uid,
  494. 'script_id' => $script_id,
  495. 'sequence' => $sequence,
  496. 'status' => 'processing',
  497. 'prompt' => getProp($data, 'prompt', ''),
  498. 'started_at' => date('Y-m-d H:i:s'),
  499. 'created_at' => date('Y-m-d H:i:s'),
  500. 'updated_at' => date('Y-m-d H:i:s')
  501. ]);
  502. }
  503. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  504. try {
  505. $aiResult = null;
  506. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  507. // DeepSeek 官方模型使用现有的 chatOnly 方法
  508. $result = $this->chatOnly($post_data);
  509. // 记录实际使用的模型
  510. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  511. $aiResult = [
  512. 'content' => $result['fullContent'],
  513. 'reasoning_content' => $result['fullReasoningContent'],
  514. 'usage' => $result['usage'],
  515. 'model' => $model,
  516. 'finish_reason' => 'stop'
  517. ];
  518. } else if (in_array($model, $this->gpt_text_models)) {
  519. // GPT 模型使用现有的 gpt54ChatOnly 方法
  520. $result = $this->gpt54ChatOnly($post_data);
  521. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  522. $aiResult = [
  523. 'content' => $result['fullContent'],
  524. 'reasoning_content' => '',
  525. 'usage' => $result['usage'],
  526. 'model' => $model,
  527. 'finish_reason' => 'stop'
  528. ];
  529. } else if (in_array($model, $this->valid_text_models)) {
  530. // 火山引擎支持的模型使用火山引擎 API(非流式)
  531. $post_data['stream'] = false;
  532. $result = $this->volcEngineChatCompletion($post_data);
  533. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  534. 'requested_model' => $model,
  535. 'result_keys' => array_keys($result),
  536. 'has_fullContent' => isset($result['fullContent']),
  537. 'has_content' => isset($result['content'])
  538. ]);
  539. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  540. $aiResult = [
  541. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  542. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  543. 'usage' => $result['usage'] ?? [],
  544. 'model' => $model,
  545. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  546. ];
  547. } else {
  548. Utils::throwError('20003:不支持的模型: ' . $model);
  549. }
  550. } catch (\Exception $e) {
  551. // 生成失败,更新任务状态
  552. if ($generateTaskId) {
  553. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  554. 'status' => 'failed',
  555. 'error_message' => $e->getMessage(),
  556. 'completed_at' => date('Y-m-d H:i:s'),
  557. 'updated_at' => date('Y-m-d H:i:s')
  558. ]);
  559. }
  560. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  561. }
  562. // 生成成功,更新任务状态
  563. if ($generateTaskId && $aiResult) {
  564. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  565. 'status' => 'success',
  566. 'result' => getProp($aiResult, 'content', ''),
  567. 'completed_at' => date('Y-m-d H:i:s'),
  568. 'updated_at' => date('Y-m-d H:i:s')
  569. ]);
  570. $aiResult['generate_task_id'] = $generateTaskId;
  571. }
  572. // 新增: 如果提供了script_id,保存对话记录
  573. if ($script_id > 0 && $aiResult) {
  574. try {
  575. $uid = Site::getUid();
  576. $now = now();
  577. // 获取用户原始的prompt(不包含剧本内容)
  578. $originalPrompt = getProp($data, 'prompt', '');
  579. $recordsToInsert = [
  580. [
  581. 'uid' => $uid,
  582. 'script_id' => $script_id,
  583. 'sequence' => $sequence,
  584. 'role' => 'user',
  585. 'content' => $originalPrompt,
  586. 'created_at' => $now,
  587. 'updated_at' => $now,
  588. ],
  589. [
  590. 'uid' => $uid,
  591. 'script_id' => $script_id,
  592. 'sequence' => $sequence,
  593. 'role' => 'assistant',
  594. 'content' => $aiResult['content'],
  595. 'created_at' => $now,
  596. 'updated_at' => $now,
  597. ]
  598. ];
  599. DB::table('mp_script_records')->insert($recordsToInsert);
  600. // 获取刚插入的记录ID(假设按插入顺序返回)
  601. $insertedRecords = DB::table('mp_script_records')
  602. ->where('uid', $uid)
  603. ->where('script_id', $script_id)
  604. ->where('sequence', $sequence)
  605. ->orderBy('id', 'desc')
  606. ->limit(2)
  607. ->get()
  608. ->map(function ($record) {
  609. return [
  610. 'rid' => $record->id,
  611. 'script_id' => $record->script_id,
  612. 'sequence' => $record->sequence,
  613. 'role' => $record->role,
  614. 'content' => $record->content,
  615. 'created_at' => $record->created_at,
  616. ];
  617. })
  618. ->reverse()
  619. ->values()
  620. ->toArray();
  621. // 将记录信息添加到返回结果中
  622. $aiResult['records'] = $insertedRecords;
  623. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  624. } catch (\Exception $e) {
  625. // 记录错误但不影响主流程
  626. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  627. }
  628. }
  629. return $aiResult;
  630. }
  631. /**
  632. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  633. *
  634. * @param array $data
  635. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  636. */
  637. public function getScriptGenerateTasks($data) {
  638. $uid = Site::getUid();
  639. return DB::table('mp_script_generate_tasks as t')
  640. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  641. ->where('t.uid', $uid)
  642. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  643. ->orderByDesc('t.id')
  644. ->paginate(15);
  645. }
  646. public function saveScriptChatHistory($data) {
  647. $uid = Site::getUid();
  648. $rid = getProp($data, 'rid');
  649. $script_id = getProp($data, 'script_id');
  650. $sequence = getProp($data, 'sequence', 0);
  651. $content = getProp($data, 'content');
  652. if (!$rid) {
  653. Utils::throwError('20003:请选择对话记录ID');
  654. }
  655. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  656. if (!$record) {
  657. Utils::throwError('20003:对话记录不存在');
  658. }
  659. if (!$script_id) {
  660. Utils::throwError('20003:请选择剧本');
  661. }
  662. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  663. if (!$script) {
  664. Utils::throwError('20003:剧本不存在');
  665. }
  666. // 批量插入数据
  667. return DB::table('mp_script_records')->where('id', $rid)->update([
  668. 'content' => $content,
  669. 'updated_at' => date('Y-m-d H:i:s')
  670. ]);
  671. }
  672. /**
  673. * 获取剧本的历史对话记录
  674. *
  675. * @param array $data 请求参数
  676. * @return array 返回历史记录数组
  677. */
  678. public function getScriptChatHistory($data) {
  679. $uid = Site::getUid();
  680. $script_id = getProp($data, 'script_id');
  681. $rid = getProp($data, 'rid');
  682. $sequence = getProp($data, 'sequence', null);
  683. if (!$script_id) {
  684. Utils::throwError('20003:请提供剧本ID');
  685. }
  686. // 验证剧本是否存在
  687. $script = DB::table('mp_scripts')
  688. ->where('id', $script_id)
  689. ->where('is_deleted', 0)
  690. ->first();
  691. if (!$script) {
  692. Utils::throwError('20003:剧本不存在');
  693. }
  694. // 构建查询
  695. $query = DB::table('mp_script_records')
  696. ->where('script_id', $script_id);
  697. // ->where('uid', $uid);
  698. // 如果提供了 sequence,则过滤指定剧集
  699. if ($sequence !== null) {
  700. $query->where('sequence', $sequence);
  701. }
  702. // 记录ID筛选
  703. if ($rid) {
  704. $query->where('id', $rid);
  705. }
  706. // 查询记录并按 id 正序排序
  707. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  708. ->orderBy('created_at', 'asc')
  709. ->orderBy('id', 'asc')
  710. ->get()
  711. ->map(function ($record) {
  712. return [
  713. 'rid' => $record->id,
  714. 'script_id' => $record->script_id,
  715. 'sequence' => $record->sequence,
  716. 'role' => $record->role,
  717. 'content' => $record->content,
  718. 'products' => $record->products ? json_decode($record->products) : [],
  719. 'created_at' => $record->created_at,
  720. ];
  721. })
  722. ->toArray();
  723. return $records;
  724. }
  725. /**
  726. * 处理图片转换为base64
  727. *
  728. * @param mixed $image 图片文件对象或文件路径
  729. * @return string|null base64编码的图片数据
  730. */
  731. private function processImageToBase64($image) {
  732. try {
  733. // 获取文件路径
  734. if (is_string($image)) {
  735. $filePath = $image;
  736. } else {
  737. // Laravel UploadedFile 对象
  738. $filePath = $image->getRealPath();
  739. }
  740. if (!file_exists($filePath)) {
  741. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  742. return null;
  743. }
  744. // 验证是否为图片文件
  745. $imageInfo = @getimagesize($filePath);
  746. if ($imageInfo === false) {
  747. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  748. return null;
  749. }
  750. // 读取图片并转换为base64
  751. $imageData = file_get_contents($filePath);
  752. $base64Image = base64_encode($imageData);
  753. dLog('deepseek')->info('图片转换成功', [
  754. 'size' => strlen($imageData),
  755. 'type' => $imageInfo['mime']
  756. ]);
  757. return $base64Image;
  758. } catch (\Exception $e) {
  759. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  760. return null;
  761. }
  762. }
  763. private function getArtStylePromptMappings($art_style='')
  764. {
  765. $arr = [
  766. '唯美真人风格' => [
  767. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  768. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  769. ],
  770. '真人古风风格' => [
  771. 'aliases' => ['真人古风风格', '真人古风'],
  772. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  773. ],
  774. '日系动漫风格' => [
  775. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  776. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  777. ],
  778. '国漫风格' => [
  779. 'aliases' => ['国漫风格', '国漫'],
  780. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  781. ],
  782. 'Q版卡通风格' => [
  783. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  784. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  785. ],
  786. '简约扁平风格' => [
  787. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  788. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  789. ],
  790. '武侠风格' => [
  791. 'aliases' => ['武侠风格', '武侠'],
  792. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  793. ],
  794. '古风仙侠风格' => [
  795. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  796. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  797. ],
  798. '新中式水墨风格' => [
  799. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  800. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  801. ],
  802. '写实插画风格' => [
  803. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  804. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  805. ],
  806. '3D卡通风格' => [
  807. 'aliases' => ['3D卡通风格', '3D卡通'],
  808. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  809. ],
  810. '条漫风格' => [
  811. 'aliases' => ['条漫风格', '条漫'],
  812. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  813. ],
  814. '赛博朋克风格' => [
  815. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  816. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  817. ],
  818. '暗黑悬疑风格' => [
  819. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  820. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  821. ],
  822. '治愈清新风格' => [
  823. 'aliases' => ['治愈清新风格', '治愈清新'],
  824. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  825. ],
  826. '3D真人风格' => [
  827. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  828. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  829. ],
  830. ];
  831. if($art_style) {
  832. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  833. }
  834. return $arr;
  835. $arr = [
  836. '唯美真人风格' => [
  837. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  838. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  839. 2. 色彩色调
  840. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  841. 3. 画质精度
  842. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  843. 4. 画面观感
  844. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  845. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  846. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  847. ],
  848. '真人古风风格' => [
  849. 'aliases' => ['真人古风风格', '真人古风'],
  850. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  851. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  852. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  853. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  854. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  855. ],
  856. '日系动漫风格' => [
  857. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  858. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  859. 正向提示词(中文)
  860. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  861. 必须遵守规则
  862. • 全程保持日系动漫风格,不混入其他画风
  863. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  864. • 画面适配所选画面比例,构图居中,主体突出
  865. • 线条干净、色彩统一,不杂乱、不突兀
  866. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  867. ],
  868. '国漫风格' => [
  869. 'aliases' => ['国漫风格', '国漫'],
  870. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  871. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  872. 必须遵守规则
  873. • 严格保持国漫画风,不串风格、不混画风
  874. • 角色形象统一,不随意改变五官、身材、服饰
  875. • 画面构图稳定,适合漫剧叙事展示
  876. • 色调统一,不出现脏色、杂色
  877. 禁止/避免词汇
  878. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  879. ],
  880. 'Q版卡通风格' => [
  881. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  882. 'prompt' => "风格说明
  883. 头大身小,造型可爱圆润,简约干净
  884. 正向提示词(中文)
  885. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  886. 必须遵守规则
  887. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  888. • 角色造型统一,表情可爱,不诡异
  889. • 画面简洁清爽,无多余复杂元素
  890. • 色彩明亮柔和,不刺眼
  891. 禁止/避免词汇
  892. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  893. ],
  894. '简约扁平风格' => [
  895. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  896. 'prompt' => "风格说明
  897. 色块简洁、无复杂渐变,现代极简风
  898. 正向提示词(中文)
  899. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  900. 必须遵守规则
  901. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  902. • 构图简洁,主体突出,无多余装饰
  903. • 色彩统一、干净,不杂乱
  904. 禁止/避免词汇
  905. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  906. ],
  907. '武侠风格' => [
  908. 'aliases' => ['武侠风格', '武侠'],
  909. 'prompt' => "风格说明
  910. 江湖气息,线条硬朗,动作感强
  911. 正向提示词(中文)
  912. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  913. 必须遵守规则
  914. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  915. • 角色形象、服饰、身材比例统一
  916. • 画面动作自然,不扭曲、不畸形
  917. 禁止/避免词汇
  918. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  919. ],
  920. '古风仙侠风格' => [
  921. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  922. 'prompt' => "风格说明
  923. 飘逸汉服、云雾仙气、唯美空灵
  924. 正向提示词(中文)
  925. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  926. 必须遵守规则
  927. • 保持古风仙侠统一画风,不混入现代、科幻元素
  928. • 角色服饰、发型、形象前后一致
  929. • 场景仙气飘逸,色调清雅统一
  930. • 画面唯美柔和,不阴暗、不诡异
  931. 禁止/避免词汇
  932. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  933. ],
  934. '新中式水墨风格' => [
  935. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  936. 'prompt' => "风格说明
  937. 淡墨渲染,毛笔笔触,留白意境
  938. 正向提示词(中文)
  939. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  940. 必须遵守规则
  941. • 严格保持水墨质感,不混入厚涂、写实、卡通
  942. • 色调淡雅统一,不浓艳杂乱
  943. • 画面干净有意境,不堆砌元素
  944. 禁止/避免词汇
  945. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  946. ],
  947. '写实插画风格' => [
  948. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  949. 'prompt' => "风格说明
  950. 接近真人比例,光影真实,质感细腻
  951. 正向提示词(中文)
  952. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  953. 必须遵守规则
  954. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  955. • 角色五官、身材、服饰高度统一
  956. • 画面清晰、光影自然、不扭曲
  957. 禁止/避免词汇
  958. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  959. ],
  960. '3D卡通风格' => [
  961. 'aliases' => ['3D卡通风格', '3D卡通'],
  962. 'prompt' => "风格说明
  963. 3D建模质感,柔和渲染,圆润可爱
  964. 正向提示词(中文)
  965. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  966. 必须遵守规则
  967. • 保持3D卡通统一质感,不出现2D杂乱线条
  968. • 角色模型、比例、形象前后一致
  969. • 画面干净,不模糊、不穿模
  970. 禁止/避免词汇
  971. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  972. ],
  973. '条漫风格' => [
  974. 'aliases' => ['条漫风格', '条漫'],
  975. 'prompt' => "风格说明
  976. 纵向分镜,上下滑动阅读,轻量化
  977. 正向提示词(中文)
  978. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  979. 必须遵守规则
  980. • 保持条漫纵向阅读逻辑,构图简洁
  981. • 画风统一,不混写实、3D、水墨
  982. • 画面干净,不杂乱
  983. 禁止/避免词汇
  984. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  985. ],
  986. '赛博朋克风格' => [
  987. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  988. 'prompt' => "风格说明
  989. 霓虹灯光、未来都市、暗色调、科技机械
  990. 正向提示词(中文)
  991. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  992. 必须遵守规则
  993. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  994. • 色调以暗调+霓虹为主,色彩统一
  995. • 画面科技感强,不杂乱
  996. 禁止/避免词汇
  997. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  998. ],
  999. '暗黑悬疑风格' => [
  1000. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1001. 'prompt' => "风格说明
  1002. 低饱和、冷色调、阴影重、神秘压抑
  1003. 正向提示词(中文)
  1004. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1005. 必须遵守规则
  1006. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1007. • 画面氛围压抑神秘,但不低俗、不血腥
  1008. • 角色形象统一,不崩坏
  1009. 禁止/避免词汇
  1010. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1011. ],
  1012. '治愈清新风格' => [
  1013. 'aliases' => ['治愈清新风格', '治愈清新'],
  1014. 'prompt' => "风格说明
  1015. 马卡龙色系、柔光、温暖干净
  1016. 正向提示词(中文)
  1017. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1018. 必须遵守规则
  1019. • 保持治愈清新统一色调,不阴暗、不诡异
  1020. • 画面柔和干净,无杂乱元素
  1021. • 角色形象柔和可爱,不狰狞
  1022. 禁止/避免词汇
  1023. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1024. ],
  1025. ];
  1026. return $arr;
  1027. }
  1028. public function getArtStylePromptByInput($inputArtStyle): string
  1029. {
  1030. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1031. if ($normalizedInput === '') {
  1032. return '';
  1033. }
  1034. return $this->getArtStylePromptMappings($normalizedInput);
  1035. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1036. // foreach ($mapping['aliases'] as $alias) {
  1037. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1038. // if ($normalizedAlias === '') {
  1039. // continue;
  1040. // }
  1041. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1042. // return $mapping['prompt'];
  1043. // }
  1044. // }
  1045. // }
  1046. return '';
  1047. }
  1048. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1049. $stylePrefixes = [
  1050. '唯美真人风格' => [
  1051. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1052. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1053. ],
  1054. '真人古风风格' => [
  1055. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1056. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1057. ],
  1058. '日系动漫风格' => [
  1059. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1060. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1061. ],
  1062. '国漫风格' => [
  1063. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1064. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1065. ],
  1066. 'Q版卡通风格' => [
  1067. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1068. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1069. ],
  1070. '简约扁平风格' => [
  1071. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1072. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1073. ],
  1074. '武侠风格' => [
  1075. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1076. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1077. ],
  1078. '古风仙侠风格' => [
  1079. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1080. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1081. ],
  1082. '新中式水墨风格' => [
  1083. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1084. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1085. ],
  1086. '写实插画风格' => [
  1087. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1088. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1089. ],
  1090. '3D卡通风格' => [
  1091. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1092. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1093. ],
  1094. '条漫风格' => [
  1095. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1096. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1097. ],
  1098. '赛博朋克风格' => [
  1099. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1100. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1101. ],
  1102. '暗黑悬疑风格' => [
  1103. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1104. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1105. ],
  1106. '治愈清新风格' => [
  1107. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1108. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1109. ]
  1110. ];
  1111. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1112. }
  1113. private function normalizeArtStyleInput($value): string
  1114. {
  1115. $value = trim((string)$value);
  1116. if ($value === '') {
  1117. return '';
  1118. }
  1119. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1120. return mb_strtolower($value, 'UTF-8');
  1121. }
  1122. private function replaceArtStyleSection(string $content, string $artStyle): string
  1123. {
  1124. if ($content === '' || $artStyle === '') {
  1125. return $content;
  1126. }
  1127. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1128. if (!preg_match($pattern, $content)) {
  1129. return $content;
  1130. }
  1131. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1132. }
  1133. /**
  1134. * DeepSeek流式输出处理方法
  1135. *
  1136. * @param array $post_data DeepSeek API请求参数
  1137. * @return \Generator 返回生成器,用于流式输出
  1138. */
  1139. private function deepSeekStreamResponse($post_data) {
  1140. // 设置最大输出tokens
  1141. $post_data['max_tokens'] = 300000;
  1142. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1143. $response = $client->post($this->url, [
  1144. 'json' => $post_data,
  1145. 'headers' => $this->headers,
  1146. 'stream' => true // 启用流式响应
  1147. ]);
  1148. $body = $response->getBody();
  1149. $fullContent = '';
  1150. $fullReasoningContent = '';
  1151. $usage = [];
  1152. $buffer = '';
  1153. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1154. // 逐行读取流式响应
  1155. while (!$body->eof()) {
  1156. $chunk = $body->read(1024); // 每次读取 1KB
  1157. $buffer .= $chunk;
  1158. // 按行分割
  1159. $lines = explode("\n", $buffer);
  1160. // 保留最后一个不完整的行
  1161. $buffer = array_pop($lines);
  1162. foreach ($lines as $line) {
  1163. $line = trim($line);
  1164. // 跳过空行
  1165. if (empty($line)) {
  1166. continue;
  1167. }
  1168. // 检查是否是 SSE 数据行
  1169. if (strpos($line, 'data: ') !== 0) {
  1170. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1171. continue;
  1172. }
  1173. $data = substr($line, 6); // 移除 "data: " 前缀
  1174. if ($data === '[DONE]') {
  1175. dLog('deepseek')->info('收到结束标记');
  1176. break 2; // 跳出两层循环
  1177. }
  1178. try {
  1179. $json = json_decode($data, true);
  1180. if (json_last_error() !== JSON_ERROR_NONE) {
  1181. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1182. continue;
  1183. }
  1184. if (isset($json['choices'][0]['delta'])) {
  1185. $delta = $json['choices'][0]['delta'];
  1186. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1187. if (isset($delta['reasoning_content'])) {
  1188. $fullReasoningContent .= $delta['reasoning_content'];
  1189. yield [
  1190. 'type' => 'reasoning',
  1191. 'content' => $delta['reasoning_content'],
  1192. 'full_reasoning' => $fullReasoningContent
  1193. ];
  1194. }
  1195. // 处理最终回答内容
  1196. if (isset($delta['content'])) {
  1197. $fullContent .= $delta['content'];
  1198. yield [
  1199. 'type' => 'content',
  1200. 'content' => $delta['content'],
  1201. ];
  1202. }
  1203. }
  1204. // 获取使用统计信息
  1205. if (isset($json['usage'])) {
  1206. $usage = $json['usage'];
  1207. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1208. }
  1209. } catch (\Exception $e) {
  1210. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1211. continue;
  1212. }
  1213. }
  1214. }
  1215. dLog('deepseek')->info('流式读取完成', [
  1216. 'content_length' => strlen($fullContent),
  1217. 'reasoning_length' => strlen($fullReasoningContent)
  1218. ]);
  1219. yield [
  1220. 'type' => 'done',
  1221. 'full_content' => $fullContent,
  1222. 'full_reasoning' => $fullReasoningContent,
  1223. 'usage' => $usage
  1224. ];
  1225. }
  1226. /**
  1227. * GPT 重试次数(env 可配置,默认 5 次)
  1228. */
  1229. private function gptRetryTimes()
  1230. {
  1231. return (int)env('GPT_RETRY_TIMES', 5);
  1232. }
  1233. /**
  1234. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1235. */
  1236. private function gptRetryInterval()
  1237. {
  1238. return (int)env('GPT_RETRY_INTERVAL', 10);
  1239. }
  1240. /**
  1241. * 判断 GPT 请求异常是否可重试
  1242. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1243. */
  1244. private function isGptRetryableException(\Exception $e)
  1245. {
  1246. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1247. return false;
  1248. }
  1249. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1250. $status = $e->getResponse()->getStatusCode();
  1251. return $status >= 500 || $status == 429;
  1252. }
  1253. return true;
  1254. }
  1255. /**
  1256. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1257. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1258. */
  1259. private function checkGptServiceAvailable()
  1260. {
  1261. $apiKey = env('GPT_54_API_KEY');
  1262. if (empty($apiKey)) {
  1263. return false;
  1264. }
  1265. try {
  1266. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1267. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1268. 'headers' => [
  1269. 'Authorization' => 'Bearer ' . $apiKey,
  1270. 'Content-Type' => 'application/json'
  1271. ]
  1272. ]);
  1273. $status = $response->getStatusCode();
  1274. return $status < 500 && $status != 429;
  1275. } catch (\Exception $e) {
  1276. return false;
  1277. }
  1278. }
  1279. /**
  1280. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1281. * 全部失败抛出友好错误
  1282. */
  1283. private function ensureGptServiceAvailable()
  1284. {
  1285. $maxRetries = $this->gptRetryTimes();
  1286. $interval = $this->gptRetryInterval();
  1287. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1288. if ($this->checkGptServiceAvailable()) {
  1289. return;
  1290. }
  1291. if ($attempt < $maxRetries) {
  1292. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1293. 'retry' => $attempt + 1,
  1294. 'max_retries' => $maxRetries
  1295. ]);
  1296. sleep($interval);
  1297. }
  1298. }
  1299. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1300. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1301. 'max_retries' => $maxRetries,
  1302. 'interval' => $interval
  1303. ]);
  1304. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1305. }
  1306. /**
  1307. * GPT 流式输出处理方法
  1308. *
  1309. * @param array $post_data GPT API请求参数
  1310. * @return \Generator 返回生成器,用于流式输出
  1311. */
  1312. private function gpt54StreamResponse($post_data) {
  1313. $apiKey = env('GPT_54_API_KEY');
  1314. if (empty($apiKey)) {
  1315. Utils::throwError('20003:GPT API Key未配置');
  1316. }
  1317. // 先探活,服务不可用时自动重试
  1318. $this->ensureGptServiceAvailable();
  1319. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1320. $headers = [
  1321. 'Authorization' => 'Bearer ' . $apiKey,
  1322. 'Content-Type' => 'application/json'
  1323. ];
  1324. // 移除 thinking 参数,GPT-5.4 不支持
  1325. if (isset($post_data['thinking'])) {
  1326. unset($post_data['thinking']);
  1327. }
  1328. if (isset($post_data['reasoning_effort'])) {
  1329. unset($post_data['reasoning_effort']);
  1330. }
  1331. $post_data['max_completion_tokens'] = 100000;
  1332. $maxRetries = $this->gptRetryTimes();
  1333. $interval = $this->gptRetryInterval();
  1334. $attempt = 0;
  1335. while (true) {
  1336. $fullContent = '';
  1337. $usage = [];
  1338. $buffer = '';
  1339. try {
  1340. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1341. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1342. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1343. 'json' => $post_data,
  1344. 'headers' => $headers,
  1345. 'stream' => true // 启用流式响应
  1346. ]);
  1347. $body = $response->getBody();
  1348. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1349. // 逐行读取流式响应
  1350. while (!$body->eof()) {
  1351. $chunk = $body->read(1024); // 每次读取 1KB
  1352. $buffer .= $chunk;
  1353. // 按行分割
  1354. $lines = explode("\n", $buffer);
  1355. // 保留最后一个不完整的行
  1356. $buffer = array_pop($lines);
  1357. foreach ($lines as $line) {
  1358. $line = trim($line);
  1359. // 跳过空行
  1360. if (empty($line)) {
  1361. continue;
  1362. }
  1363. // 检查是否是 SSE 数据行
  1364. if (strpos($line, 'data: ') !== 0) {
  1365. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1366. continue;
  1367. }
  1368. $data = substr($line, 6); // 移除 "data: " 前缀
  1369. if ($data === '[DONE]') {
  1370. dLog('deepseek')->info('收到结束标记');
  1371. break 2; // 跳出 foreach 和流读取循环
  1372. }
  1373. try {
  1374. $json = json_decode($data, true);
  1375. if (json_last_error() !== JSON_ERROR_NONE) {
  1376. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1377. continue;
  1378. }
  1379. if (isset($json['choices'][0]['delta'])) {
  1380. $delta = $json['choices'][0]['delta'];
  1381. // 处理回答内容
  1382. if (isset($delta['content'])) {
  1383. $fullContent .= $delta['content'];
  1384. yield [
  1385. 'type' => 'content',
  1386. 'content' => $delta['content'],
  1387. ];
  1388. }
  1389. }
  1390. // 获取使用统计信息
  1391. if (isset($json['usage'])) {
  1392. $usage = $json['usage'];
  1393. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1394. }
  1395. } catch (\Exception $e) {
  1396. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1397. continue;
  1398. }
  1399. }
  1400. }
  1401. dLog('deepseek')->info('流式读取完成', [
  1402. 'content_length' => strlen($fullContent)
  1403. ]);
  1404. yield [
  1405. 'type' => 'done',
  1406. 'full_content' => $fullContent,
  1407. 'full_reasoning' => '',
  1408. 'usage' => $usage
  1409. ];
  1410. return;
  1411. } catch (\Exception $e) {
  1412. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1413. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1414. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1415. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1416. throw $e;
  1417. }
  1418. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1419. 'retry' => $attempt + 1,
  1420. 'max_retries' => $maxRetries,
  1421. 'error' => $e->getMessage()
  1422. ]);
  1423. sleep($interval);
  1424. $attempt++;
  1425. }
  1426. }
  1427. }
  1428. // 与推理模型对话
  1429. public function chatWithReasoner($data) {
  1430. $content = getProp($data, 'content');
  1431. $model = getProp($data, 'model', 'r1');
  1432. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1433. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1434. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1435. if ($model == 'r1') {
  1436. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1437. $thinkingMode = 'disabled';
  1438. } else {
  1439. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1440. $thinkingMode = 'disabled';
  1441. }
  1442. // 获取可选情感(根据音色可支持情感选)
  1443. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1444. $emotion_list = [];
  1445. foreach ($timbre_emotion as $emotion) {
  1446. $tmp = explode(',', $emotion);
  1447. $emotion_list = array_merge($emotion_list, $tmp);
  1448. }
  1449. $emotion_list = array_unique($emotion_list);
  1450. $emotion_str = implode('、', $emotion_list);
  1451. // // 获取可选情感
  1452. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1453. // $emotion_str = implode('、', $emotion_list);
  1454. // 是否启用情感
  1455. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1456. if ($enable_emotion) {
  1457. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1458. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1459. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1460. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1461. }else {
  1462. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1463. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1464. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1465. }
  1466. $messages = [
  1467. [
  1468. 'role' => 'system',
  1469. 'content' => $sys_content
  1470. ],
  1471. [
  1472. 'role' => 'user',
  1473. 'content' => $content
  1474. ]
  1475. ];
  1476. $post_data = [
  1477. 'model' => $model,
  1478. 'messages' => $messages,
  1479. // 'max_tokens' => 8192,
  1480. 'temperature' => 1,
  1481. 'frequency_penalty' => 0,
  1482. 'presence_penalty' => 0,
  1483. 'thinking' => ['type' => $thinkingMode],
  1484. 'response_format' => [
  1485. 'type' => 'text'
  1486. ],
  1487. 'stream' => false
  1488. ];
  1489. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1490. // 根据模型类型选择调用方法
  1491. $fullContent = '';
  1492. $usage = [];
  1493. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1494. // DeepSeek 官方模型使用 DeepSeek API
  1495. $chatResult = $this->chatOnly($post_data);
  1496. } else if (in_array($model, $this->gpt_text_models)) {
  1497. // GPT-5.4 模型使用 TokenRouter API
  1498. $chatResult = $this->gpt54ChatOnly($post_data);
  1499. } else {
  1500. // 其他模型使用火山引擎API
  1501. $chatResult = $this->volcEngineChatCompletion($post_data);
  1502. }
  1503. if (is_array($chatResult)) {
  1504. $fullContent = $chatResult['fullContent'];
  1505. $usage = $chatResult['usage'];
  1506. }
  1507. // 处理获取到的剧本数据
  1508. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1509. $result = [
  1510. 'origin_content' => $fullContent,
  1511. 'roles' => getProp($script_content, 'roles'),
  1512. 'words' => getProp($script_content, 'words'),
  1513. ];
  1514. return $result;
  1515. }
  1516. public function resetParagraphAudio($data) {
  1517. $bid = getProp($data, 'bid');
  1518. $cid = getProp($data, 'cid');
  1519. $version_id = getProp($data, 'version_id');
  1520. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1521. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1522. 'generate_status' => '待制作',
  1523. 'updated_at' => date('Y-m-d H:i:s')
  1524. ]);
  1525. }
  1526. public function saveParagraphAudio($data) {
  1527. $bid = getProp($data, 'bid');
  1528. $cid = getProp($data, 'cid');
  1529. $version_id = getProp($data, 'version_id');
  1530. $sequence = getProp($data, 'sequence');
  1531. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1532. // 获取所有情感
  1533. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1534. $emotion_list = array_flip($emotion_list);
  1535. // 获取音色支持情感
  1536. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1537. $timbre_emotion = explode(',', $timbre_emotion);
  1538. $emotion = getProp($data, 'emotion');
  1539. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1540. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1541. $list = [
  1542. 'bid' => $bid,
  1543. 'cid' => $cid,
  1544. 'version_id' => $version_id,
  1545. 'sequence' => $sequence,
  1546. 'role' => getProp($data, 'role'),
  1547. 'gender' => getProp($data, 'gender'),
  1548. 'text' => trim(getProp($data, 'text')),
  1549. 'emotion' => $emotion,
  1550. 'emotion_type' => $emotion_type,
  1551. 'voice_type' => getProp($data, 'voice_type'),
  1552. 'voice_name' => getProp($data, 'voice_name'),
  1553. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1554. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1555. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1556. 'pitch' => getProp($data, 'pitch', 0),
  1557. // 'paragraph_audio_url' => '',
  1558. 'generate_status' => '制作中',
  1559. 'error_msg' => '',
  1560. 'updated_at' => date('Y-m-d H:i:s')
  1561. ];
  1562. $continue = false;
  1563. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1564. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1565. $list['generate_status'] = '制作成功';
  1566. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1567. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1568. $continue = true;
  1569. }
  1570. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1571. if ($id) {
  1572. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1573. }else {
  1574. $list['created_at'] = date('Y-m-d H:i:s');
  1575. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1576. $boolen = $id ? true : false;
  1577. }
  1578. // 如果更新成功则加入查询队列
  1579. if ($boolen) {
  1580. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1581. Redis::sadd($redis_key, $id);
  1582. }
  1583. if ($boolen && !$continue) {
  1584. $boolen = false;
  1585. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1586. // 根据ID通过API通知合成音频
  1587. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1588. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1589. $response = $result->getBody()->getContents();
  1590. $response_arr = json_decode($response, true);
  1591. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1592. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1593. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1594. Utils::throwError('20003:通知火山生成段落音频失败');
  1595. }
  1596. $boolen = true;
  1597. }
  1598. return $boolen;
  1599. }
  1600. public function insertAudioEffect($data) {
  1601. $audio_id = getProp($data, 'audio_id');
  1602. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1603. $bid = getProp($chapter_audio, 'bid');
  1604. $version_id = getProp($chapter_audio, 'version_id');
  1605. $cid = getProp($chapter_audio, 'cid');
  1606. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1607. $audio_effect_json = getProp($data, 'audio_effect_json');
  1608. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1609. try {
  1610. DB::beginTransaction();
  1611. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1612. if (!$count) {
  1613. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1614. }else {
  1615. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1616. }
  1617. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1618. 'audio_effect_status' => '添加中',
  1619. 'audio_effect_json' => $audio_effect_json,
  1620. 'updated_at' => date('Y-m-d H:i:s')
  1621. ]);
  1622. if (!$boolen1) {
  1623. DB::rollBack();
  1624. Utils::throwError('20003:更新生成数据失败');
  1625. }
  1626. $id = DB::table('mp_audio_tasks')->insertGetId([
  1627. 'audio_id' => $audio_id,
  1628. 'generate_status' => '执行中',
  1629. 'generate_json' => json_encode([], 256),
  1630. 'bid' => $bid,
  1631. 'book_name' => getProp($chapter_audio, 'book_name'),
  1632. 'version_id' => $version_id,
  1633. 'version_name' => getProp($chapter_audio, 'version_name'),
  1634. 'cid' => $cid,
  1635. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1636. 'task_name' => $task_name,
  1637. 'created_at' => date('Y-m-d H:i:s'),
  1638. 'updated_at' => date('Y-m-d H:i:s')
  1639. ]);
  1640. if (!$id) {
  1641. DB::rollBack();
  1642. Utils::throwError('20003:创建任务失败');
  1643. }
  1644. }catch (\Exception $e) {
  1645. DB::rollBack();
  1646. Utils::throwError('20003:'.$e->getMessage());
  1647. }
  1648. DB::commit();
  1649. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1650. // 根据ID通过API通知合成音频
  1651. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1652. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1653. $response = $result->getBody()->getContents();
  1654. $response_arr = json_decode($response, true);
  1655. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1656. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1657. Log::info('通知火山插入音效失败: '.$error_msg);
  1658. Utils::throwError('20003:通知火山插入音效失败');
  1659. }
  1660. return true;
  1661. }
  1662. public function insertBgm($data) {
  1663. $audio_id = getProp($data, 'audio_id');
  1664. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1665. $bid = getProp($chapter_audio, 'bid');
  1666. $version_id = getProp($chapter_audio, 'version_id');
  1667. $cid = getProp($chapter_audio, 'cid');
  1668. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1669. $bgm_json = getProp($data, 'bgm_json');
  1670. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1671. if (!$bgm_json) {
  1672. $bgm_json = getProp($data, 'audio_effect_json');
  1673. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1674. }
  1675. try {
  1676. DB::beginTransaction();
  1677. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1678. if (!$count) {
  1679. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1680. }else {
  1681. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1682. }
  1683. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1684. 'bgm_status' => '添加中',
  1685. 'bgm_json' => $bgm_json,
  1686. 'updated_at' => date('Y-m-d H:i:s')
  1687. ]);
  1688. if (!$boolen1) {
  1689. DB::rollBack();
  1690. Utils::throwError('20003:更新生成数据失败');
  1691. }
  1692. $id = DB::table('mp_audio_tasks')->insertGetId([
  1693. 'audio_id' => $audio_id,
  1694. 'generate_status' => '执行中',
  1695. 'generate_json' => json_encode([], 256),
  1696. 'bid' => $bid,
  1697. 'book_name' => getProp($chapter_audio, 'book_name'),
  1698. 'version_id' => $version_id,
  1699. 'version_name' => getProp($chapter_audio, 'version_name'),
  1700. 'cid' => $cid,
  1701. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1702. 'task_name' => $task_name,
  1703. 'created_at' => date('Y-m-d H:i:s'),
  1704. 'updated_at' => date('Y-m-d H:i:s')
  1705. ]);
  1706. if (!$id) {
  1707. DB::rollBack();
  1708. Utils::throwError('20003:创建任务失败');
  1709. }
  1710. }catch (\Exception $e) {
  1711. DB::rollBack();
  1712. Utils::throwError('20003:'.$e->getMessage());
  1713. }
  1714. DB::commit();
  1715. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1716. // 根据ID通过API通知合成音频
  1717. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1718. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1719. $response = $result->getBody()->getContents();
  1720. $response_arr = json_decode($response, true);
  1721. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1722. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1723. Log::info('通知火山插入bgm失败: '.$error_msg);
  1724. Utils::throwError('20003:通知火山插入bgm失败');
  1725. }
  1726. return true;
  1727. }
  1728. public function getParagraphAudios($data) {
  1729. $bid = getProp($data, 'bid');
  1730. $cid = getProp($data, 'cid');
  1731. $version_id = getProp($data, 'version_id');
  1732. $sequence = getProp($data, 'sequence');
  1733. // 获取已生成的音频
  1734. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1735. if ($sequence) $query->where('sequence', $sequence);
  1736. $paragraph_audios = $query->orderBy('sequence')->get();
  1737. $result = [];
  1738. foreach($paragraph_audios as $item) {
  1739. $result[] = [
  1740. 'sequence' => getProp($item, 'sequence'),
  1741. 'role' => getProp($item, 'role'),
  1742. 'gender' => getProp($item, 'gender'),
  1743. 'text' => trim(getProp($item, 'text')),
  1744. 'emotion' => getProp($item, 'emotion'),
  1745. 'emotion_type' => getProp($item, 'emotion_type'),
  1746. 'voice_type' => getProp($item, 'voice_type'),
  1747. 'voice_name' => getProp($item, 'voice_name'),
  1748. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1749. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1750. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1751. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1752. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1753. ];
  1754. }
  1755. return $result;
  1756. }
  1757. // 新增合成任务
  1758. public function addGenerateTask($data) {
  1759. $bid = getProp($data, 'bid');
  1760. $cid = getProp($data, 'cid');
  1761. $version_id = getProp($data, 'version_id');
  1762. $generate_json = getProp($data, 'generate_json');
  1763. // 获取已生成的音频
  1764. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1765. $paragraph_list = [];
  1766. foreach($paragraph_audios as $item) {
  1767. $paragraph_list[getProp($item, 'sequence')] = [
  1768. 'role' => getProp($item, 'role'),
  1769. 'gender' => getProp($item, 'gender'),
  1770. 'text' => trim(getProp($item, 'text')),
  1771. 'emotion' => getProp($item, 'emotion'),
  1772. 'emotion_type' => getProp($item, 'emotion_type'),
  1773. 'voice_type' => getProp($item, 'voice_type'),
  1774. 'voice_name' => getProp($item, 'voice_name'),
  1775. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1776. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1777. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1778. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1779. ];
  1780. }
  1781. // 更新角色-音色信息
  1782. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1783. $existed_role_info = json_decode($existed_role_info, true);
  1784. if (!$existed_role_info) $existed_role_info = [];
  1785. // 获取情感信息
  1786. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1787. $emotion_list = array_flip($emotion_list);
  1788. // 获取音色对应情感组
  1789. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1790. $timbre_emotion_list = [];
  1791. foreach($timbre_emotions as $item) {
  1792. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1793. }
  1794. // 构造生成音频的json
  1795. $words = json_decode($generate_json, true);
  1796. // 最终合成前的参数组
  1797. $mp_chapter_paragraph_audios = [];
  1798. $sequence = 1;
  1799. $complete_paragraph_sequences = [];
  1800. foreach($words as &$word) {
  1801. 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:参数格式有误');
  1802. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1803. $role = getProp($word, 'role');
  1804. $word['gender'] = (int)$word['gender'];
  1805. // 判断音色对应情感是否支持,不支持则调整为中性
  1806. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1807. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1808. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1809. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1810. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1811. }else {
  1812. $word['emotion'] = '中性';
  1813. $word['emotion_type'] = 'neutral';
  1814. }
  1815. $existed_role_info[$role] = [
  1816. 'timbre_type' => $word['voice_type'],
  1817. 'timbre_name' => $word['voice_name'],
  1818. 'emotion' => $word['emotion'],
  1819. 'emotion_type' => $word['emotion_type'],
  1820. 'speed_ratio' => $word['speed_ratio'],
  1821. 'loudness_ratio'=> $word['loudness_ratio'],
  1822. 'emotion_scale' => $word['emotion_scale'],
  1823. 'pitch' => $word['pitch']
  1824. ];
  1825. $word['paragraph_audio_url'] = '';
  1826. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1827. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1828. // 如果音频存在并且参数都未改变则使用已生成的音频
  1829. if (getProp($paragraph, 'paragraph_audio_url')) {
  1830. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1831. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1832. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1833. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1834. // {
  1835. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1836. // }
  1837. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1838. }
  1839. $tmp = $word;
  1840. // 组装章节分句音频数据
  1841. // $tmp['sequence'] = getProp($word, 'sequence');
  1842. // $tmp['text'] = getProp($word, 'text');
  1843. // $tmp['emotion'] = getProp($word, 'emotion');
  1844. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1845. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1846. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1847. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1848. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1849. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1850. $tmp['bid'] = $bid;
  1851. $tmp['version_id'] = $version_id;
  1852. $tmp['cid'] = $cid;
  1853. $tmp['sequence'] = $sequence;
  1854. $tmp['created_at'] = date('Y-m-d H:i:s');
  1855. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1856. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1857. $mp_chapter_paragraph_audios[] = $tmp;
  1858. $complete_paragraph_sequences[] = $sequence;
  1859. $sequence++;
  1860. }
  1861. $generate_json = json_encode($words, 256);
  1862. // 判断是否有未生成字幕的段落
  1863. $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();
  1864. if ($no_subtitle_sequences) {
  1865. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1866. }
  1867. try {
  1868. DB::beginTransaction();
  1869. $role_info = json_encode($existed_role_info, 256);
  1870. $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')]);
  1871. if (!$boolen) {
  1872. DB::rollBack();
  1873. Utils::throwError('20003:更新角色信息失败');
  1874. }
  1875. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1876. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1877. if (!$count) {
  1878. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1879. }else {
  1880. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1881. }
  1882. $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')]);
  1883. if (!$boolen1) {
  1884. DB::rollBack();
  1885. Utils::throwError('20003:更新生成数据失败');
  1886. }
  1887. $id = DB::table('mp_audio_tasks')->insertGetId([
  1888. 'audio_id' => getProp($chapter_audio, 'id'),
  1889. 'generate_status' => '执行中',
  1890. 'generate_json' => $generate_json,
  1891. 'bid' => $bid,
  1892. 'book_name' => getProp($chapter_audio, 'book_name'),
  1893. 'version_id' => $version_id,
  1894. 'version_name' => getProp($chapter_audio, 'version_name'),
  1895. 'cid' => $cid,
  1896. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1897. 'task_name' => $task_name,
  1898. 'created_at' => date('Y-m-d H:i:s'),
  1899. 'updated_at' => date('Y-m-d H:i:s')
  1900. ]);
  1901. if (!$id) {
  1902. DB::rollBack();
  1903. Utils::throwError('20003:创建任务失败');
  1904. }
  1905. // 删除不在段落序号范围内的其他数据
  1906. if ($complete_paragraph_sequences) {
  1907. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1908. }
  1909. // // 删除章节分句音频数据并重新插入
  1910. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1911. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1912. // if (!$boolen3) {
  1913. // DB::rollBack();
  1914. // Utils::throwError('20003:更新章节分句音频失败');
  1915. // }
  1916. } catch (\Exception $e) {
  1917. DB::rollBack();
  1918. Utils::throwError('20003:'.$e->getMessage());
  1919. }
  1920. DB::commit();
  1921. // 通知火山生成音频
  1922. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1923. // 根据ID通过API通知合成音频
  1924. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1925. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1926. $response = $result->getBody()->getContents();
  1927. $response_arr = json_decode($response, true);
  1928. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1929. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1930. Log::info('通知火山生成音频失败: '.$error_msg);
  1931. Utils::throwError('20003:通知火山生成音频失败');
  1932. }
  1933. return true;
  1934. }
  1935. public function timbreList($data) {
  1936. $gender = getProp($data, 'gender');
  1937. $timbre_name = getProp($data, 'voice_name');
  1938. $category_id = getProp($data, 'category_id');
  1939. $age_stage = getProp($data, 'age_stage');
  1940. $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');
  1941. if ($gender) {
  1942. $query->where('gender', $gender);
  1943. }
  1944. if ($timbre_name) {
  1945. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1946. }
  1947. if ($category_id) {
  1948. $query->where(function ($query) use ($category_id) {
  1949. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1950. });
  1951. }
  1952. if ($age_stage) {
  1953. $query->where('age_stage', $age_stage);
  1954. }
  1955. $list = $query->get()->map(function ($value) {
  1956. $value = (array)$value;
  1957. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1958. return $value;
  1959. })->toArray();
  1960. return $list;
  1961. }
  1962. // 生成火山临时token
  1963. public function setStsToken() {
  1964. // ************* 配置参数 *************
  1965. $method = 'GET';
  1966. $service = 'sts';
  1967. $host = 'open.volcengineapi.com';
  1968. $region = env('VOLC_REGION');
  1969. $endpoint = 'https://open.volcengineapi.com';
  1970. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1971. $access_key = env('VOLC_AK');
  1972. $secret_key = env('VOLC_SK');
  1973. // 获取缓存中的token,如果没有则请求接口
  1974. $token = Redis::get('volc_sts_token');
  1975. if (!$token) {
  1976. // 查询参数
  1977. $query_parameters = [
  1978. 'Action' => 'AssumeRole',
  1979. 'RoleSessionName' => 'user@zw',
  1980. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1981. 'Version' => '2018-01-01'
  1982. ];
  1983. // 生成URL编码的查询字符串
  1984. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1985. // 获取签名头信息
  1986. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1987. // 构建完整URL
  1988. $request_url = $endpoint . '?' . $request_parameters;
  1989. $client = new Client(['verify' => false]);
  1990. $response = $client->get($request_url, ['headers' => $headers]);
  1991. $response_arr = json_decode($response->getBody()->getContents(), true);
  1992. $result = [
  1993. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1994. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1995. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1996. 'Region' => env('VOLC_REGION'),
  1997. 'Endpoint' => env('VOLC_END_POINT'),
  1998. 'Bucket' => env('VOLC_BUCKET'),
  1999. ];
  2000. // 缓存token
  2001. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2002. return $result;
  2003. } else {
  2004. return json_decode($token, true);
  2005. }
  2006. // $response = $response['Response'];
  2007. // $access_key = $response['Credentials']['AccessKeyId'];
  2008. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2009. // $security_token = $response['Credentials']['SecurityToken'];
  2010. // $expiration = $response['Credentials']['Expiration'];
  2011. // dd($response_arr);
  2012. }
  2013. public function emotionGroups($data) {
  2014. $id = getProp($data, 'group_id');
  2015. $group_name = getProp($data, 'group_name');
  2016. $voice_type = getProp($data, 'voice_type');
  2017. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2018. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2019. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2020. if ($group_name) {
  2021. $query->where('group_name', 'like', "%{$group_name}%");
  2022. }
  2023. if ($id) {
  2024. $query->where('id', $id);
  2025. }
  2026. if ($voice_type) {
  2027. $query->where('voice_type', $voice_type);
  2028. }
  2029. return $query->orderBy('id')->get()->map(function ($value) {
  2030. return (array)$value;
  2031. })->toArray();
  2032. }
  2033. private function sign($key, $msg) {
  2034. return hash_hmac('sha256', $msg, $key, true);
  2035. }
  2036. // 生成签名密钥
  2037. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2038. $kDate = $this->sign($key, $dateStamp);
  2039. $kRegion = $this->sign($kDate, $regionName);
  2040. $kService = $this->sign($kRegion, $serviceName);
  2041. $kSigning = $this->sign($kService, 'request');
  2042. return $kSigning;
  2043. }
  2044. // 获取签名头信息
  2045. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2046. $contenttype = 'application/x-www-form-urlencoded';
  2047. $accept = 'application/json';
  2048. // 获取当前UTC时间
  2049. $t = new DateTime('now', new DateTimeZone('UTC'));
  2050. $xdate = $t->format('Ymd\THis\Z');
  2051. $datestamp = $t->format('Ymd');
  2052. // 1. 拼接规范请求串
  2053. $canonical_uri = '/';
  2054. $canonical_querystring = $request_parameters;
  2055. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2056. $signed_headers = 'content-type;host;x-date';
  2057. // 空请求体的SHA256哈希
  2058. $payload_hash = hash('sha256', '');
  2059. $canonical_request = implode("\n", [
  2060. $method,
  2061. $canonical_uri,
  2062. $canonical_querystring,
  2063. $canonical_headers,
  2064. $signed_headers,
  2065. $payload_hash
  2066. ]);
  2067. // 2. 拼接待签名字符串
  2068. $algorithm = 'HMAC-SHA256';
  2069. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2070. $hashed_canonical_request = hash('sha256', $canonical_request);
  2071. $string_to_sign = implode("\n", [
  2072. $algorithm,
  2073. $xdate,
  2074. $credential_scope,
  2075. $hashed_canonical_request
  2076. ]);
  2077. // 3. 计算签名
  2078. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2079. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2080. // 4. 添加签名到请求头
  2081. $authorization_header = sprintf(
  2082. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2083. $algorithm,
  2084. $access_key,
  2085. $credential_scope,
  2086. $signed_headers,
  2087. $signature
  2088. );
  2089. return [
  2090. 'Accept' => $accept,
  2091. 'Content-Type' => $contenttype,
  2092. 'X-Date' => $xdate,
  2093. 'Authorization' => $authorization_header
  2094. ];
  2095. }
  2096. // 文字合成语音(火山引擎)
  2097. public function tts($data) {
  2098. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2099. $headers = [
  2100. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2101. 'Content-Type' => 'application/json; charset=UTF-8'
  2102. ];
  2103. $post_data = [
  2104. 'app' => [
  2105. 'appid' => env('VOLC_APPID'),
  2106. 'token' => env('VOLC_TOKEN'),
  2107. 'cluster' => 'volcano_tts'
  2108. ],
  2109. 'user' => [
  2110. 'uid' => 'mp_audio'
  2111. ],
  2112. // 'audio' => [
  2113. // 'voice_type' =>
  2114. // ],
  2115. ];
  2116. }
  2117. public function scriptList($data) {
  2118. $uid = Site::getUid();
  2119. $script_id = getProp($data, 'script_id');
  2120. $script_name = getProp($data, 'script_name');
  2121. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2122. if ($script_id) {
  2123. $query->where('id', $script_id);
  2124. }
  2125. if ($script_name) {
  2126. $query->where('script_name', 'like', "%{$script_name}%");
  2127. }
  2128. return $query->orderBy('created_at', 'desc')->paginate(12);
  2129. }
  2130. public function scripts($data) {
  2131. $uid = Site::getUid();
  2132. $script_id = getProp($data, 'script_id');
  2133. $script_name = getProp($data, 'script_name');
  2134. $is_products = getProp($data, 'is_products');
  2135. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2136. if ($script_id) {
  2137. $query->where('id', $script_id);
  2138. }
  2139. if ($is_products !== '') {
  2140. $query->where('is_products', $is_products);
  2141. }
  2142. if ($script_name) {
  2143. $query->where('script_name', 'like', "%{$script_name}%");
  2144. }
  2145. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2146. return (array)$value;
  2147. })->toArray();
  2148. }
  2149. public function scriptInfo($data) {
  2150. $uid = Site::getUid();
  2151. $script_id = getProp($data, 'script_id');
  2152. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2153. // ->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();
  2154. ->selectRaw('id as script_id, script_name')->first();
  2155. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2156. $script = (array)$script;
  2157. // 获取分集组信息
  2158. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2159. ->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')
  2160. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2161. $value = (array)$value;
  2162. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2163. return (array)$value;
  2164. })->toArray();
  2165. $script['group'] = $groups;
  2166. return $script;
  2167. }
  2168. public function createScript($data) {
  2169. $script_name = getProp($data, 'script_name');
  2170. $uid = Site::getUid(); // 获取当前用户ID
  2171. $cpid = Site::getCpid(); // 获取当前公司组ID
  2172. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2173. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2174. $script_name .= '_'.date('YmdHis');
  2175. }
  2176. return DB::table('mp_scripts')->insertGetId([
  2177. 'script_name' => $script_name,
  2178. 'user_id' => $uid,
  2179. 'cpid' => $cpid,
  2180. 'created_at' => date('Y-m-d H:i:s'),
  2181. 'updated_at' => date('Y-m-d H:i:s')
  2182. ]);
  2183. }
  2184. public function editScript($data) {
  2185. $script_id = getProp($data, 'script_id');
  2186. $script_name = getProp($data, 'script_name');
  2187. $uid = Site::getUid(); // 获取当前用户ID
  2188. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2189. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2190. if ($id && (int)$id !== (int)$script_id) {
  2191. $script_name .= '_'.date('YmdHis');
  2192. }
  2193. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2194. 'script_name' => $script_name,
  2195. 'updated_at' => date('Y-m-d H:i:s')
  2196. ]);
  2197. }
  2198. public function delScript($data) {
  2199. $script_id = getProp($data, 'script_id');
  2200. $uid = Site::getUid(); // 获取当前用户ID
  2201. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2202. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2203. 'is_deleted' => 1,
  2204. 'updated_at' => date('Y-m-d H:i:s')
  2205. ]);
  2206. }
  2207. public function createEpisode($data) {
  2208. $script_id = getProp($data, 'script_id');
  2209. $group_name = getProp($data, 'group_name');
  2210. $remark = getProp($data, 'remark');
  2211. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2212. $uid = Site::getUid(); // 获取当前用户ID
  2213. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2214. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2215. $group_name .= '_'.date('YmdHis');
  2216. }
  2217. return DB::table('mp_script_episode_group')->insertGetId([
  2218. 'script_id' => $script_id,
  2219. 'group_name' => $group_name,
  2220. 'user_id' => $uid,
  2221. 'remark' => $remark,
  2222. 'created_at' => date('Y-m-d H:i:s'),
  2223. 'updated_at' => date('Y-m-d H:i:s')
  2224. ]);
  2225. }
  2226. public function editEpisode($data) {
  2227. $group_id = getProp($data, 'group_id');
  2228. $start_episode_number = getProp($data, 'start_episode_number');
  2229. $end_episode_number = getProp($data, 'end_episode_number');
  2230. $group_name = getProp($data, 'group_name');
  2231. $uid = Site::getUid(); // 获取当前用户ID
  2232. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2233. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2234. if ($id && (int)$id !== (int)$group_id) {
  2235. $group_name .= '_'.date('YmdHis');
  2236. }
  2237. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2238. 'group_name' => $group_name,
  2239. 'start_episode_number' => $start_episode_number,
  2240. 'end_episode_number' => $end_episode_number,
  2241. 'updated_at' => date('Y-m-d H:i:s')
  2242. ]);
  2243. }
  2244. public function delEpisode($data) {
  2245. $group_id = getProp($data, 'group_id');
  2246. $uid = Site::getUid(); // 获取当前用户ID
  2247. if (!$group_id) Utils::throwError('20003:请选择分集');
  2248. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2249. 'is_deleted' => 1,
  2250. 'updated_at' => date('Y-m-d H:i:s')
  2251. ]);
  2252. }
  2253. /**
  2254. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2255. *
  2256. * @param array $data 包含以下参数:
  2257. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2258. * - question: 用户问题(可选)
  2259. * - model: 使用的模型(r1 或 v3,默认 v3)
  2260. * @return \Generator 返回生成器,用于流式输出
  2261. */
  2262. public function generateEpisodes($data) {
  2263. $script_id = getProp($data, 'script_id');
  2264. $group_id = getProp($data, 'group_id');
  2265. // $file = getProp($data, 'file');
  2266. $file = '';
  2267. $content = getProp($data, 'content', '');
  2268. // $bid = getProp($data, 'bid', 0);
  2269. $bid = 0;
  2270. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2271. if (!$group) {
  2272. Utils::throwError('20003:剧本分集不存在');
  2273. }
  2274. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2275. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2276. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2277. $prompt = getProp($data, 'prompt');
  2278. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2279. $model = getProp($data, 'model');
  2280. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2281. Utils::throwError('20003:该模型不存在!');
  2282. }
  2283. // 检查是否存在重叠的剧集序号范围
  2284. $exists_groups = DB::table('mp_script_episode_group')
  2285. ->where('script_id', $script_id)
  2286. ->where('id', '<>', $group_id) // 排除当前组
  2287. ->where('is_deleted', 0)
  2288. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2289. // 检查新范围是否与现有范围重叠
  2290. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2291. // 新范围的开始在现有范围内
  2292. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2293. ->where('end_episode_number', '>=', $start_episode_sequence);
  2294. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2295. // 新范围的结束在现有范围内
  2296. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2297. ->where('end_episode_number', '>=', $end_episode_sequence);
  2298. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2299. // 新范围完全包含现有范围
  2300. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2301. ->where('end_episode_number', '<=', $end_episode_sequence);
  2302. });
  2303. })
  2304. ->select('start_episode_number', 'end_episode_number')
  2305. ->get();
  2306. if ($exists_groups->isNotEmpty()) {
  2307. $conflict_ranges = [];
  2308. foreach ($exists_groups as $group) {
  2309. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2310. }
  2311. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2312. }
  2313. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2314. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2315. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2316. if ($model === 'deepseek-chat') {
  2317. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2318. $model = 'deepseek-v4-flash';
  2319. $thinkingMode = 'disabled';
  2320. } elseif ($model === 'deepseek-reasoner') {
  2321. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2322. $model = 'deepseek-v4-flash';
  2323. $thinkingMode = 'enabled';
  2324. }
  2325. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2326. if (!$script) {
  2327. Utils::throwError('20003:剧本不存在');
  2328. }
  2329. $content = getProp($group, 'content');
  2330. if (!$file && !$content && !$bid) {
  2331. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2332. }
  2333. // 提取文件内容
  2334. if ($file) {
  2335. $content = $this->extractFileContent($file);
  2336. if (!$content) {
  2337. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2338. }
  2339. } elseif ($bid) {
  2340. $content = $this->getContentByBid($bid);
  2341. if (!$content) {
  2342. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2343. }
  2344. } elseif ($content) {
  2345. $content = filterContent($content);
  2346. } elseif ($prompt) {
  2347. $content = filterContent($prompt);
  2348. } else {
  2349. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2350. }
  2351. // 构建消息
  2352. $messages = [
  2353. $this->sys_message,
  2354. [
  2355. 'role' => 'user',
  2356. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2357. ]
  2358. ];
  2359. $post_data = [
  2360. 'model' => $model,
  2361. 'messages' => $messages,
  2362. // 'max_tokens' => 8192,
  2363. 'temperature' => 0.7,
  2364. 'frequency_penalty' => 0,
  2365. 'presence_penalty' => 0,
  2366. 'thinking' => ['type' => $thinkingMode],
  2367. 'response_format' => ['type' => 'text'],
  2368. 'stream' => true
  2369. ];
  2370. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2371. // 根据模型类型选择调用方法
  2372. $fullContent = '';
  2373. $fullReasoningContent = '';
  2374. $usage = [];
  2375. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2376. // DeepSeek 官方模型使用 DeepSeek API
  2377. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2378. } else if (in_array($model, $this->gpt_text_models)) {
  2379. // GPT-5.4 模型使用 TokenRouter API
  2380. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2381. } else {
  2382. // 其他模型使用火山引擎API
  2383. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2384. }
  2385. // 处理流式输出
  2386. foreach ($streamGenerator as $chunk) {
  2387. if (isset($chunk['type'])) {
  2388. if ($chunk['type'] === 'done') {
  2389. // 最终结果
  2390. $fullContent = $chunk['full_content'];
  2391. $fullReasoningContent = $chunk['full_reasoning'];
  2392. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2393. } else {
  2394. // 逐块yield数据
  2395. yield $chunk;
  2396. }
  2397. }
  2398. }
  2399. dLog('deepseek')->info('完整内容: '.$fullContent);
  2400. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2401. // 处理完整内容并返回最终结果
  2402. $script_arr = [];
  2403. if ($fullContent) {
  2404. $script_arr = extractScriptContent($fullContent);
  2405. }
  2406. logDB('deepseek', 'info', '解析内容', $script_arr);
  2407. if (!$script_arr['episodes']) {
  2408. Utils::throwError('20003:未生成剧本相关信息');
  2409. // yield [
  2410. // 'type' => 'done',
  2411. // 'script' => $script_arr,
  2412. // 'msg' => '未生成剧本相关信息',
  2413. // 'answer' => $fullContent,
  2414. // 'reasoning' => $fullReasoningContent,
  2415. // 'usage' => $usage
  2416. // ];
  2417. // return ;
  2418. }
  2419. try {
  2420. DB::beginTransaction();
  2421. // // 返回前保存剧本内容
  2422. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2423. // 'content' => $content,
  2424. // 'updated_at' => date('Y-m-d H:i:s')
  2425. // ]);
  2426. // if (!$boolen) {
  2427. // Utils::throwError('20003:保存剧本内容失败');
  2428. // }
  2429. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2430. // 'start_episode_number' => $start_episode_sequence,
  2431. // 'end_episode_number' => $end_episode_sequence,
  2432. // 'updated_at' => date('Y-m-d H:i:s')
  2433. // ]);
  2434. // if (!$boolen1) {
  2435. // Utils::throwError('20003:保存分集失败');
  2436. // }
  2437. $episode_content = '';
  2438. $episodes = [];
  2439. foreach ($script_arr['episodes'] as $item) {
  2440. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2441. // $episodes[] = [
  2442. // 'script_id' => $script_id,
  2443. // 'episode_number' => $item['episode_number'],
  2444. // 'episode_name' => $item['episode_name'],
  2445. // 'episode_content' => $item['episode_content'],
  2446. // 'created_at' => date('Y-m-d H:i:s'),
  2447. // 'updated_at' => date('Y-m-d H:i:s'),
  2448. // ];
  2449. }
  2450. if ($episode_content) {
  2451. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2452. 'episode_content' => $episode_content,
  2453. 'updated_at' => date('Y-m-d H:i:s')
  2454. ]);
  2455. if (!$boolen2) {
  2456. Utils::throwError('20003:保存分集内容失败');
  2457. }
  2458. }else {
  2459. Utils::throwError('20003:分集剧本解析失败');
  2460. }
  2461. }catch (\Exception $e) {
  2462. DB::rollBack();
  2463. Utils::throwError('20003:'.$e->getMessage());
  2464. }
  2465. DB::commit();
  2466. yield [
  2467. 'type' => 'done',
  2468. 'script' => $script_arr,
  2469. 'episode_content' => $episode_content,
  2470. 'answer' => $fullContent,
  2471. 'reasoning' => $fullReasoningContent,
  2472. 'usage' => $usage
  2473. ];
  2474. }
  2475. public function chatWithFileStream($data) {
  2476. $script_id = getProp($data, 'script_id');
  2477. $group_id = getProp($data, 'group_id');
  2478. $file = getProp($data, 'file');
  2479. $content = getProp($data, 'content', '');
  2480. $bid = getProp($data, 'bid', 0);
  2481. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2482. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2483. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2484. $prompt = getProp($data, 'prompt');
  2485. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2486. if (!empty($prompt)) {
  2487. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2488. }
  2489. $question = getProp($data, 'question', $baseQuestion);
  2490. $model = getProp($data, 'model');
  2491. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2492. Utils::throwError('20003:该模型不存在!');
  2493. }
  2494. // 检查是否存在重叠的剧集序号范围
  2495. $exists_groups = DB::table('mp_script_episode_group')
  2496. ->where('script_id', $script_id)
  2497. ->where('id', '<>', $group_id)
  2498. ->where('is_deleted', 0)
  2499. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2500. // 检查新范围是否与现有范围重叠
  2501. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2502. // 新范围的开始在现有范围内
  2503. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2504. ->where('end_episode_number', '>=', $start_episode_sequence);
  2505. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2506. // 新范围的结束在现有范围内
  2507. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2508. ->where('end_episode_number', '>=', $end_episode_sequence);
  2509. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2510. // 新范围完全包含现有范围
  2511. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2512. ->where('end_episode_number', '<=', $end_episode_sequence);
  2513. });
  2514. })
  2515. ->select('start_episode_number', 'end_episode_number')
  2516. ->get();
  2517. if ($exists_groups->isNotEmpty()) {
  2518. $conflict_ranges = [];
  2519. foreach ($exists_groups as $group) {
  2520. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2521. }
  2522. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2523. }
  2524. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2525. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2526. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2527. if ($model === 'deepseek-chat') {
  2528. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2529. $model = 'deepseek-v4-flash';
  2530. $thinkingMode = 'disabled';
  2531. } elseif ($model === 'deepseek-reasoner') {
  2532. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2533. $model = 'deepseek-v4-flash';
  2534. $thinkingMode = 'enabled';
  2535. }
  2536. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2537. if (!$script) {
  2538. Utils::throwError('20003:剧本不存在');
  2539. }
  2540. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2541. if (!$group) {
  2542. Utils::throwError('20003:剧本分集不存在');
  2543. }
  2544. if (!$file && !$content && !$bid) {
  2545. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2546. }
  2547. // 提取文件内容
  2548. if ($file) {
  2549. $content = $this->extractFileContent($file);
  2550. if (!$content) {
  2551. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2552. }
  2553. } elseif ($bid) {
  2554. $content = $this->getContentByBid($bid);
  2555. if (!$content) {
  2556. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2557. }
  2558. } elseif ($content) {
  2559. $content = filterContent($content);
  2560. } elseif ($prompt) {
  2561. $content = filterContent($prompt);
  2562. } else {
  2563. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2564. }
  2565. // 构建消息
  2566. $messages = [
  2567. [
  2568. 'role' => 'system',
  2569. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2570. 强制要求:\n
  2571. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2572. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2573. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2574. 普通要求:\n
  2575. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2576. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2577. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2578. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2579. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2580. 示例如下:\n
  2581. ###剧本名:西昆仑
  2582. ###故事梗概
  2583. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2584. ###剧本亮点
  2585. 亮点1:绝境奇药,生死一线
  2586. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2587. 亮点2:结拜兄妹,化解尴尬
  2588. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2589. 亮点3:纤发夺命,情愫暗涌
  2590. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2591. ###人物关系
  2592. 阿雪与梁萧之间存在兄妹之情。
  2593. ###核心矛盾
  2594. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2595. ###主体列表
  2596. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2597. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2598. 阴阳球:天地异宝,能化生精气,救人于危难。
  2599. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2600. ###美术风格
  2601. 基础画风风格词:厚涂古风
  2602. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2603. ###场景列表
  2604. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2605. [
  2606. 'role' => 'user',
  2607. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2608. ]
  2609. ];
  2610. $post_data = [
  2611. 'model' => $model,
  2612. 'messages' => $messages,
  2613. // 'max_tokens' => 8192,
  2614. 'temperature' => 0.7,
  2615. 'frequency_penalty' => 0,
  2616. 'presence_penalty' => 0,
  2617. 'thinking' => ['type' => $thinkingMode],
  2618. 'response_format' => ['type' => 'text'],
  2619. 'stream' => true
  2620. ];
  2621. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2622. // 根据模型类型选择调用方法
  2623. $fullContent = '';
  2624. $fullReasoningContent = '';
  2625. $usage = [];
  2626. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2627. // DeepSeek 官方模型使用 DeepSeek API
  2628. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2629. } else if (in_array($model, $this->gpt_text_models)) {
  2630. // GPT-5.4 模型使用 TokenRouter API
  2631. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2632. } else {
  2633. // 其他模型使用火山引擎API
  2634. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2635. }
  2636. // 处理流式输出
  2637. foreach ($streamGenerator as $chunk) {
  2638. if (isset($chunk['type'])) {
  2639. if ($chunk['type'] === 'done') {
  2640. // 最终结果
  2641. $fullContent = $chunk['full_content'];
  2642. $fullReasoningContent = $chunk['full_reasoning'];
  2643. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2644. } else {
  2645. // 逐块yield数据
  2646. yield $chunk;
  2647. }
  2648. }
  2649. }
  2650. dLog('deepseek')->info('完整内容: '.$fullContent);
  2651. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2652. // 处理完整内容并返回最终结果
  2653. $script_arr = [];
  2654. if ($fullContent) {
  2655. $script_arr = extractScriptContent($fullContent);
  2656. }
  2657. logDB('deepseek', 'info', '解析内容', $script_arr);
  2658. if (!$script_arr['roles']) {
  2659. Utils::throwError('20003:未生成剧本相关信息');
  2660. // yield [
  2661. // 'type' => 'done',
  2662. // 'script' => $script_arr,
  2663. // 'msg' => '未生成剧本相关信息',
  2664. // 'answer' => $fullContent,
  2665. // 'reasoning' => $fullReasoningContent,
  2666. // 'usage' => $usage
  2667. // ];
  2668. }
  2669. try {
  2670. DB::beginTransaction();
  2671. // // 返回前保存剧本内容
  2672. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2673. // 'content' => $content,
  2674. // 'status' => '解析完成',
  2675. // 'updated_at' => date('Y-m-d H:i:s')
  2676. // ]);
  2677. // if (!$boolen) {
  2678. // Utils::throwError('20003:保存剧本内容失败');
  2679. // }
  2680. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2681. 'start_episode_number' => $start_episode_sequence,
  2682. 'end_episode_number' => $end_episode_sequence,
  2683. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2684. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2685. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2686. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2687. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2688. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2689. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2690. 'status' => '解析完成',
  2691. 'content' => $content,
  2692. 'updated_at' => date('Y-m-d H:i:s')
  2693. ]);
  2694. if (!$boolen1) {
  2695. Utils::throwError('20003:保存分集失败');
  2696. }
  2697. // $episodes = [];
  2698. // foreach ($script_arr['episodes'] as $item) {
  2699. // $episodes[] = [
  2700. // 'script_id' => $script_id,
  2701. // 'episode_number' => $item['episode_number'],
  2702. // 'episode_name' => $item['episode_name'],
  2703. // 'episode_content' => $item['episode_content'],
  2704. // 'created_at' => date('Y-m-d H:i:s'),
  2705. // 'updated_at' => date('Y-m-d H:i:s'),
  2706. // ];
  2707. // }
  2708. // if ($episodes) {
  2709. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2710. // if (!$boolen2) {
  2711. // Utils::throwError('20003:保存分集内容失败');
  2712. // }
  2713. // }else {
  2714. // Utils::throwError('20003:分集剧本解析失败');
  2715. // }
  2716. }catch (\Exception $e) {
  2717. DB::rollBack();
  2718. Utils::throwError('20003:'.$e->getMessage());
  2719. }
  2720. DB::commit();
  2721. yield [
  2722. 'type' => 'done',
  2723. 'script' => $script_arr,
  2724. 'answer' => $fullContent,
  2725. 'reasoning' => $fullReasoningContent,
  2726. 'usage' => $usage
  2727. ];
  2728. }
  2729. /**
  2730. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2731. *
  2732. * @param array $data 包含以下参数:
  2733. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2734. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2735. * - model: 使用的模型(r1 或 v3,默认 v3)
  2736. * @return array
  2737. */
  2738. public function chatWithFile($data) {
  2739. $script_id = getProp($data, 'script_id');
  2740. $file = getProp($data, 'file');
  2741. $content = getProp($data, 'content', '');
  2742. $bid = getProp($data, 'bid', 0);
  2743. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2744. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2745. $prompt = getProp($data, 'prompt');
  2746. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2747. if (!empty($prompt)) {
  2748. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2749. }
  2750. $question = getProp($data, 'question', $baseQuestion);
  2751. // 处理文本模型
  2752. $model = getProp($data, 'model');
  2753. if (!$model) {
  2754. // 用户没有输入,使用默认值
  2755. $model = 'doubao-seed-2-0-mini-260215';
  2756. }
  2757. // 验证模型是否在可用模型表中
  2758. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2759. $model = 'doubao-seed-2-0-mini-260215';
  2760. }
  2761. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2762. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2763. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2764. if ($model === 'deepseek-chat') {
  2765. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2766. $model = 'deepseek-v4-flash';
  2767. $thinkingMode = 'disabled';
  2768. } elseif ($model === 'deepseek-reasoner') {
  2769. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2770. $model = 'deepseek-v4-flash';
  2771. $thinkingMode = 'enabled';
  2772. }
  2773. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2774. if (!$script) {
  2775. Utils::throwError('20003:剧本不存在');
  2776. }
  2777. if (!$file && !$content && !$bid) {
  2778. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2779. }
  2780. // 提取文件内容
  2781. if ($file) {
  2782. $content = $this->extractFileContent($file);
  2783. if (!$content) {
  2784. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2785. }
  2786. } elseif ($bid) {
  2787. $content = $this->getContentByBid($bid);
  2788. if (!$content) {
  2789. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2790. }
  2791. } elseif ($content) {
  2792. $content = filterContent($content);
  2793. } elseif ($prompt) {
  2794. $content = filterContent($prompt);
  2795. } else {
  2796. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2797. }
  2798. // 构建消息
  2799. $messages = [
  2800. $this->sys_message,
  2801. [
  2802. 'role' => 'user',
  2803. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2804. ]
  2805. ];
  2806. $post_data = [
  2807. 'model' => $model,
  2808. 'messages' => $messages,
  2809. // 'max_tokens' => 8192,
  2810. 'temperature' => 0.7,
  2811. 'frequency_penalty' => 0,
  2812. 'presence_penalty' => 0,
  2813. 'thinking' => ['type' => $thinkingMode],
  2814. 'response_format' => ['type' => 'text'],
  2815. 'stream' => false
  2816. ];
  2817. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2818. // 根据模型类型选择调用方法
  2819. $fullContent = '';
  2820. $usage = [];
  2821. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2822. // DeepSeek 官方模型使用 DeepSeek API
  2823. $chatResult = $this->chatOnly($post_data);
  2824. } else if (in_array($model, $this->gpt_text_models)) {
  2825. // GPT-5.4 模型使用 TokenRouter API
  2826. $chatResult = $this->gpt54ChatOnly($post_data);
  2827. } else {
  2828. // 其他模型使用火山引擎API
  2829. $chatResult = $this->volcEngineChatCompletion($post_data);
  2830. }
  2831. if (is_array($chatResult)) {
  2832. $fullContent = $chatResult['fullContent'];
  2833. $usage = $chatResult['usage'];
  2834. }
  2835. $script_arr = [];
  2836. // 处理结果
  2837. if ($fullContent) {
  2838. $script_arr = extractScriptContent($fullContent);
  2839. }
  2840. // 返回前保存剧本内容
  2841. DB::table('mp_scripts')->where('id', $script_id)->update([
  2842. 'content' => $content,
  2843. 'updated_at' => date('Y-m-d H:i:s')
  2844. ]);
  2845. return [
  2846. 'script' => $script_arr,
  2847. 'answer' => $fullContent,
  2848. 'usage' => $usage
  2849. ];
  2850. }
  2851. public function getEpisodeContent($data) {
  2852. $group_id = getProp($data, 'group_id');
  2853. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2854. }
  2855. public function saveEpisodeContent($data) {
  2856. $script_id = getProp($data, 'script_id');
  2857. $group_id = getProp($data, 'group_id');
  2858. $start_episode_sequence = getProp($data, 'start_episode_number');
  2859. $end_episode_sequence = getProp($data, 'end_episode_number');
  2860. // 检查是否存在重叠的剧集序号范围
  2861. $exists_groups = DB::table('mp_script_episode_group')
  2862. ->where('script_id', $script_id)
  2863. ->where('id', '<>', $group_id) // 排除当前组
  2864. ->where('is_deleted', 0)
  2865. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2866. // 检查新范围是否与现有范围重叠
  2867. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2868. // 新范围的开始在现有范围内
  2869. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2870. ->where('end_episode_number', '>=', $start_episode_sequence);
  2871. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2872. // 新范围的结束在现有范围内
  2873. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2874. ->where('end_episode_number', '>=', $end_episode_sequence);
  2875. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2876. // 新范围完全包含现有范围
  2877. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2878. ->where('end_episode_number', '<=', $end_episode_sequence);
  2879. });
  2880. })
  2881. ->select('start_episode_number', 'end_episode_number')
  2882. ->get();
  2883. if ($exists_groups->isNotEmpty()) {
  2884. $conflict_ranges = [];
  2885. foreach ($exists_groups as $group) {
  2886. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2887. }
  2888. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2889. }
  2890. $episode_content = getProp($data, 'episode_content');
  2891. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2892. 'content' => $episode_content,
  2893. 'start_episode_number' => $start_episode_sequence,
  2894. 'end_episode_number' => $end_episode_sequence,
  2895. 'updated_at' => date('Y-m-d H:i:s')
  2896. ]);
  2897. $script_arr =getProp($data, 'script', []);
  2898. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2899. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2900. $script_id = getProp($data, 'script_id');
  2901. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2902. try {
  2903. DB::beginTransaction();
  2904. $update_data = [
  2905. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2906. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2907. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2908. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2909. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2910. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2911. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2912. 'status' => 3,
  2913. 'start_episode_sequence' => $start_episode_sequence,
  2914. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2915. 'episode_num' => count($script_arr['episodes']),
  2916. 'updated_at' => date('Y-m-d H:i:s')
  2917. ];
  2918. // 保存剧本内容
  2919. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2920. if (!$boolen) {
  2921. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2922. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2923. Utils::throwError('20003:剧本内容保存失败');
  2924. }
  2925. // 保存分集内容
  2926. // 删除历史分集内容
  2927. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2928. $episodes = [];
  2929. $sequence = 1;
  2930. foreach ($script_arr['episodes'] as $episode) {
  2931. $segment_number = 1;
  2932. foreach($episode['segments'] as $segment) {
  2933. $episodes[] = [
  2934. 'script_id' => $script_id,
  2935. 'episode_number' => $episode['episode_number'],
  2936. 'title' => $episode['title'],
  2937. // 'content' => $episode['content'],
  2938. 'content' => '',
  2939. 'segment_number' => $segment_number,
  2940. 'segment_content' => $segment['segment_content'],
  2941. 'sequence' => $sequence,
  2942. 'created_at' => date('Y-m-d H:i:s'),
  2943. 'updated_at' => date('Y-m-d H:i:s')
  2944. ];
  2945. $sequence++;
  2946. $segment_number++;
  2947. }
  2948. }
  2949. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2950. if (!$boolen2) {
  2951. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2952. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2953. Utils::throwError('20003:分集内容保存失败');
  2954. }
  2955. } catch (\Exception $e) {
  2956. DB::rollBack();
  2957. Utils::throwError('20003:'.$e->getMessage());
  2958. }
  2959. DB::commit();
  2960. return true;
  2961. }
  2962. public function getBookContent($data) {
  2963. $bid = getProp($data, 'bid');
  2964. $start_sequence = getProp($data, 'start_sequence');
  2965. $end_sequence = getProp($data, 'end_sequence');
  2966. $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])
  2967. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2968. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2969. return $return_content;
  2970. }
  2971. public function exportScript($data) {
  2972. $filename = getProp($data, 'filename');
  2973. $script_id = getProp($data, 'script_id');
  2974. $group_id = getProp($data, 'group_id');
  2975. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2976. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2977. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2978. $script = (array)$script;
  2979. // 获取分集组信息
  2980. if ($group_id) {
  2981. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2982. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2983. ->get()->map(function($value) {
  2984. return (array)$value;
  2985. })->toArray();
  2986. }else {
  2987. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2988. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2989. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2990. return (array)$value;
  2991. })->toArray();
  2992. }
  2993. if (!$groups) Utils::throwError('20003:分集不存在');
  2994. $script['group'] = $groups;
  2995. $export_type = getProp($data, 'export_type', 'txt');
  2996. // 生成文件名
  2997. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2998. // 根据导出类型生成不同格式的文件
  2999. switch ($export_type) {
  3000. case 'txt':
  3001. return $this->exportScriptAsTxt($script, $filename);
  3002. case 'pdf':
  3003. return $this->exportScriptAsPdf($script, $filename);
  3004. default:
  3005. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3006. }
  3007. }
  3008. /**
  3009. * 导出剧本为TXT格式
  3010. */
  3011. private function exportScriptAsTxt($script, $filename) {
  3012. // 构建TXT内容
  3013. $content = $this->buildScriptContent($script);
  3014. // 设置响应头,直接下载
  3015. header('Content-Type: text/plain; charset=utf-8');
  3016. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3017. header('Content-Length: ' . strlen($content));
  3018. // 输出内容并结束
  3019. echo $content;
  3020. exit();
  3021. }
  3022. /**
  3023. * 导出剧本为PDF格式
  3024. */
  3025. private function exportScriptAsPdf($script, $filename) {
  3026. // 使用HTML转PDF的方式来更好地支持中文
  3027. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3028. // 创建PDF实例
  3029. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3030. // 设置文档信息
  3031. $pdf->SetCreator('剧本导出系统');
  3032. $pdf->SetAuthor('系统');
  3033. $pdf->SetTitle($script['script_name']);
  3034. $pdf->SetSubject('剧本导出');
  3035. // 设置边距
  3036. $pdf->SetMargins(15, 15, 15);
  3037. $pdf->SetAutoPageBreak(TRUE, 15);
  3038. // 添加页面
  3039. $pdf->AddPage();
  3040. // 注册并使用 simsun.ttf 字体
  3041. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3042. // 使用HTML内容生成PDF
  3043. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3044. // 直接输出PDF文件供下载
  3045. header('Content-Type: application/pdf');
  3046. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3047. // 直接输出PDF内容
  3048. $pdf->Output($filename . '.pdf', 'D');
  3049. exit();
  3050. }
  3051. /**
  3052. * 构建用于PDF的HTML内容
  3053. */
  3054. private function buildScriptHtmlForPdf($script) {
  3055. $html = '<style>
  3056. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3057. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3058. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3059. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3060. .info { margin-bottom: 8px; }
  3061. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3062. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3063. .segment { margin-bottom: 10px; margin-left: 20px; }
  3064. .episode-content { white-space: pre-wrap; }
  3065. </style>';
  3066. // 标题
  3067. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3068. // 处理分组数据
  3069. if (!empty($script['group']) && is_array($script['group'])) {
  3070. $groups = (array)$script['group'];
  3071. foreach ($groups as $group) {
  3072. $html .= '<div class="group">';
  3073. // 分组标题
  3074. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3075. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3076. // 故事梗概
  3077. if (!empty($group['intro'])) {
  3078. $html .= '<h3>故事梗概</h3>';
  3079. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3080. }
  3081. // 剧本亮点
  3082. if (!empty($group['highlights'])) {
  3083. $html .= '<h3>剧本亮点</h3>';
  3084. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3085. }
  3086. // 人物关系
  3087. if (!empty($group['role_relationship'])) {
  3088. $html .= '<h3>人物关系</h3>';
  3089. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3090. }
  3091. // 核心矛盾
  3092. if (!empty($group['core_contradiction'])) {
  3093. $html .= '<h3>核心矛盾</h3>';
  3094. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3095. }
  3096. // 主体列表
  3097. if (!empty($group['roles']) && is_array($group['roles'])) {
  3098. $html .= '<h3>主体列表</h3>';
  3099. $html .= '<ul>';
  3100. foreach ($group['roles'] as $role) {
  3101. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3102. }
  3103. $html .= '</ul>';
  3104. }
  3105. // 美术风格
  3106. if (!empty($group['art_style'])) {
  3107. $html .= '<h3>美术风格</h3>';
  3108. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3109. }
  3110. // 场景列表
  3111. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3112. $html .= '<h3>场景列表</h3>';
  3113. $html .= '<ul>';
  3114. foreach ($group['scenes'] as $scene) {
  3115. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3116. }
  3117. $html .= '</ul>';
  3118. }
  3119. // 分集剧本
  3120. if (!empty($group['episode_content'])) {
  3121. $html .= '<h3>分集剧本</h3>';
  3122. // 去除零宽字符和其他不可见字符
  3123. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3124. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3125. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3126. }
  3127. $html .= '</div>';
  3128. }
  3129. }
  3130. return $html;
  3131. }
  3132. /**
  3133. * 构建PDF内容
  3134. */
  3135. private function buildPdfContent($pdf, $script) {
  3136. // 标题
  3137. $pdf->SetFont('dejavusans', 'B', 18);
  3138. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3139. $pdf->Ln(5);
  3140. // 基本信息
  3141. $pdf->SetFont('dejavusans', '', 12);
  3142. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3143. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3144. $pdf->Ln(5);
  3145. // 剧本简介
  3146. if (!empty($script['intro'])) {
  3147. $pdf->SetFont('dejavusans', 'B', 14);
  3148. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3149. $pdf->SetFont('dejavusans', '', 12);
  3150. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3151. $pdf->Ln(3);
  3152. }
  3153. // 亮点
  3154. if (!empty($script['highlights'])) {
  3155. $pdf->SetFont('dejavusans', 'B', 14);
  3156. $pdf->Cell(0, 10, '亮点', 0, 1);
  3157. $pdf->SetFont('dejavusans', '', 12);
  3158. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3159. $pdf->Ln(3);
  3160. }
  3161. // 核心矛盾
  3162. if (!empty($script['core_contradiction'])) {
  3163. $pdf->SetFont('dejavusans', 'B', 14);
  3164. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3165. $pdf->SetFont('dejavusans', '', 12);
  3166. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3167. $pdf->Ln(3);
  3168. }
  3169. // 艺术风格
  3170. if (!empty($script['art_style'])) {
  3171. $pdf->SetFont('dejavusans', 'B', 14);
  3172. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3173. $pdf->SetFont('dejavusans', '', 12);
  3174. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3175. $pdf->Ln(3);
  3176. }
  3177. // 备注
  3178. if (!empty($script['remark'])) {
  3179. $pdf->SetFont('dejavusans', 'B', 14);
  3180. $pdf->Cell(0, 10, '备注', 0, 1);
  3181. $pdf->SetFont('dejavusans', '', 12);
  3182. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3183. $pdf->Ln(3);
  3184. }
  3185. // 角色列表
  3186. if (!empty($script['roles']) && is_array($script['roles'])) {
  3187. $pdf->SetFont('dejavusans', 'B', 14);
  3188. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3189. $pdf->SetFont('dejavusans', '', 12);
  3190. foreach ($script['roles'] as $index => $role) {
  3191. if (is_array($role) || is_object($role)) {
  3192. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3193. } else {
  3194. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3195. }
  3196. }
  3197. $pdf->Ln(3);
  3198. }
  3199. // 角色关系
  3200. if (!empty($script['role_relationship'])) {
  3201. $pdf->SetFont('dejavusans', 'B', 14);
  3202. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3203. $pdf->SetFont('dejavusans', '', 12);
  3204. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3205. $pdf->Ln(3);
  3206. }
  3207. // 场景列表
  3208. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3209. $pdf->SetFont('dejavusans', 'B', 14);
  3210. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3211. $pdf->SetFont('dejavusans', '', 12);
  3212. foreach ($script['scenes'] as $index => $scene) {
  3213. if (is_array($scene) || is_object($scene)) {
  3214. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3215. } else {
  3216. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3217. }
  3218. }
  3219. $pdf->Ln(5);
  3220. }
  3221. // 分集内容
  3222. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3223. $pdf->SetFont('dejavusans', 'B', 16);
  3224. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3225. $pdf->Ln(3);
  3226. foreach ($script['episodes'] as $episode) {
  3227. // 检查是否需要新页面
  3228. if ($pdf->GetY() > 250) {
  3229. $pdf->AddPage();
  3230. }
  3231. $pdf->SetFont('dejavusans', 'B', 14);
  3232. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3233. if (!empty($episode['title'])) {
  3234. $episodeTitle .= ':' . $episode['title'];
  3235. }
  3236. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3237. // 处理分段内容
  3238. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3239. $pdf->SetFont('dejavusans', '', 12);
  3240. foreach ($episode['segments'] as $segment) {
  3241. if (!empty($segment['segment_content'])) {
  3242. // 如果有分段编号,显示分段标题
  3243. if (!empty($segment['segment_number'])) {
  3244. $pdf->SetFont('dejavusans', 'B', 12);
  3245. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3246. $pdf->SetFont('dejavusans', '', 12);
  3247. }
  3248. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3249. $pdf->Ln(2);
  3250. }
  3251. }
  3252. }
  3253. $pdf->Ln(5);
  3254. }
  3255. }
  3256. }
  3257. /**
  3258. * 构建剧本文本内容
  3259. */
  3260. private function buildScriptContent($script) {
  3261. $content = '';
  3262. $groups = $script['group'];
  3263. $groups = (array)$groups;
  3264. foreach ($groups as $group) {
  3265. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3266. // 剧本基本信息
  3267. if (!empty($group['intro'])) {
  3268. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3269. }
  3270. if (!empty($group['highlights'])) {
  3271. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3272. }
  3273. if (!empty($group['role_relationship'])) {
  3274. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3275. }
  3276. if (!empty($group['core_contradiction'])) {
  3277. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3278. }
  3279. if (!empty($group['roles']) && is_array($group['roles'])) {
  3280. $content .= "###主体列表\n";
  3281. foreach ($group['roles'] as $role) {
  3282. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3283. }
  3284. $content .= "\n\n";
  3285. }
  3286. if (!empty($group['art_style'])) {
  3287. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3288. }
  3289. // 场景信息
  3290. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3291. $content .= "###场景列表\n";
  3292. foreach ($group['scenes'] as $scene) {
  3293. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3294. }
  3295. $content .= "\n\n";
  3296. }
  3297. // 分集内容
  3298. if (!empty($group['episode_content'])) {
  3299. $content .= "###分集剧本\n";
  3300. $content .= $group['episode_content'];
  3301. // foreach ($script['episodes'] as $episode) {
  3302. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3303. // // if (!empty($episode['episode_name'])) {
  3304. // // $content .= ":" . $episode['episode_name'];
  3305. // // }
  3306. // // $content .= "\n";
  3307. // $content .= $episode['episode_content'] . "\n\n";
  3308. // }
  3309. }
  3310. }
  3311. return $content;
  3312. }
  3313. /**
  3314. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3315. *
  3316. * @param array $data 包含以下参数:
  3317. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3318. * - question: 用户问题(可选)
  3319. * - model: 使用的模型(r1 或 v3,默认 v3)
  3320. * @return \Generator 返回生成器,用于流式输出
  3321. */
  3322. public function addChat($data) {
  3323. $uid = Site::getUid();
  3324. $anime_id = getProp($data, 'anime_id');
  3325. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3326. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3327. if (!$anime) Utils::throwError('20003:对话不存在');
  3328. $file = getProp($data, 'file');
  3329. $content = getProp($data, 'content', '');
  3330. $bid = getProp($data, 'bid', 0);
  3331. $script_id = getProp($data, 'script_id', 0);
  3332. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3333. $prompt = getProp($data, 'prompt');
  3334. $user_anime_name = getProp($anime, 'anime_name');
  3335. // 处理文本模型
  3336. $model = getProp($data, 'model');
  3337. if (!$model) {
  3338. // 用户没有输入,从anime表获取
  3339. $model = getProp($anime, 'model');
  3340. if (!$model) {
  3341. // anime表也没有,使用默认值
  3342. $model = 'doubao-seed-2-0-mini-260215';
  3343. }
  3344. }
  3345. // 验证模型是否在可用模型表中
  3346. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3347. $model = 'doubao-seed-2-0-mini-260215';
  3348. }
  3349. $is_multi = getProp($anime, 'is_multi');
  3350. $is_single = (int)$is_multi !== 1;
  3351. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3352. if ($prompt) {
  3353. $question .= "本次修改要求如下:\n{$prompt}";
  3354. }
  3355. // if (!$file && !$content && !$bid) {
  3356. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3357. // }
  3358. // 提取文件内容
  3359. if ($file) {
  3360. $content = $this->extractFileContent($file);
  3361. if (!$content) {
  3362. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3363. }
  3364. } elseif ($script_id) {
  3365. $content = $this->getContentByScriptId($script_id);
  3366. if (!$content) {
  3367. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3368. }
  3369. } elseif ($bid) {
  3370. $content = $this->getContentByBid($bid);
  3371. if (!$content) {
  3372. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3373. }
  3374. } elseif ($content) {
  3375. $content = filterContent($content);
  3376. } else {
  3377. $content = getProp($anime, 'content');
  3378. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3379. $need_generate_content = true;
  3380. }
  3381. }
  3382. // 美术风格
  3383. $input_art_style = getProp($data, 'art_style');
  3384. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3385. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3386. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3387. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3388. 中年女:邻居阿姨
  3389. 老年男:幽默大爷
  3390. 老年女:婆婆
  3391. 萌娃:奶气萌娃";
  3392. // 判断是否需要生成原文内容
  3393. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3394. // 如果需要生成原文内容,添加额外的要求
  3395. $content_generation_requirement = $need_generate_content
  3396. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3397. : "";
  3398. // 美术风格
  3399. if (!$mappedArtStyle) {
  3400. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3401. }else {
  3402. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3403. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3404. }else {
  3405. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3406. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3407. }
  3408. }
  3409. $systemPrompt = $is_single
  3410. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3411. 强制要求:
  3412. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3413. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3414. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3415. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3416. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3417. 普通要求:
  3418. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3419. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3420. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3421. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3422. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3423. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3424. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3425. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3426. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3427. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3428. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3429. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3430. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3431. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3432. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3433. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3434. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3435. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3436. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3437. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3438. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3439. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3440. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3441. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3442. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3443. 5.{$mappedArtStyle_prompt}\n\n
  3444. 示例如下:\n
  3445. ###剧本名:西昆仑
  3446. ###故事梗概
  3447. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3448. ###剧本亮点
  3449. 亮点1:绝境奇药,生死一线
  3450. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3451. 亮点2:结拜兄妹,化解尴尬
  3452. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3453. 亮点3:纤发夺命,情愫暗涌
  3454. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3455. ###人物关系
  3456. 阿雪与梁萧之间存在兄妹之情。
  3457. ###核心矛盾
  3458. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3459. ###主体列表
  3460. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3461. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3462. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3463. 姿态:站立。}{{甜心小美}}
  3464. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3465. 全景,正面拍摄,青年女性,亚洲人。
  3466. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3467. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3468. 姿态:站立。}{{阳光青年}}
  3469. ###美术风格
  3470. 基础画风风格词:厚涂古风
  3471. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3472. ###场景列表
  3473. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3474. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3475. 无人物。}
  3476. ###分镜剧本
  3477. ##第1幕:徐家老旧厨房 白天 室内
  3478. 分镜1
  3479. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3480. 场景:徐家老旧厨房
  3481. 构图设计:全景,低角度仰视
  3482. 运镜调度:手持拍摄
  3483. 配音角色:旁白
  3484. 出镜角色:许芸-校服装、徐母
  3485. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3486. 画面类型:普通画面
  3487. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3488. 分镜2
  3489. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3490. 场景:徐家老旧厨房
  3491. 构图设计:近景,徐母面部特写
  3492. 运镜调度:固定镜头
  3493. 配音角色:徐母
  3494. 出镜角色:徐母
  3495. 台词内容:问我夜不归宿死哪儿去了。
  3496. 画面类型:对口型
  3497. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3498. ##第2幕:徐家简陋客厅 黄昏 室内
  3499. 分镜3
  3500. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3501. 场景:徐家简陋客厅
  3502. 构图设计:全景,景深虚化
  3503. 运镜调度:固定镜头
  3504. 配音角色:旁白
  3505. 出镜角色:无
  3506. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3507. 画面类型:普通画面
  3508. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3509. 分镜4
  3510. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3511. 场景:徐家简陋客厅
  3512. 构图设计:特写,火车票
  3513. 运镜调度:固定镜头
  3514. 配音角色:旁白
  3515. 出镜角色:无
  3516. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3517. 画面类型:普通画面
  3518. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3519. "
  3520. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3521. 强制要求:\n
  3522. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3523. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3524. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3525. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3526. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3527. 普通要求:\n
  3528. 1.剧本名(必须生成)必须与文档内容高度相关
  3529. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3530. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3531. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3532. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3533. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3534. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3535. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3536. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3537. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3538. 4.{$mappedArtStyle_prompt}\n\n
  3539. 示例如下:\n
  3540. ###剧本名:西昆仑
  3541. ###故事梗概
  3542. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3543. ###剧本亮点
  3544. 亮点1:绝境奇药,生死一线
  3545. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3546. 亮点2:结拜兄妹,化解尴尬
  3547. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3548. 亮点3:纤发夺命,情愫暗涌
  3549. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3550. ###人物关系
  3551. 阿雪与梁萧之间存在兄妹之情。
  3552. ###核心矛盾
  3553. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3554. ###主体列表
  3555. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3556. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3557. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3558. 姿态:站立。}{{甜心小美}}
  3559. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3560. 全景,正面拍摄,青年女性,亚洲人。
  3561. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3562. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3563. 姿态:站立。}{{阳光青年}}
  3564. ###美术风格
  3565. 基础画风风格词:厚涂古风
  3566. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3567. ###场景列表
  3568. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3569. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3570. 无人物。}";
  3571. // 构建消息
  3572. $messages = [
  3573. [
  3574. 'role' => 'system',
  3575. 'content' => $systemPrompt
  3576. ],
  3577. [
  3578. 'role' => 'user',
  3579. 'content' => "以下是文档内容:
  3580. {$content}
  3581. 用户问题:
  3582. {$question}"
  3583. ]
  3584. ];
  3585. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3586. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3587. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3588. if ($model === 'deepseek-chat') {
  3589. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3590. $model = 'deepseek-v4-flash';
  3591. $thinkingMode = 'disabled';
  3592. } elseif ($model === 'deepseek-reasoner') {
  3593. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3594. $model = 'deepseek-v4-flash';
  3595. $thinkingMode = 'enabled';
  3596. }
  3597. $post_data = [
  3598. 'model' => $model,
  3599. 'messages' => $messages,
  3600. // 'max_tokens' => 8192,
  3601. 'temperature' => 0.7,
  3602. 'frequency_penalty' => 0,
  3603. 'presence_penalty' => 0,
  3604. 'response_format' => ['type' => 'text'],
  3605. 'thinking' => ['type'=>$thinkingMode],
  3606. 'stream' => true // 启用流式输出
  3607. ];
  3608. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3609. // 根据模型类型选择调用方法
  3610. $fullContent = '';
  3611. $fullReasoningContent = '';
  3612. $usage = [];
  3613. try {
  3614. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3615. // DeepSeek 官方模型使用 DeepSeek API
  3616. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3617. } else if (in_array($model, $this->gpt_text_models)) {
  3618. // GPT-5.4 模型使用 TokenRouter API
  3619. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3620. } else {
  3621. // 其他模型使用火山引擎API
  3622. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3623. }
  3624. // 验证返回值类型
  3625. if (!is_iterable($streamGenerator)) {
  3626. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3627. dLog('deepseek')->error('addChat流式生成器无效', [
  3628. 'generator_type' => $errorType,
  3629. 'model' => $model,
  3630. 'anime_id' => $anime_id
  3631. ]);
  3632. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3633. 'type' => $errorType,
  3634. 'model' => $model
  3635. ]);
  3636. yield [
  3637. 'type' => 'error',
  3638. 'script' => [],
  3639. 'episode' => [],
  3640. 'answer' => '',
  3641. 'reasoning' => '',
  3642. 'usage' => [],
  3643. 'error' => '接口返回数据异常,请重新请求'
  3644. ];
  3645. return;
  3646. }
  3647. // 处理流式输出
  3648. foreach ($streamGenerator as $chunk) {
  3649. if (isset($chunk['type'])) {
  3650. if ($chunk['type'] === 'done') {
  3651. // 最终结果
  3652. $fullContent = $chunk['full_content'];
  3653. $fullReasoningContent = $chunk['full_reasoning'];
  3654. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3655. } else {
  3656. // 逐块yield数据
  3657. yield $chunk;
  3658. }
  3659. }
  3660. }
  3661. } catch (\Exception $e) {
  3662. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3663. 'model' => $model,
  3664. 'anime_id' => $anime_id,
  3665. 'trace' => $e->getTraceAsString()
  3666. ]);
  3667. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3668. 'error' => $e->getMessage(),
  3669. 'model' => $model
  3670. ]);
  3671. yield [
  3672. 'type' => 'error',
  3673. 'script' => [],
  3674. 'episode' => [],
  3675. 'answer' => '',
  3676. 'reasoning' => '',
  3677. 'usage' => [],
  3678. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3679. ];
  3680. return;
  3681. }
  3682. dLog('deepseek')->info('完整内容: '.$fullContent);
  3683. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3684. // 处理完整内容并返回最终结果
  3685. $script_arr = [];
  3686. if ($fullContent) {
  3687. $script_arr = handleScriptContent($fullContent);
  3688. dLog('deepseek')->info('解析内容', $script_arr);
  3689. logDB('deepseek', 'info', '解析内容', $script_arr);
  3690. }
  3691. if (empty($script_arr['roles'])) {
  3692. // 未生成剧本相关内容,保存对话记录并返回提示
  3693. dLog('deepseek')->info('未生成剧本相关的内容');
  3694. try {
  3695. DB::beginTransaction();
  3696. $now = date('Y-m-d H:i:s');
  3697. // 保存对话记录
  3698. $records = [
  3699. [
  3700. 'uid' => $uid,
  3701. 'anime_id' => $anime_id,
  3702. 'sequence' => 0,
  3703. 'role' => 'user',
  3704. 'content' => $prompt,
  3705. 'created_at' => $now,
  3706. 'updated_at' => $now
  3707. ],
  3708. [
  3709. 'uid' => $uid,
  3710. 'anime_id' => $anime_id,
  3711. 'sequence' => 0,
  3712. 'role' => 'assistant',
  3713. // 'content' => $fullContent,
  3714. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3715. 'created_at' => $now,
  3716. 'updated_at' => $now
  3717. ]
  3718. ];
  3719. DB::table('mp_anime_records')->insert($records);
  3720. DB::commit();
  3721. } catch (\Exception $e) {
  3722. DB::rollBack();
  3723. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3724. }
  3725. yield [
  3726. 'type' => 'done',
  3727. 'script' => [],
  3728. 'episode' => [],
  3729. 'answer' => $fullContent,
  3730. 'reasoning' => $fullReasoningContent,
  3731. 'usage' => $usage,
  3732. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3733. ];
  3734. return;
  3735. }
  3736. // 如果需要生成原文内容,从script_arr中提取
  3737. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3738. $content = $script_arr['content'];
  3739. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3740. if (!$content) {
  3741. yield [
  3742. 'type' => 'done',
  3743. 'script' => [],
  3744. 'episode' => [],
  3745. 'answer' => $fullContent,
  3746. 'reasoning' => $fullReasoningContent,
  3747. 'usage' => $usage,
  3748. 'error' => '未生成剧本内容,请调整提示词再试'
  3749. ];
  3750. return;
  3751. }
  3752. }
  3753. // 替换美术风格
  3754. if ($mappedArtStyle !== '') {
  3755. $script_arr['art_style'] = $mappedArtStyle;
  3756. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3757. }
  3758. // 新建动漫
  3759. if ($user_anime_name == '新剧本策划') {
  3760. $anime_name = getProp($script_arr, 'script_name');
  3761. // if (!$anime_name) {
  3762. // // 未识别到剧本名,保存对话记录并返回提示
  3763. // dLog('deepseek')->info('未能识别到剧本名称');
  3764. // try {
  3765. // DB::beginTransaction();
  3766. // $now = date('Y-m-d H:i:s');
  3767. // // 保存对话记录
  3768. // $records = [
  3769. // [
  3770. // 'uid' => $uid,
  3771. // 'anime_id' => $anime_id,
  3772. // 'sequence' => 0,
  3773. // 'role' => 'user',
  3774. // 'content' => $prompt,
  3775. // 'created_at' => $now,
  3776. // 'updated_at' => $now
  3777. // ],
  3778. // [
  3779. // 'uid' => $uid,
  3780. // 'anime_id' => $anime_id,
  3781. // 'sequence' => 0,
  3782. // 'role' => 'assistant',
  3783. // 'content' => '未能生成剧本名称,请重试',
  3784. // 'created_at' => $now,
  3785. // 'updated_at' => $now
  3786. // ]
  3787. // ];
  3788. // DB::table('mp_anime_records')->insert($records);
  3789. // DB::commit();
  3790. // } catch (\Exception $e) {
  3791. // DB::rollBack();
  3792. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3793. // }
  3794. // yield [
  3795. // 'type' => 'done',
  3796. // 'script' => [],
  3797. // 'episode' => [],
  3798. // 'answer' => $fullContent,
  3799. // 'reasoning' => $fullReasoningContent,
  3800. // 'usage' => $usage,
  3801. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3802. // ];
  3803. // return;
  3804. // }
  3805. // 确认对话名称唯一性
  3806. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3807. $anime_name = $anime_name . '_' . date('YmdHis');
  3808. }
  3809. }else {
  3810. $anime_name = $user_anime_name;
  3811. }
  3812. $table_data = [
  3813. 'user_id' => $uid,
  3814. 'anime_name' => $anime_name,
  3815. 'model' => $model,
  3816. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3817. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3818. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3819. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3820. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3821. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3822. 'art_style_type' => $input_art_style,
  3823. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3824. 'status' => '解析完成',
  3825. 'content' => $content,
  3826. 'is_multi' => $is_multi,
  3827. 'ace_mode' => $ace_mode,
  3828. 'generate_status' => '待执行',
  3829. 'updated_at' => date('Y-m-d H:i:s')
  3830. ];
  3831. if ($table_data['content']) {
  3832. $chapters = splitContent($table_data['content']);
  3833. $chapter_count = count($chapters);
  3834. if ($chapter_count > 0) {
  3835. $table_data['start_episode_sequence'] = 1;
  3836. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3837. }
  3838. }
  3839. // 如果有剧本ID则进行绑定
  3840. if ($script_id) {
  3841. $table_data['script_id'] = $script_id;
  3842. }
  3843. $single_episode = [];
  3844. try {
  3845. DB::beginTransaction();
  3846. $now = date('Y-m-d H:i:s');
  3847. // 更新动漫大纲
  3848. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3849. if (!$boolen) {
  3850. dLog('deepseek')->info('动漫保存失败', $table_data);
  3851. Utils::throwError('20003:动漫保存失败');
  3852. }
  3853. // 保存对话记录
  3854. $records = [
  3855. [
  3856. 'uid' => $uid,
  3857. 'anime_id' => $anime_id,
  3858. 'sequence' => 0,
  3859. 'role' => 'user',
  3860. 'content' => $prompt,
  3861. 'created_at' => date('Y-m-d H:i:s'),
  3862. 'updated_at' => date('Y-m-d H:i:s')
  3863. ],
  3864. [
  3865. 'uid' => $uid,
  3866. 'anime_id' => $anime_id,
  3867. 'sequence' => 0,
  3868. 'role' => 'assistant',
  3869. 'content' => $fullContent,
  3870. 'created_at' => date('Y-m-d H:i:s'),
  3871. 'updated_at' => date('Y-m-d H:i:s')
  3872. ]
  3873. ];
  3874. // 保存对话记录
  3875. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3876. if (!$boolen3) {
  3877. Utils::throwError('20003:对话记录保存失败');
  3878. }
  3879. if ($is_single) {
  3880. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3881. if (empty($episode_arr['acts'])) {
  3882. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3883. }
  3884. $saveResult = $this->saveEpisodeVersionData(
  3885. $anime_id,
  3886. 1,
  3887. $episode_arr,
  3888. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3889. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3890. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3891. null,
  3892. null,
  3893. false,
  3894. $content,
  3895. $now
  3896. );
  3897. $single_episode = $saveResult['episode'];
  3898. $episode_id = $saveResult['episode_id'];
  3899. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3900. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3901. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3902. 'props' => json_encode($saveResult['merged_props'], 256),
  3903. 'updated_at' => $now
  3904. ]);
  3905. if ($boolen5 === false) {
  3906. Utils::throwError('20003:单剧集主表资源同步失败');
  3907. }
  3908. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3909. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3910. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3911. $episode_record_content = '确认分镜大纲';
  3912. if ($content !== '') {
  3913. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3914. }
  3915. $episode_records = [
  3916. [
  3917. 'uid' => $uid,
  3918. 'anime_id' => $anime_id,
  3919. 'role' => 'user',
  3920. 'content' => $episode_record_content,
  3921. 'sequence' => 1,
  3922. 'episode_id' => $episode_id,
  3923. 'created_at' => $now,
  3924. 'updated_at' => $now
  3925. ],
  3926. [
  3927. 'uid' => $uid,
  3928. 'anime_id' => $anime_id,
  3929. 'role' => 'assistant',
  3930. 'content' => $fullContent,
  3931. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3932. 'sequence' => 1,
  3933. 'episode_id' => $episode_id,
  3934. 'created_at' => $now,
  3935. 'updated_at' => $now
  3936. ]
  3937. ];
  3938. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3939. if (!$boolen4) {
  3940. Utils::throwError('20003:单剧集分镜记录保存失败');
  3941. }
  3942. }
  3943. }catch (\Exception $e) {
  3944. DB::rollBack();
  3945. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3946. yield [
  3947. 'type' => 'done',
  3948. 'answer' => $fullContent,
  3949. 'reasoning' => $fullReasoningContent,
  3950. 'usage' => $usage,
  3951. 'error' => $e->getMessage(),
  3952. ];
  3953. return;
  3954. }
  3955. DB::commit();
  3956. dLog('deepseek')->info('保存完毕');
  3957. if ($is_single && !empty($single_episode)) {
  3958. // $this->batchSetGlobalRoleImg([
  3959. // 'anime_id' => $anime_id,
  3960. // ]);
  3961. // $this->batchSetGlobalSceneImg([
  3962. // 'anime_id' => $anime_id,
  3963. // ]);
  3964. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3965. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3966. }
  3967. $table_data['anime_id'] = $anime_id;
  3968. $table_data['roles'] = json_decode($table_data['roles'], true);
  3969. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3970. // $table_data['episodes'] = $script_arr['episodes'];
  3971. unset($table_data['created_at']);
  3972. unset($table_data['updated_at']);
  3973. unset($table_data['status']);
  3974. dLog('deepseek')->info('开始返回');
  3975. yield [
  3976. 'type' => 'done',
  3977. 'script' => $table_data,
  3978. 'episode' => $single_episode,
  3979. 'answer' => $fullContent,
  3980. 'reasoning' => $fullReasoningContent,
  3981. 'usage' => $usage
  3982. ];
  3983. }
  3984. public function reGenerateAnime($data) {
  3985. $uid = Site::getUid();
  3986. $file = getProp($data, 'file');
  3987. $content = getProp($data, 'content', '');
  3988. $bid = getProp($data, 'bid', 0);
  3989. $script_id = getProp($data, 'script_id', 0);
  3990. $anime_id = getProp($data, 'anime_id');
  3991. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3992. if (!$anime) {
  3993. Utils::throwError('20003:该对话不存在');
  3994. }
  3995. $user_anime_name = getProp($anime, 'anime_name');
  3996. $prompt = getProp($data, 'prompt');
  3997. // 处理文本模型
  3998. $model = getProp($data, 'model');
  3999. if (!$model) {
  4000. // 用户没有输入,从anime表获取
  4001. $model = getProp($anime, 'model');
  4002. if (!$model) {
  4003. // anime表也没有,使用默认值
  4004. $model = 'doubao-seed-2-0-mini-260215';
  4005. }
  4006. }
  4007. // 验证模型是否在可用模型表中
  4008. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4009. $model = 'doubao-seed-2-0-mini-260215';
  4010. }
  4011. $is_multi = getProp($anime, 'is_multi', 1);
  4012. $is_single = (int)$is_multi !== 1;
  4013. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4014. if ($is_single) {
  4015. $episode_exists = DB::table('mp_anime_episodes')
  4016. ->where('anime_id', $anime_id)
  4017. ->where('sequence', 1)
  4018. ->exists();
  4019. if ($episode_exists) {
  4020. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4021. }
  4022. }
  4023. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4024. if ($prompt) {
  4025. $question .= "本次修改要求如下:\n{$prompt}";
  4026. }
  4027. // 提取文件内容
  4028. if ($file) {
  4029. $content = $this->extractFileContent($file);
  4030. if (!$content) {
  4031. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4032. }
  4033. } elseif ($script_id) {
  4034. $content = $this->getContentByScriptId($script_id);
  4035. if (!$content) {
  4036. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4037. }
  4038. } elseif ($bid) {
  4039. $content = $this->getContentByBid($bid);
  4040. if (!$content) {
  4041. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4042. }
  4043. } elseif ($content) {
  4044. $content = filterContent($content);
  4045. }else {
  4046. $content = filterContent(getProp($anime, 'content'));
  4047. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4048. $need_generate_content = true;
  4049. }
  4050. }
  4051. // 判断是否需要生成原文内容
  4052. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4053. // 如果需要生成原文内容,添加额外的要求
  4054. $content_generation_requirement = $need_generate_content
  4055. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4056. : "";
  4057. // 美术风格
  4058. $input_art_style = getProp($anime, 'art_style');
  4059. if (!$input_art_style) {
  4060. $input_art_style = getProp($data, 'art_style');
  4061. }
  4062. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4063. // 美术风格
  4064. if (!$mappedArtStyle) {
  4065. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4066. }else {
  4067. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4068. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4069. }else {
  4070. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4071. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4072. }
  4073. }
  4074. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4075. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4076. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4077. 中年女:邻居阿姨
  4078. 老年男:幽默大爷
  4079. 老年女:婆婆
  4080. 萌娃:奶气萌娃";
  4081. $system_message = ['role'=>'system', 'content'=>$is_single
  4082. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4083. 强制要求:
  4084. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4085. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4086. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4087. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4088. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4089. 普通要求:
  4090. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4091. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4092. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4093. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4094. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4095. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4096. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4097. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4098. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4099. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4100. 3.$mappedArtStyle_prompt\n\n
  4101. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4102. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4103. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4104. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4105. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4106. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4107. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4108. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4109. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4110. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4111. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4112. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4113. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4114. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4115. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4116. 示例如下:\n
  4117. ###剧本名:西昆仑
  4118. ###故事梗概
  4119. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4120. ###剧本亮点
  4121. 亮点1:绝境奇药,生死一线
  4122. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4123. 亮点2:结拜兄妹,化解尴尬
  4124. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4125. 亮点3:纤发夺命,情愫暗涌
  4126. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4127. ###人物关系
  4128. 阿雪与梁萧之间存在兄妹之情。
  4129. ###核心矛盾
  4130. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4131. ###主体列表
  4132. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4133. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4134. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4135. 姿态:站立。}{{甜心小美}}
  4136. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4137. 全景,正面拍摄,青年女性,亚洲人。
  4138. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4139. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4140. 姿态:站立。}{{阳光青年}}
  4141. ###美术风格
  4142. 基础画风风格词:厚涂古风
  4143. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4144. ###场景列表
  4145. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4146. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4147. 无人物。}
  4148. ###分镜剧本
  4149. ##第1幕:徐家老旧厨房 白天 室内
  4150. 分镜1
  4151. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4152. 场景:徐家老旧厨房
  4153. 构图设计:全景,低角度仰视
  4154. 运镜调度:手持拍摄
  4155. 配音角色:旁白
  4156. 出镜角色:许芸-校服装、徐母
  4157. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4158. 画面类型:普通画面
  4159. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4160. 分镜2
  4161. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4162. 场景:徐家老旧厨房
  4163. 构图设计:近景,徐母面部特写
  4164. 运镜调度:固定镜头
  4165. 配音角色:徐母
  4166. 出镜角色:徐母
  4167. 台词内容:问我夜不归宿死哪儿去了。
  4168. 画面类型:对口型
  4169. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4170. ##第2幕:徐家简陋客厅 黄昏 室内
  4171. 分镜3
  4172. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4173. 场景:徐家简陋客厅
  4174. 构图设计:全景,景深虚化
  4175. 运镜调度:固定镜头
  4176. 配音角色:旁白
  4177. 出镜角色:无
  4178. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4179. 画面类型:普通画面
  4180. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4181. 分镜4
  4182. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4183. 场景:徐家简陋客厅
  4184. 构图设计:特写,火车票
  4185. 运镜调度:固定镜头
  4186. 配音角色:旁白
  4187. 出镜角色:无
  4188. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4189. 画面类型:普通画面
  4190. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4191. "
  4192. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4193. 强制要求:\n
  4194. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4195. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4196. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4197. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4198. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4199. 普通要求:\n
  4200. 1.剧本名(必须生成)必须与文档内容高度相关
  4201. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4202. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4203. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4204. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4205. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4206. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4207. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4208. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4209. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4210. 4.$mappedArtStyle_prompt\n\n
  4211. 示例如下:\n
  4212. ###剧本名:西昆仑
  4213. ###故事梗概
  4214. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4215. ###剧本亮点
  4216. 亮点1:绝境奇药,生死一线
  4217. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4218. 亮点2:结拜兄妹,化解尴尬
  4219. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4220. 亮点3:纤发夺命,情愫暗涌
  4221. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4222. ###人物关系
  4223. 阿雪与梁萧之间存在兄妹之情。
  4224. ###核心矛盾
  4225. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4226. ###主体列表
  4227. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4228. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4229. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4230. 姿态:站立。}{{甜心小美}}
  4231. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4232. 全景,正面拍摄,青年女性,亚洲人。
  4233. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4234. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4235. 姿态:站立。}{{阳光青年}}
  4236. ###美术风格
  4237. 基础画风风格词:厚涂古风
  4238. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4239. ###场景列表
  4240. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4241. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4242. 无人物。}"];
  4243. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4244. $episode_count = $this->extractEpisodeNumber($prompt);
  4245. if ((int)getProp($anime, 'is_multi') !== 1) {
  4246. yield [
  4247. 'type' => 'done',
  4248. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4249. 'reasoning' => '',
  4250. 'usage' => []
  4251. ];
  4252. return;
  4253. }
  4254. if ($episode_count) {
  4255. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4256. $system_message = [
  4257. 'role' => 'system',
  4258. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4259. 强制要求:\n
  4260. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4261. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4262. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4263. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4264. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4265. 普通要求:\n
  4266. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4267. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4268. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4269. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4270. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4271. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4272. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4273. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4274. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4275. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4276. 示例如下:\n
  4277. ###剧本名:西昆仑
  4278. ###故事梗概
  4279. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4280. ###剧本亮点
  4281. 亮点1:绝境奇药,生死一线
  4282. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4283. 亮点2:结拜兄妹,化解尴尬
  4284. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4285. 亮点3:纤发夺命,情愫暗涌
  4286. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4287. ###人物关系
  4288. 阿雪与梁萧之间存在兄妹之情。
  4289. ###核心矛盾
  4290. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4291. ###主体列表
  4292. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4293. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4294. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4295. 姿态:站立。}{{甜心小美}}
  4296. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4297. 全景,正面拍摄,青年女性,亚洲人。
  4298. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4299. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4300. 姿态:站立。}{{阳光青年}}
  4301. ###美术风格
  4302. 基础画风风格词:厚涂古风
  4303. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4304. ###场景列表
  4305. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4306. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4307. 无人物。}
  4308. ###分集详细内容
  4309. ##第1章 重生
  4310. 我重生了。
  4311. 源于一个男人偏执的暗恋。
  4312. ##第2章 相救
  4313. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4314. 我眼睛扫向站在锅炉后的卞大伟。"
  4315. ];
  4316. // 构建消息
  4317. $messages = [
  4318. $system_message,
  4319. [
  4320. 'role' => 'user',
  4321. 'content' => "以下是文档内容:
  4322. {$content}
  4323. 用户问题:
  4324. {$question}"
  4325. ]
  4326. ];
  4327. }else {
  4328. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4329. // 构建消息
  4330. $messages = [
  4331. $system_message,
  4332. [
  4333. 'role' => 'user',
  4334. 'content' => "以下是文档内容:
  4335. {$content}
  4336. 用户问题:
  4337. {$question}"
  4338. ]
  4339. ];
  4340. }else {
  4341. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4342. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4343. return (array)$value;
  4344. })->toArray();
  4345. array_unshift($messages, $system_message);
  4346. $messages[] = [
  4347. 'role' => 'user',
  4348. 'content' => $prompt
  4349. ];
  4350. }
  4351. }
  4352. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4353. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4354. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4355. if ($model === 'deepseek-chat') {
  4356. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4357. $model = 'deepseek-v4-flash';
  4358. $thinkingMode = 'disabled';
  4359. } elseif ($model === 'deepseek-reasoner') {
  4360. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4361. $model = 'deepseek-v4-flash';
  4362. $thinkingMode = 'enabled';
  4363. }
  4364. $post_data = [
  4365. 'model' => $model,
  4366. 'messages' => $messages,
  4367. // 'max_tokens' => 8192,
  4368. 'temperature' => 0.7,
  4369. 'frequency_penalty' => 0,
  4370. 'presence_penalty' => 0,
  4371. 'response_format' => ['type' => 'text'],
  4372. 'thinking' => ['type' => $thinkingMode],
  4373. 'stream' => true // 启用流式输出
  4374. ];
  4375. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4376. // 根据模型类型选择调用方法
  4377. $fullContent = '';
  4378. $fullReasoningContent = '';
  4379. $usage = [];
  4380. // dd($post_data);
  4381. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4382. try {
  4383. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4384. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4385. } else if (in_array($model, $this->gpt_text_models)) {
  4386. // GPT-5.4 模型使用 TokenRouter API
  4387. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4388. } else {
  4389. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4390. }
  4391. // 验证返回值类型
  4392. if (!is_iterable($streamGenerator)) {
  4393. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4394. dLog('deepseek')->error('方法名流式生成器无效', [
  4395. 'generator_type' => $errorType,
  4396. 'model' => $model,
  4397. // 添加其他上下文信息
  4398. ]);
  4399. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4400. 'type' => $errorType,
  4401. 'model' => $model
  4402. ]);
  4403. yield [
  4404. 'type' => 'error',
  4405. // 根据方法返回相应的空数据结构
  4406. 'answer' => '',
  4407. 'reasoning' => '',
  4408. 'usage' => [],
  4409. 'error' => '接口返回数据异常,请重新请求'
  4410. ];
  4411. return;
  4412. }
  4413. // 处理流式输出
  4414. foreach ($streamGenerator as $chunk) {
  4415. if (isset($chunk['type'])) {
  4416. if ($chunk['type'] === 'done') {
  4417. $fullContent = $chunk['full_content'];
  4418. $fullReasoningContent = $chunk['full_reasoning'];
  4419. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4420. } else {
  4421. yield $chunk;
  4422. }
  4423. }
  4424. }
  4425. } catch (\Exception $e) {
  4426. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4427. 'model' => $model,
  4428. 'trace' => $e->getTraceAsString()
  4429. ]);
  4430. logDB('deepseek', 'error', '方法名流式处理失败', [
  4431. 'error' => $e->getMessage(),
  4432. 'model' => $model
  4433. ]);
  4434. yield [
  4435. 'type' => 'error',
  4436. // 根据方法返回相应的空数据结构
  4437. 'answer' => '',
  4438. 'reasoning' => '',
  4439. 'usage' => [],
  4440. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4441. ];
  4442. return;
  4443. }
  4444. dLog('deepseek')->info('完整内容: '.$fullContent);
  4445. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4446. // 处理完整内容并返回最终结果
  4447. $script_arr = [];
  4448. if ($fullContent) {
  4449. $script_arr = handleScriptContent($fullContent);
  4450. dLog('deepseek')->info('解析内容', $script_arr);
  4451. logDB('deepseek', 'info', '解析内容', $script_arr);
  4452. }
  4453. if (empty($script_arr['roles'])) {
  4454. // 未生成剧本相关内容,保存对话记录并返回提示
  4455. dLog('deepseek')->info('未生成剧本相关的内容');
  4456. try {
  4457. $now = date('Y-m-d H:i:s');
  4458. // 保存对话记录
  4459. $records = [
  4460. [
  4461. 'uid' => $uid,
  4462. 'anime_id' => $anime_id,
  4463. 'sequence' => 0,
  4464. 'role' => 'user',
  4465. 'content' => $prompt,
  4466. 'created_at' => $now,
  4467. 'updated_at' => $now
  4468. ],
  4469. [
  4470. 'uid' => $uid,
  4471. 'anime_id' => $anime_id,
  4472. 'sequence' => 0,
  4473. 'role' => 'assistant',
  4474. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4475. 'created_at' => $now,
  4476. 'updated_at' => $now
  4477. ]
  4478. ];
  4479. DB::table('mp_anime_records')->insert($records);
  4480. } catch (\Exception $e) {
  4481. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4482. }
  4483. yield [
  4484. 'type' => 'done',
  4485. 'script' => [],
  4486. 'episode' => [],
  4487. 'answer' => $fullContent,
  4488. 'reasoning' => $fullReasoningContent,
  4489. 'usage' => $usage,
  4490. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4491. ];
  4492. return;
  4493. }
  4494. // 替换美术风格
  4495. if ($mappedArtStyle !== '') {
  4496. $script_arr['art_style'] = $mappedArtStyle;
  4497. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4498. }
  4499. if ($user_anime_name != '新剧本策划') {
  4500. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4501. // 确认对话名称唯一性
  4502. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4503. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4504. }
  4505. }else {
  4506. $anime_name = $user_anime_name;
  4507. }
  4508. $table_data = [
  4509. 'user_id' => $uid,
  4510. 'model' => $model,
  4511. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4512. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4513. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4514. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4515. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4516. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4517. 'art_style_type' => $input_art_style,
  4518. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4519. 'status' => '解析完成',
  4520. 'generate_status' => '待执行',
  4521. 'updated_at' => date('Y-m-d H:i:s')
  4522. ];
  4523. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4524. // 如果是修改集数,则将content内容更新(会改变原文)
  4525. if (isset($episode_count) && $episode_count > 0) {
  4526. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4527. $table_data['start_episode_sequence'] = 1;
  4528. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4529. }else {
  4530. // 如果需要生成原文内容,从script_arr中提取
  4531. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4532. $table_data['content'] = $script_arr['content'];
  4533. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4534. if (!$table_data['content']) {
  4535. yield [
  4536. 'type' => 'done',
  4537. 'script' => [],
  4538. 'episode' => [],
  4539. 'answer' => $fullContent,
  4540. 'reasoning' => $fullReasoningContent,
  4541. 'usage' => $usage,
  4542. 'error' => '未生成剧本内容,请调整提示词再试'
  4543. ];
  4544. return;
  4545. }
  4546. }
  4547. if (isset($table_data['content']) && $table_data['content']) {
  4548. $chapters = splitContent($table_data['content']);
  4549. $chapter_count = count($chapters);
  4550. if ($chapter_count > 0) {
  4551. $table_data['start_episode_sequence'] = 1;
  4552. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4553. }
  4554. }
  4555. }
  4556. $single_episode = [];
  4557. try {
  4558. DB::beginTransaction();
  4559. $now = date('Y-m-d H:i:s');
  4560. // 更新动漫大纲
  4561. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4562. if (!$boolen) {
  4563. dLog('deepseek')->info('对话修改失败', $table_data);
  4564. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4565. Utils::throwError('20003:对话修改失败');
  4566. }
  4567. // 保存对话记录
  4568. $records = [
  4569. [
  4570. 'uid' => $uid,
  4571. 'anime_id' => $anime_id,
  4572. 'sequence' => 0,
  4573. 'role' => 'user',
  4574. 'content' => $prompt,
  4575. 'created_at' => $now,
  4576. 'updated_at' => $now
  4577. ],
  4578. [
  4579. 'uid' => $uid,
  4580. 'anime_id' => $anime_id,
  4581. 'sequence' => 0,
  4582. 'role' => 'assistant',
  4583. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4584. 'content' => $fullContent,
  4585. 'created_at' => $now,
  4586. 'updated_at' => $now
  4587. ]
  4588. ];
  4589. // 保存对话记录
  4590. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4591. if (!$boolen3) {
  4592. Utils::throwError('20003:对话记录保存失败');
  4593. }
  4594. // 单剧集模式:生成并保存剧集信息
  4595. if ($is_single) {
  4596. $anime_name = getProp($anime, 'anime_name', '未命名');
  4597. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4598. if (empty($episode_arr['acts'])) {
  4599. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4600. }
  4601. $saveResult = $this->saveEpisodeVersionData(
  4602. $anime_id,
  4603. 1,
  4604. $episode_arr,
  4605. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4606. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4607. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4608. null,
  4609. null,
  4610. false,
  4611. $content,
  4612. $now
  4613. );
  4614. $single_episode = $saveResult['episode'];
  4615. $episode_id = $saveResult['episode_id'];
  4616. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4617. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4618. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4619. 'props' => json_encode($saveResult['merged_props'], 256),
  4620. 'updated_at' => $now
  4621. ]);
  4622. if ($boolen5 === false) {
  4623. Utils::throwError('20003:单剧集主表资源同步失败');
  4624. }
  4625. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4626. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4627. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4628. $episode_record_content = '确认分镜大纲';
  4629. if ($content !== '') {
  4630. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4631. }
  4632. $episode_records = [
  4633. [
  4634. 'uid' => $uid,
  4635. 'anime_id' => $anime_id,
  4636. 'role' => 'user',
  4637. 'content' => $episode_record_content,
  4638. 'sequence' => 1,
  4639. 'episode_id' => $episode_id,
  4640. 'created_at' => $now,
  4641. 'updated_at' => $now
  4642. ],
  4643. [
  4644. 'uid' => $uid,
  4645. 'anime_id' => $anime_id,
  4646. 'role' => 'assistant',
  4647. 'content' => $fullContent,
  4648. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4649. 'sequence' => 1,
  4650. 'episode_id' => $episode_id,
  4651. 'created_at' => $now,
  4652. 'updated_at' => $now
  4653. ]
  4654. ];
  4655. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4656. if (!$boolen4) {
  4657. Utils::throwError('20003:单剧集分镜记录保存失败');
  4658. }
  4659. }
  4660. }catch (\Exception $e) {
  4661. DB::rollBack();
  4662. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4663. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4664. yield [
  4665. 'type' => 'done',
  4666. 'answer' => $fullContent,
  4667. 'reasoning' => $fullReasoningContent,
  4668. 'usage' => $usage,
  4669. 'error' => $e->getMessage(),
  4670. ];
  4671. return;
  4672. }
  4673. DB::commit();
  4674. dLog('deepseek')->info('保存完毕');
  4675. if ($is_single && !empty($single_episode)) {
  4676. // $this->batchSetGlobalRoleImg([
  4677. // 'anime_id' => $anime_id,
  4678. // ]);
  4679. // $this->batchSetGlobalSceneImg([
  4680. // 'anime_id' => $anime_id,
  4681. // ]);
  4682. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4683. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4684. }
  4685. $table_data['anime_id'] = $anime_id;
  4686. $table_data['roles'] = json_decode($table_data['roles'], true);
  4687. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4688. unset($table_data['updated_at']);
  4689. unset($table_data['status']);
  4690. yield [
  4691. 'type' => 'done',
  4692. 'script' => $table_data,
  4693. 'episode' => $single_episode,
  4694. 'answer' => $fullContent,
  4695. 'reasoning' => $fullReasoningContent,
  4696. 'usage' => $usage
  4697. ];
  4698. }
  4699. public function chat($data) {
  4700. $uid = Site::getUid();
  4701. $anime_id = getProp($data, 'anime_id');
  4702. $file = getProp($data, 'file');
  4703. $content = getProp($data, 'content', '');
  4704. $bid = getProp($data, 'bid', 0);
  4705. $script_id = getProp($data, 'script_id', 0);
  4706. $episode_number = getProp($data, 'episode_number', 1);
  4707. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4708. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4709. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4710. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4711. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4712. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4713. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4714. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4715. $roles = is_array($roles) ? $roles : [];
  4716. $scenes = is_array($scenes) ? $scenes : [];
  4717. // 获取最后一集序号
  4718. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4719. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4720. // 转换主体列表和场景列表的格式
  4721. // 获取参考主体或场景
  4722. if ((int)$episode_number === 1) {
  4723. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4724. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4725. }else {
  4726. $prev_episode_number = $episode_number - 1;
  4727. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4728. }
  4729. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4730. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4731. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4732. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4733. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4734. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4735. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4736. 中年女:邻居阿姨
  4737. 老年男:幽默大爷
  4738. 老年女:婆婆
  4739. 萌娃:奶气萌娃";
  4740. if ($roles_content) {
  4741. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4742. 主体范围:\n {$roles_content}\n
  4743. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4744. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4745. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4746. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4747. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4748. }else {
  4749. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4750. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4751. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4752. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4753. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4754. }
  4755. if ($scenes_content) {
  4756. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4757. 场景范围:\n {$scenes_content}\n
  4758. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4759. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4760. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4761. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4762. }else {
  4763. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4764. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4765. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4766. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4767. }
  4768. // 提取文件内容
  4769. if ($file) {
  4770. $uploaded_content = $this->extractFileContent($file);
  4771. if (!$uploaded_content) {
  4772. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4773. }
  4774. } elseif ($script_id) {
  4775. $uploaded_content = $this->getContentByScriptId($script_id);
  4776. if (!$uploaded_content) {
  4777. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4778. }
  4779. } elseif ($bid) {
  4780. $uploaded_content = $this->getContentByBid($bid);
  4781. if (!$uploaded_content) {
  4782. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4783. }
  4784. } elseif ($content) {
  4785. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4786. }
  4787. // elseif ($prompt) {
  4788. // $uploaded_content = filterContent($prompt);
  4789. // }
  4790. else {
  4791. $uploaded_content = '';
  4792. }
  4793. $input_art_style = getProp($anime, 'art_style');
  4794. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4795. // 美术风格
  4796. if (!$mappedArtStyle) {
  4797. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4798. }else {
  4799. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4800. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4801. }else {
  4802. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4803. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4804. }
  4805. }
  4806. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4807. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4808. // 强制要求:
  4809. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4810. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4811. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4812. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4813. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4814. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4815. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4816. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4817. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4818. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4819. // - 分镜要和场景列表、人物主体保持一致\n
  4820. // 普通要求:
  4821. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4822. // {$role_demo}
  4823. // {$scene_demo}
  4824. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4825. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4826. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4827. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4828. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4829. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4830. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4831. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4832. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4833. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4834. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4835. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4836. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4837. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4838. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4839. // 5.$mappedArtStyle_prompt\n\n
  4840. // 示例格式:\n
  4841. // 第1集:隐形的守护者
  4842. // ###故事梗概
  4843. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4844. // ###美术风格
  4845. // 基础画风风格词:韩漫二次元
  4846. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4847. // ###主体列表
  4848. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4849. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4850. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4851. // ###场景列表
  4852. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4853. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4854. // 无人物。}
  4855. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4856. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4857. // 无人物。}
  4858. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4859. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4860. // 无人物。}
  4861. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4862. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4863. // 无人物。}
  4864. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4865. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4866. // 无人物。}
  4867. // ###分镜剧本
  4868. // ##第1幕:徐家老旧厨房 白天 室内
  4869. // 分镜1
  4870. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4871. // 场景:徐家老旧厨房
  4872. // 构图设计:全景,低角度仰视
  4873. // 运镜调度:手持拍摄
  4874. // 配音角色:旁白
  4875. // 出镜角色:许芸-校服装、徐母
  4876. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4877. // 画面类型:普通画面
  4878. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4879. // 分镜2
  4880. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4881. // 场景:徐家老旧厨房
  4882. // 构图设计:近景,徐母面部特写
  4883. // 运镜调度:固定镜头
  4884. // 配音角色:徐母
  4885. // 出镜角色:徐母
  4886. // 台词内容:问我夜不归宿死哪儿去了。
  4887. // 画面类型:对口型
  4888. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4889. // ##第2幕:徐家简陋客厅 黄昏 室内
  4890. // 分镜3
  4891. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4892. // 场景:徐家简陋客厅
  4893. // 构图设计:全景,景深虚化
  4894. // 运镜调度:固定镜头
  4895. // 配音角色:旁白
  4896. // 出镜角色:无
  4897. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4898. // 画面类型:普通画面
  4899. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4900. // 分镜4
  4901. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4902. // 场景:徐家简陋客厅
  4903. // 构图设计:特写,火车票
  4904. // 运镜调度:固定镜头
  4905. // 配音角色:旁白
  4906. // 出镜角色:无
  4907. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4908. // 画面类型:普通画面
  4909. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4910. // \n\n";
  4911. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4912. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4913. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4914. 普通要求:
  4915. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4916. {$role_demo}
  4917. {$scene_demo}
  4918. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4919. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4920. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4921. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4922. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4923. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4924. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4925. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4926. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4927. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4928. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4929. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4930. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4931. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4932. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4933. 5.$mappedArtStyle_prompt
  4934. 6.《情绪-视听语言映射表》:
  4935. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4936. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4937. -----|---------|------------|----------------
  4938. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4939. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4940. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4941. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4942. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4943. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4944. -----|---------|------------|----------------
  4945. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4946. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4947. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4948. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4949. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4950. --------|---------|--------------|-------------
  4951. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4952. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4953. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4954. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4955. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4956. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4957. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4958. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4959. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4960. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4961. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4962. -----|---------|------------|------------
  4963. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4964. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4965. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4966. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4967. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4968. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4969. --------|---------|--------------|----------
  4970. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4971. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4972. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4973. 6.6 声音设计与潜意识影响 (Soundscape)
  4974. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4975. -----|---------|------------|------------------
  4976. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4977. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4978. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4979. 理论基石:
  4980. - The Five C's of Cinematography by Joseph V. Mascelli
  4981. - Film Art: An Introduction by David Bordwell
  4982. - Sight, Sound, Motion by Herbert Zettl
  4983. - Notes on the Cinematograph by Robert Bresson
  4984. \n\n
  4985. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4986. 示例格式:\n
  4987. 第1集:隐形的守护者
  4988. ###故事梗概
  4989. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4990. ###美术风格
  4991. 基础画风风格词:韩漫二次元
  4992. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4993. ###主体列表
  4994. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4995. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4996. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4997. ###场景列表
  4998. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4999. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5000. 无人物。}
  5001. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5002. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5003. 无人物。}
  5004. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5005. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5006. 无人物。}
  5007. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5008. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5009. 无人物。}
  5010. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5011. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5012. 无人物。}
  5013. ###分镜剧本
  5014. ##第1幕:徐家老旧厨房 白天 室内
  5015. 分镜1
  5016. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5017. 场景:徐家老旧厨房
  5018. 构图设计:全景,低角度仰视
  5019. 运镜调度:手持拍摄
  5020. 配音角色:旁白
  5021. 出镜角色:许芸-校服装、徐母
  5022. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5023. 画面类型:普通画面
  5024. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5025. 分镜2
  5026. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5027. 场景:徐家老旧厨房
  5028. 构图设计:近景,徐母面部特写
  5029. 运镜调度:固定镜头
  5030. 配音角色:徐母
  5031. 出镜角色:徐母
  5032. 台词内容:问我夜不归宿死哪儿去了。
  5033. 画面类型:对口型
  5034. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5035. ##第2幕:徐家简陋客厅 黄昏 室内
  5036. 分镜3
  5037. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5038. 场景:徐家简陋客厅
  5039. 构图设计:全景,景深虚化
  5040. 运镜调度:固定镜头
  5041. 配音角色:旁白
  5042. 出镜角色:无
  5043. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5044. 画面类型:普通画面
  5045. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5046. 分镜4
  5047. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5048. 场景:徐家简陋客厅
  5049. 构图设计:特写,火车票
  5050. 运镜调度:固定镜头
  5051. 配音角色:旁白
  5052. 出镜角色:无
  5053. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5054. 画面类型:普通画面
  5055. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5056. \n\n";
  5057. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5058. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5059. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5060. $prompt = $origin_prompt;
  5061. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5062. // 获取章节内容
  5063. $full_content = getProp($anime, 'content');
  5064. if ($uploaded_content) {
  5065. $full_content = $uploaded_content;
  5066. }
  5067. // 根据章节内容拆分章节
  5068. $chapters = splitContent($full_content);
  5069. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5070. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5071. $messages = [];
  5072. if ($prompt == '确认分镜大纲') {
  5073. // 暂时保留
  5074. $content = $chapter_content;
  5075. if ($is_single) $content = $full_content; // 单剧集使用全文
  5076. if (!$content) {
  5077. Utils::throwError('20003:章节内容无法获取,请确认');
  5078. }
  5079. $question = $is_single
  5080. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5081. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5082. // 构建消息
  5083. $messages[] =
  5084. [
  5085. 'role' => 'user',
  5086. 'content' => $question
  5087. ];
  5088. }else if ($prompt == '继续策划下一集') {
  5089. if ($is_single) {
  5090. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5091. }
  5092. $content = $chapter_content;
  5093. if (!$content) {
  5094. Utils::throwError('20003:章节内容无法获取,请确认');
  5095. }
  5096. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5097. // 获取上一集最后记录
  5098. $prev_sequence = $episode_number - 1;
  5099. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5100. // 构建消息
  5101. $messages[] =
  5102. [
  5103. 'role' => 'user',
  5104. 'content' => $question
  5105. ];
  5106. }else {
  5107. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5108. if (!$content) {
  5109. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5110. }
  5111. if (!$content) {
  5112. Utils::throwError('20003:章节内容无法获取,请确认');
  5113. }
  5114. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5115. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5116. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5117. if ($origin_prompt) {
  5118. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5119. }
  5120. $messages[] =
  5121. [
  5122. 'role' => 'user',
  5123. 'content' => $question
  5124. ];
  5125. }
  5126. // 处理文本模型
  5127. $model = getProp($data, 'model');
  5128. if (!$model) {
  5129. // 用户没有输入,从anime表获取
  5130. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5131. $model = getProp($anime, 'model');
  5132. if (!$model) {
  5133. // anime表也没有,使用默认值
  5134. $model = 'doubao-seed-2-0-mini-260215';
  5135. }
  5136. }
  5137. // 验证模型是否在可用模型表中
  5138. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5139. $model = 'doubao-seed-2-0-mini-260215';
  5140. }
  5141. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5142. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5143. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5144. if ($model === 'deepseek-chat') {
  5145. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5146. $model = 'deepseek-v4-flash';
  5147. $thinkingMode = 'disabled';
  5148. } elseif ($model === 'deepseek-reasoner') {
  5149. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5150. $model = 'deepseek-v4-flash';
  5151. $thinkingMode = 'enabled';
  5152. }
  5153. $post_data = [
  5154. 'model' => $model,
  5155. 'messages' => $messages,
  5156. // 'max_tokens' => 8192,
  5157. 'temperature' => 0.2,
  5158. 'frequency_penalty' => 0,
  5159. 'presence_penalty' => 0,
  5160. 'response_format' => ['type' => 'text'],
  5161. 'thinking' => ['type' => $thinkingMode],
  5162. 'stream' => true // 启用流式输出
  5163. ];
  5164. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5165. // 根据模型类型选择调用方法
  5166. $fullContent = '';
  5167. $fullReasoningContent = '';
  5168. $usage = [];
  5169. try {
  5170. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5171. // DeepSeek 官方模型使用 DeepSeek API
  5172. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5173. } else if (in_array($model, $this->gpt_text_models)) {
  5174. // GPT-5.4 模型使用 TokenRouter API
  5175. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5176. } else {
  5177. // 其他模型使用火山引擎API
  5178. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5179. }
  5180. // 验证返回值类型
  5181. if (!is_iterable($streamGenerator)) {
  5182. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5183. dLog('deepseek')->error('chat流式生成器无效', [
  5184. 'generator_type' => $errorType,
  5185. 'model' => $model,
  5186. 'anime_id' => $anime_id,
  5187. 'episode_number' => $episode_number
  5188. ]);
  5189. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5190. 'type' => $errorType,
  5191. 'model' => $model
  5192. ]);
  5193. yield [
  5194. 'type' => 'error',
  5195. 'episode' => [],
  5196. 'answer' => '',
  5197. 'reasoning' => '',
  5198. 'usage' => [],
  5199. 'error' => '接口返回数据异常,请重新请求'
  5200. ];
  5201. return;
  5202. }
  5203. // 处理流式输出
  5204. foreach ($streamGenerator as $chunk) {
  5205. if (isset($chunk['type'])) {
  5206. if ($chunk['type'] === 'done') {
  5207. // 最终结果
  5208. $fullContent = $chunk['full_content'];
  5209. $fullReasoningContent = $chunk['full_reasoning'];
  5210. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5211. } else {
  5212. // 逐块yield数据
  5213. yield $chunk;
  5214. }
  5215. }
  5216. }
  5217. } catch (\Exception $e) {
  5218. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5219. 'model' => $model,
  5220. 'anime_id' => $anime_id,
  5221. 'episode_number' => $episode_number,
  5222. 'trace' => $e->getTraceAsString()
  5223. ]);
  5224. logDB('deepseek', 'error', 'chat流式处理失败', [
  5225. 'error' => $e->getMessage(),
  5226. 'model' => $model
  5227. ]);
  5228. yield [
  5229. 'type' => 'error',
  5230. 'episode' => [],
  5231. 'answer' => '',
  5232. 'reasoning' => '',
  5233. 'usage' => [],
  5234. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5235. ];
  5236. return;
  5237. }
  5238. dLog('deepseek')->info('完整内容: '.$fullContent);
  5239. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5240. // 处理完整内容并返回最终结果
  5241. $episode_arr = handleEpisodeContent($fullContent);
  5242. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5243. if (empty($episode_arr['acts'])) {
  5244. // 未生成剧本相关内容,保存对话记录并返回提示
  5245. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5246. try {
  5247. $now = date('Y-m-d H:i:s');
  5248. // 保存对话记录
  5249. $records = [
  5250. [
  5251. 'uid' => $uid,
  5252. 'anime_id' => $anime_id,
  5253. 'sequence' => $episode_number,
  5254. 'role' => 'user',
  5255. 'content' => $prompt,
  5256. 'created_at' => $now,
  5257. 'updated_at' => $now
  5258. ],
  5259. [
  5260. 'uid' => $uid,
  5261. 'anime_id' => $anime_id,
  5262. 'sequence' => $episode_number,
  5263. 'role' => 'assistant',
  5264. 'content' => $fullContent,
  5265. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5266. 'created_at' => $now,
  5267. 'updated_at' => $now
  5268. ]
  5269. ];
  5270. DB::table('mp_anime_records')->insert($records);
  5271. } catch (\Exception $e) {
  5272. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5273. }
  5274. yield [
  5275. 'type' => 'done',
  5276. 'episode' => [],
  5277. 'answer' => $fullContent,
  5278. 'reasoning' => $fullReasoningContent,
  5279. 'usage' => $usage,
  5280. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5281. ];
  5282. return;
  5283. }
  5284. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5285. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5286. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5287. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5288. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5289. $existing_props = is_array($existing_props) ? $existing_props : [];
  5290. $now = date('Y-m-d H:i:s');
  5291. try {
  5292. DB::beginTransaction();
  5293. $saveResult = $this->saveEpisodeVersionData(
  5294. $anime_id,
  5295. $episode_number,
  5296. $episode_arr,
  5297. $existing_roles,
  5298. $existing_scenes,
  5299. $existing_props,
  5300. $current_episode,
  5301. $base_episode,
  5302. $is_regenerate_version,
  5303. $content,
  5304. $now
  5305. );
  5306. $episode = $saveResult['episode'];
  5307. $episode_id = $saveResult['episode_id'];
  5308. $merged_roles = $saveResult['merged_roles'];
  5309. $merged_scenes = $saveResult['merged_scenes'];
  5310. $merged_props = $saveResult['merged_props'];
  5311. $record_content = $origin_prompt;
  5312. if ($uploaded_content !== '') {
  5313. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5314. }
  5315. $records = [
  5316. [
  5317. 'uid' => $uid,
  5318. 'anime_id' => $anime_id,
  5319. 'role' => 'user',
  5320. 'content' => $record_content,
  5321. 'sequence' => $episode_number,
  5322. 'episode_id' => $episode_id,
  5323. 'created_at' => $now,
  5324. 'updated_at' => $now
  5325. ],
  5326. [
  5327. 'uid' => $uid,
  5328. 'anime_id' => $anime_id,
  5329. 'role' => 'assistant',
  5330. 'content' => $fullContent,
  5331. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5332. 'sequence' => $episode_number,
  5333. 'episode_id' => $episode_id,
  5334. 'created_at' => $now,
  5335. 'updated_at' => $now
  5336. ]
  5337. ];
  5338. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5339. if (!$boolen4) {
  5340. Utils::throwError('20003:对话记录保存失败');
  5341. }
  5342. // 保存模型和内容到anime表
  5343. $update_anime_data = [
  5344. 'model' => $model,
  5345. 'updated_at' => $now
  5346. ];
  5347. if ($uploaded_content) {
  5348. $update_anime_data['content'] = $uploaded_content;
  5349. }
  5350. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5351. }catch (\Exception $e) {
  5352. DB::rollBack();
  5353. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5354. yield [
  5355. 'type' => 'done',
  5356. 'answer' => $fullContent,
  5357. 'reasoning' => $fullReasoningContent,
  5358. 'usage' => $usage,
  5359. 'error' => $e->getMessage(),
  5360. ];
  5361. return;
  5362. }
  5363. DB::commit();
  5364. if ($is_global_generate_pics) {
  5365. // // 批量生成全局角色图片
  5366. // $this->batchSetGlobalRoleImg([
  5367. // 'anime_id' => $anime_id,
  5368. // ], true);
  5369. // // 批量生成全局场景图片
  5370. // $this->batchSetGlobalSceneImg([
  5371. // 'anime_id' => $anime_id,
  5372. // ], true);
  5373. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5374. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5375. }
  5376. $episode['episode_id'] = $episode_id;
  5377. $episode['roles'] = $merged_roles;
  5378. $episode['scenes'] = $merged_scenes;
  5379. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5380. yield [
  5381. 'type' => 'done',
  5382. 'episode' => $episode,
  5383. 'answer' => $fullContent,
  5384. 'reasoning' => $fullReasoningContent,
  5385. 'usage' => $usage
  5386. ];
  5387. }
  5388. public function addChatForAce($data) {
  5389. $uid = Site::getUid();
  5390. $anime_id = getProp($data, 'anime_id');
  5391. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5392. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5393. if (!$anime) Utils::throwError('20003:对话不存在');
  5394. $file = getProp($data, 'file');
  5395. $content = getProp($data, 'content', '');
  5396. $bid = getProp($data, 'bid', 0);
  5397. $script_id = getProp($data, 'script_id', 0);
  5398. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5399. $prompt = getProp($data, 'prompt');
  5400. $is_multi = getProp($anime, 'is_multi');
  5401. $is_single = (int)$is_multi !== 1;
  5402. $extra_products = getProp($data, 'products', []);
  5403. if (!$extra_products) {
  5404. $extra_products = getProp($anime, 'extra_products');
  5405. if ($extra_products) {
  5406. $extra_products = json_decode($extra_products, true);
  5407. }else {
  5408. $extra_products = [];
  5409. }
  5410. }else {
  5411. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5412. }
  5413. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5414. $anime_script_id = getProp($anime, 'script_id');
  5415. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5416. $cpid = Site::getCpid();
  5417. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5418. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5419. ->where('mapping.script_id', $anime_script_id)
  5420. ->where('product.cpid', $cpid)
  5421. ->where('product.is_deleted', 0);
  5422. $mappings = $script_products_mappings->select(
  5423. 'mapping.product_id',
  5424. 'mapping.episode_number',
  5425. 'product.product_name',
  5426. 'product.type',
  5427. 'product.product',
  5428. 'product.pic_prompt',
  5429. 'product.url',
  5430. 'product.pic_task_id',
  5431. 'product.pic_task_status',
  5432. 'product.three_view_image_url'
  5433. )
  5434. ->get();
  5435. // 按 product_id 分组,合并 episode_number
  5436. $productMap = [];
  5437. foreach ($mappings as $item) {
  5438. $product_id = $item->product_id;
  5439. $product_name = $item->product_name;
  5440. // 处理product_name两边的符号
  5441. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5442. if (!isset($productMap[$product_id])) {
  5443. $productMap[$product_id] = [
  5444. 'product_id' => $product_id,
  5445. 'product_name' => $product_name,
  5446. 'type' => (int)$item->type,
  5447. 'product' => (int)$item->product,
  5448. 'pic_prompt' => $item->pic_prompt,
  5449. 'url' => $item->url,
  5450. 'pic_task_id' => $item->pic_task_id,
  5451. 'pic_task_status' => $item->pic_task_status,
  5452. 'episode_numbers' => [],
  5453. ];
  5454. }
  5455. // 添加 episode_number(去重)
  5456. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5457. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5458. }
  5459. }
  5460. // 将查询到的剧本资产合并到extra_products中
  5461. // 先构建extra_products的索引(以product_id为key,用于去重)
  5462. $extraProductsMap = [];
  5463. foreach ($extra_products as $item) {
  5464. $key = getProp($item, 'product_id');
  5465. if ($key) {
  5466. $extraProductsMap[$key] = $item;
  5467. }
  5468. }
  5469. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5470. foreach ($productMap as $product) {
  5471. $product_id = $product['product_id'];
  5472. // 如果不存在则添加(不带episode_number信息)
  5473. if (!isset($extraProductsMap[$product_id])) {
  5474. $extraProductsMap[$product_id] = [
  5475. 'product_id' => $product['product_id'],
  5476. 'product_name' => $product['product_name'],
  5477. 'type' => $product['type'],
  5478. 'product' => $product['product'],
  5479. 'pic_prompt' => $product['pic_prompt'],
  5480. 'url' => $product['url'],
  5481. 'pic_task_id' => $product['pic_task_id'],
  5482. 'pic_task_status' => $product['pic_task_status'],
  5483. ];
  5484. }
  5485. }
  5486. // 重新赋值给extra_products
  5487. $extra_products = array_values($extraProductsMap);
  5488. }
  5489. $user_anime_name = getProp($anime, 'anime_name');
  5490. // 处理提示词
  5491. if ($prompt && $extra_products) {
  5492. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5493. foreach($extra_products as $item) {
  5494. $product_name = getProp($item, 'product_name');
  5495. if ($product_name) {
  5496. // 替换 {product_name} 为 product_name
  5497. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5498. }
  5499. }
  5500. }
  5501. // 处理文本模型
  5502. $model = getProp($data, 'model');
  5503. if (!$model) {
  5504. // 用户没有输入,从anime表获取
  5505. $model = getProp($anime, 'model');
  5506. if (!$model) {
  5507. // anime表也没有,使用默认值
  5508. $model = 'deepseek-v4-pro';
  5509. }
  5510. }
  5511. // 验证模型是否在可用模型表中
  5512. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5513. $model = 'deepseek-v4-pro';
  5514. }
  5515. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5516. if ($prompt) {
  5517. $question .= "本次修改要求如下:\n{$prompt}";
  5518. }
  5519. // if (!$file && !$content && !$bid) {
  5520. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5521. // }
  5522. // 提取文件内容
  5523. if ($file) {
  5524. $content = $this->extractFileContent($file);
  5525. if (!$content) {
  5526. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5527. }
  5528. } elseif ($script_id) {
  5529. $content = $this->getContentByScriptId($script_id);
  5530. if (!$content) {
  5531. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5532. }
  5533. } elseif ($bid) {
  5534. $content = $this->getContentByBid($bid);
  5535. if (!$content) {
  5536. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5537. }
  5538. } elseif ($content) {
  5539. $content = filterContent($content);
  5540. } else {
  5541. $content = getProp($anime, 'content');
  5542. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5543. $need_generate_content = true;
  5544. }
  5545. }
  5546. // 美术风格
  5547. $input_art_style = getProp($data, 'art_style');
  5548. if (!$input_art_style) {
  5549. $mappedArtStyle = getProp($anime, 'art_style');
  5550. }else {
  5551. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5552. }
  5553. // 判断是否需要生成原文内容
  5554. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5555. // 如果需要生成原文内容,添加额外的要求
  5556. $content_generation_requirement = $need_generate_content
  5557. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5558. : "";
  5559. // 美术风格
  5560. if (!$mappedArtStyle) {
  5561. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5562. }else {
  5563. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5564. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5565. }else {
  5566. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5567. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5568. }
  5569. }
  5570. // 构建主体、场景和道具提示词
  5571. $extra_role_prompt = "\n";
  5572. $extra_scene_prompt = "\n";
  5573. $extra_prop_prompt = "\n";
  5574. $ref_products = []; // 参考资产
  5575. if ($extra_products) {
  5576. foreach($extra_products as $item) {
  5577. $product = getProp($item, 'product');
  5578. $product_name = getProp($item, 'product_name');
  5579. if ($product_name == '旁白') continue;
  5580. $ref_products[$product_name] = $item;
  5581. $pic_prompt = getProp($item, 'pic_prompt');
  5582. if ((int)$product === 1) {
  5583. // 拼接角色信息
  5584. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5585. } elseif ((int)$product === 2) {
  5586. // 拼接场景信息
  5587. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5588. } elseif ((int)$product === 3) {
  5589. // 拼接道具信息
  5590. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5591. }
  5592. }
  5593. // 优化提示词,融入剧本
  5594. if (!empty(trim($extra_role_prompt))) {
  5595. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5596. }
  5597. if (!empty(trim($extra_scene_prompt))) {
  5598. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5599. }
  5600. if (!empty(trim($extra_prop_prompt))) {
  5601. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5602. }
  5603. }
  5604. if ($anime_script_id && $is_single) {
  5605. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5606. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5607. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5608. }else {
  5609. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5610. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5611. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5612. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5613. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5614. {$extra_role_prompt}";
  5615. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5616. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5617. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5618. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5619. {$extra_scene_prompt}";
  5620. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5621. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5622. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5623. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5624. {$extra_prop_prompt}";
  5625. }
  5626. $systemPrompt = $is_single
  5627. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5628. 强制要求:
  5629. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5630. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5631. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5632. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5633. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5634. 普通要求:
  5635. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5636. $role_demo
  5637. $scene_demo
  5638. $prop_demo
  5639. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5640. 5.1片段分割逻辑(优先级从高到低):
  5641. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5642. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5643. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5644. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5645. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5646. - 片段数量格式为: 片段数量:8
  5647. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5648. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5649. 5.3分镜结构:每个分镜包含以下字段:
  5650. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5651. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5652. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5653. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5654. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5655. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5656. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5657. - 运镜:场景+画面描述+运镜
  5658. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5659. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5660. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5661. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5662. 6.{$mappedArtStyle_prompt}\n\n
  5663. 示例如下:\n
  5664. ###剧本名:西昆仑
  5665. ###故事梗概
  5666. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5667. ###剧本亮点
  5668. 亮点1:绝境奇药,生死一线
  5669. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5670. 亮点2:结拜兄妹,化解尴尬
  5671. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5672. 亮点3:纤发夺命,情愫暗涌
  5673. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5674. ###人物关系
  5675. 阿雪与梁萧之间存在兄妹之情。
  5676. ###核心矛盾
  5677. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5678. ###主体列表
  5679. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5680. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5681. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5682. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5683. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5684. 全景,正面拍摄,青年女性,亚洲人。
  5685. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5686. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5687. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5688. ###美术风格
  5689. 基础画风风格词:厚涂古风
  5690. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5691. ###场景列表
  5692. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5693. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5694. 无人物。}
  5695. ###分段剧本
  5696. 片段数量:8
  5697. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5698. ##片段1
  5699. 时长:12s
  5700. 分镜1
  5701. 出场角色:刀疤脸
  5702. 场景:边境小镇街道
  5703. 出场道具:酒杯-高脚杯
  5704. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5705. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5706. 配音台词:
  5707. 背景音效:
  5708. 分镜2
  5709. 出场角色:刀疤脸
  5710. 场景:悦来酒馆
  5711. 出场道具:酒杯-高脚杯
  5712. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5713. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5714. 配音台词:
  5715. 背景音效:
  5716. 分镜3
  5717. 出场角色:刀疤脸
  5718. 场景:悦来酒馆
  5719. 出场道具:酒杯-高脚杯
  5720. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5721. 运镜:从中景推向令牌特写。
  5722. 配音台词:
  5723. 背景音效:
  5724. 分镜4
  5725. 出场角色:刀疤脸
  5726. 场景:悦来酒馆
  5727. 出场道具:酒杯-高脚杯
  5728. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5729. 运镜:极速推向酒水溅起的瞬间。
  5730. 配音台词:
  5731. 背景音效:
  5732. 分镜5
  5733. 出场角色:刀疤脸
  5734. 场景:悦来酒馆
  5735. 出场道具:酒杯-高脚杯
  5736. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5737. 运镜:固定机位,利用倾斜构图制造压迫感。
  5738. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5739. 背景音效:
  5740. \n\n"
  5741. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5742. 强制要求:\n
  5743. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5744. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5745. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5746. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5747. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5748. 普通要求:\n
  5749. 1.剧本名(必须生成)必须与文档内容高度相关
  5750. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5751. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5752. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5753. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5754. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5755. {$extra_role_prompt}
  5756. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5757. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5758. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5759. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5760. {$extra_scene_prompt}
  5761. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5762. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5763. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5764. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5765. {$extra_prop_prompt}
  5766. 5.{$mappedArtStyle_prompt}\n\n
  5767. 示例如下:\n
  5768. ###剧本名:西昆仑
  5769. ###故事梗概
  5770. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5771. ###剧本亮点
  5772. 亮点1:绝境奇药,生死一线
  5773. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5774. 亮点2:结拜兄妹,化解尴尬
  5775. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5776. 亮点3:纤发夺命,情愫暗涌
  5777. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5778. ###人物关系
  5779. 阿雪与梁萧之间存在兄妹之情。
  5780. ###核心矛盾
  5781. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5782. ###主体列表
  5783. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5784. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5785. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5786. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5787. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5788. 全景,正面拍摄,青年女性,亚洲人。
  5789. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5790. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5791. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5792. ###美术风格
  5793. 基础画风风格词:厚涂古风
  5794. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5795. ###场景列表
  5796. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5797. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5798. 无人物。}
  5799. ###道具列表
  5800. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5801. // 构建消息
  5802. $messages = [
  5803. [
  5804. 'role' => 'system',
  5805. 'content' => $systemPrompt
  5806. ],
  5807. [
  5808. 'role' => 'user',
  5809. 'content' => "以下是文档内容:
  5810. {$content}
  5811. 用户问题:
  5812. {$question}"
  5813. ]
  5814. ];
  5815. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5816. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5817. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5818. if ($model === 'deepseek-chat') {
  5819. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5820. $model = 'deepseek-v4-flash';
  5821. $thinkingMode = 'disabled';
  5822. } elseif ($model === 'deepseek-reasoner') {
  5823. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5824. $model = 'deepseek-v4-flash';
  5825. $thinkingMode = 'enabled';
  5826. }
  5827. $post_data = [
  5828. 'model' => $model,
  5829. 'messages' => $messages,
  5830. // 'max_tokens' => 8192,
  5831. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5832. 'frequency_penalty' => 0,
  5833. 'presence_penalty' => 0,
  5834. 'response_format' => ['type' => 'text'],
  5835. 'thinking' => ['type'=>$thinkingMode],
  5836. 'stream' => true // 启用流式输出
  5837. ];
  5838. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5839. // 根据模型类型选择调用方法
  5840. $fullContent = '';
  5841. $fullReasoningContent = '';
  5842. $usage = [];
  5843. try {
  5844. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5845. // DeepSeek 官方模型使用 DeepSeek API
  5846. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5847. } else if (in_array($model, $this->gpt_text_models)) {
  5848. // GPT-5.4 模型使用 TokenRouter API
  5849. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5850. } else {
  5851. // 其他模型使用火山引擎API
  5852. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5853. }
  5854. // 验证返回值类型
  5855. if (!is_iterable($streamGenerator)) {
  5856. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5857. dLog('deepseek')->error('addChat流式生成器无效', [
  5858. 'generator_type' => $errorType,
  5859. 'model' => $model,
  5860. 'anime_id' => $anime_id
  5861. ]);
  5862. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5863. 'type' => $errorType,
  5864. 'model' => $model
  5865. ]);
  5866. yield [
  5867. 'type' => 'error',
  5868. 'script' => [],
  5869. 'episode' => [],
  5870. 'answer' => '',
  5871. 'reasoning' => '',
  5872. 'usage' => [],
  5873. 'error' => '接口返回数据异常,请重新请求'
  5874. ];
  5875. return;
  5876. }
  5877. // 处理流式输出
  5878. foreach ($streamGenerator as $chunk) {
  5879. if (isset($chunk['type'])) {
  5880. if ($chunk['type'] === 'done') {
  5881. // 最终结果
  5882. $fullContent = $chunk['full_content'];
  5883. $fullReasoningContent = $chunk['full_reasoning'];
  5884. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5885. } else {
  5886. // 逐块yield数据
  5887. yield $chunk;
  5888. }
  5889. }
  5890. }
  5891. } catch (\Exception $e) {
  5892. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5893. 'model' => $model,
  5894. 'anime_id' => $anime_id,
  5895. 'trace' => $e->getTraceAsString()
  5896. ]);
  5897. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5898. 'error' => $e->getMessage(),
  5899. 'model' => $model
  5900. ]);
  5901. yield [
  5902. 'type' => 'error',
  5903. 'script' => [],
  5904. 'episode' => [],
  5905. 'answer' => '',
  5906. 'reasoning' => '',
  5907. 'usage' => [],
  5908. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5909. ];
  5910. return;
  5911. }
  5912. dLog('deepseek')->info('完整内容: '.$fullContent);
  5913. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5914. // 处理完整内容并返回最终结果
  5915. $script_arr = [];
  5916. if ($fullContent) {
  5917. $script_arr = handleScriptContentForAce($fullContent);
  5918. dLog('deepseek')->info('解析内容', $script_arr);
  5919. logDB('deepseek', 'info', '解析内容', $script_arr);
  5920. }
  5921. if (empty($script_arr['roles'])) {
  5922. // 未生成剧本相关内容,保存对话记录并返回提示
  5923. dLog('deepseek')->info('未生成剧本相关的内容');
  5924. try {
  5925. DB::beginTransaction();
  5926. $now = date('Y-m-d H:i:s');
  5927. // 保存对话记录
  5928. $records = [
  5929. [
  5930. 'uid' => $uid,
  5931. 'anime_id' => $anime_id,
  5932. 'sequence' => 0,
  5933. 'role' => 'user',
  5934. 'content' => $prompt,
  5935. 'created_at' => $now,
  5936. 'updated_at' => $now
  5937. ],
  5938. [
  5939. 'uid' => $uid,
  5940. 'anime_id' => $anime_id,
  5941. 'sequence' => 0,
  5942. 'role' => 'assistant',
  5943. // 'content' => $fullContent,
  5944. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5945. 'created_at' => $now,
  5946. 'updated_at' => $now
  5947. ]
  5948. ];
  5949. DB::table('mp_anime_records')->insert($records);
  5950. DB::commit();
  5951. } catch (\Exception $e) {
  5952. DB::rollBack();
  5953. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5954. }
  5955. yield [
  5956. 'type' => 'done',
  5957. 'script' => [],
  5958. 'episode' => [],
  5959. 'answer' => $fullContent,
  5960. 'reasoning' => $fullReasoningContent,
  5961. 'usage' => $usage,
  5962. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5963. ];
  5964. return;
  5965. }
  5966. // 如果需要生成原文内容,从script_arr中提取
  5967. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5968. $content = $script_arr['content'];
  5969. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5970. if (!$content) {
  5971. yield [
  5972. 'type' => 'done',
  5973. 'script' => [],
  5974. 'episode' => [],
  5975. 'answer' => $fullContent,
  5976. 'reasoning' => $fullReasoningContent,
  5977. 'usage' => $usage,
  5978. 'error' => '未生成剧本内容,请调整提示词再试'
  5979. ];
  5980. return;
  5981. }
  5982. }
  5983. // 替换美术风格
  5984. if ($mappedArtStyle !== '') {
  5985. $script_arr['art_style'] = $mappedArtStyle;
  5986. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5987. }
  5988. // 新建动漫
  5989. if ($user_anime_name == '新剧本策划') {
  5990. $anime_name = getProp($script_arr, 'script_name');
  5991. // if (!$anime_name) {
  5992. // // 未识别到剧本名,保存对话记录并返回提示
  5993. // dLog('deepseek')->info('未能识别到剧本名称');
  5994. // try {
  5995. // DB::beginTransaction();
  5996. // $now = date('Y-m-d H:i:s');
  5997. // // 保存对话记录
  5998. // $records = [
  5999. // [
  6000. // 'uid' => $uid,
  6001. // 'anime_id' => $anime_id,
  6002. // 'sequence' => 0,
  6003. // 'role' => 'user',
  6004. // 'content' => $prompt,
  6005. // 'created_at' => $now,
  6006. // 'updated_at' => $now
  6007. // ],
  6008. // [
  6009. // 'uid' => $uid,
  6010. // 'anime_id' => $anime_id,
  6011. // 'sequence' => 0,
  6012. // 'role' => 'assistant',
  6013. // 'content' => '未能生成剧本名称,请重试',
  6014. // 'created_at' => $now,
  6015. // 'updated_at' => $now
  6016. // ]
  6017. // ];
  6018. // DB::table('mp_anime_records')->insert($records);
  6019. // DB::commit();
  6020. // } catch (\Exception $e) {
  6021. // DB::rollBack();
  6022. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6023. // }
  6024. // yield [
  6025. // 'type' => 'done',
  6026. // 'script' => [],
  6027. // 'episode' => [],
  6028. // 'answer' => $fullContent,
  6029. // 'reasoning' => $fullReasoningContent,
  6030. // 'usage' => $usage,
  6031. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6032. // ];
  6033. // return;
  6034. // }
  6035. // 确认对话名称唯一性
  6036. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6037. $anime_name = $anime_name . '_' . date('YmdHis');
  6038. }
  6039. }else {
  6040. $anime_name = $user_anime_name;
  6041. }
  6042. $table_data = [
  6043. 'user_id' => $uid,
  6044. 'anime_name' => $anime_name,
  6045. 'model' => $model,
  6046. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6047. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6048. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6049. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6050. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6051. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6052. 'art_style_type' => $input_art_style,
  6053. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6054. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6055. 'status' => '解析完成',
  6056. 'content' => $content,
  6057. 'is_multi' => $is_multi,
  6058. 'ace_mode' => $ace_mode,
  6059. 'generate_status' => '待执行',
  6060. 'updated_at' => date('Y-m-d H:i:s')
  6061. ];
  6062. if ($table_data['content']) {
  6063. $chapters = splitContent($table_data['content']);
  6064. $chapter_count = count($chapters);
  6065. if ($chapter_count > 0) {
  6066. $table_data['start_episode_sequence'] = 1;
  6067. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6068. }
  6069. }
  6070. if ($extra_products) {
  6071. $table_data['extra_products'] = json_encode($extra_products, 256);
  6072. }
  6073. // 如果有剧本ID则进行绑定
  6074. if ($script_id) {
  6075. $table_data['script_id'] = $script_id;
  6076. }
  6077. $single_episode = [];
  6078. try {
  6079. DB::beginTransaction();
  6080. $now = date('Y-m-d H:i:s');
  6081. // 更新动漫大纲
  6082. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6083. if (!$boolen) {
  6084. dLog('deepseek')->info('动漫保存失败', $table_data);
  6085. Utils::throwError('20003:动漫保存失败');
  6086. }
  6087. // 保存对话记录
  6088. $records = [
  6089. [
  6090. 'uid' => $uid,
  6091. 'anime_id' => $anime_id,
  6092. 'sequence' => 0,
  6093. 'role' => 'user',
  6094. 'content' => $prompt,
  6095. 'created_at' => date('Y-m-d H:i:s'),
  6096. 'updated_at' => date('Y-m-d H:i:s')
  6097. ],
  6098. [
  6099. 'uid' => $uid,
  6100. 'anime_id' => $anime_id,
  6101. 'sequence' => 0,
  6102. 'role' => 'assistant',
  6103. 'content' => $fullContent,
  6104. 'created_at' => date('Y-m-d H:i:s'),
  6105. 'updated_at' => date('Y-m-d H:i:s')
  6106. ]
  6107. ];
  6108. // 保存对话记录
  6109. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6110. if (!$boolen3) {
  6111. Utils::throwError('20003:对话记录保存失败');
  6112. }
  6113. if ($is_single) {
  6114. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6115. if (empty($episode_arr['acts'])) {
  6116. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6117. }
  6118. $saveResult = $this->saveEpisodeVersionData(
  6119. $anime_id,
  6120. 1,
  6121. $episode_arr,
  6122. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6123. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6124. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6125. null,
  6126. null,
  6127. false,
  6128. $content,
  6129. $now,
  6130. $ref_products
  6131. );
  6132. $single_episode = $saveResult['episode'];
  6133. $episode_id = $saveResult['episode_id'];
  6134. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6135. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6136. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6137. 'props' => json_encode($saveResult['merged_props'], 256),
  6138. 'updated_at' => $now
  6139. ]);
  6140. if ($boolen5 === false) {
  6141. Utils::throwError('20003:单剧集主表资源同步失败');
  6142. }
  6143. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6144. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6145. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6146. $episode_record_content = '确认分镜大纲';
  6147. if ($content !== '') {
  6148. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6149. }
  6150. $episode_records = [
  6151. [
  6152. 'uid' => $uid,
  6153. 'anime_id' => $anime_id,
  6154. 'role' => 'user',
  6155. 'content' => $episode_record_content,
  6156. 'sequence' => 1,
  6157. 'episode_id' => $episode_id,
  6158. 'created_at' => $now,
  6159. 'updated_at' => $now
  6160. ],
  6161. [
  6162. 'uid' => $uid,
  6163. 'anime_id' => $anime_id,
  6164. 'role' => 'assistant',
  6165. 'content' => $fullContent,
  6166. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6167. 'sequence' => 1,
  6168. 'episode_id' => $episode_id,
  6169. 'created_at' => $now,
  6170. 'updated_at' => $now
  6171. ]
  6172. ];
  6173. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6174. if (!$boolen4) {
  6175. Utils::throwError('20003:单剧集分镜记录保存失败');
  6176. }
  6177. }
  6178. }catch (\Exception $e) {
  6179. DB::rollBack();
  6180. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6181. yield [
  6182. 'type' => 'done',
  6183. 'answer' => $fullContent,
  6184. 'reasoning' => $fullReasoningContent,
  6185. 'usage' => $usage,
  6186. 'error' => $e->getMessage(),
  6187. ];
  6188. return;
  6189. }
  6190. DB::commit();
  6191. dLog('deepseek')->info('保存完毕');
  6192. if ($is_single && !empty($single_episode)) {
  6193. // $this->batchSetGlobalRoleImg([
  6194. // 'anime_id' => $anime_id,
  6195. // ]);
  6196. // $this->batchSetGlobalSceneImg([
  6197. // 'anime_id' => $anime_id,
  6198. // ]);
  6199. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6200. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6201. }
  6202. $table_data['anime_id'] = $anime_id;
  6203. $table_data['roles'] = json_decode($table_data['roles'], true);
  6204. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6205. // $table_data['episodes'] = $script_arr['episodes'];
  6206. unset($table_data['created_at']);
  6207. unset($table_data['updated_at']);
  6208. unset($table_data['status']);
  6209. dLog('deepseek')->info('开始返回');
  6210. yield [
  6211. 'type' => 'done',
  6212. 'script' => $table_data,
  6213. 'episode' => $single_episode,
  6214. 'answer' => $fullContent,
  6215. 'reasoning' => $fullReasoningContent,
  6216. 'usage' => $usage
  6217. ];
  6218. }
  6219. public function reGenerateAnimeForAce($data) {
  6220. $uid = Site::getUid();
  6221. $file = getProp($data, 'file');
  6222. $content = getProp($data, 'content', '');
  6223. $bid = getProp($data, 'bid', 0);
  6224. $script_id = getProp($data, 'script_id', 0);
  6225. $anime_id = getProp($data, 'anime_id');
  6226. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6227. if (!$anime) {
  6228. Utils::throwError('20003:该对话不存在');
  6229. }
  6230. $is_multi = getProp($anime, 'is_multi', 1);
  6231. $is_single = (int)$is_multi !== 1;
  6232. $extra_products = getProp($data, 'products', []);
  6233. if (!$extra_products) {
  6234. $extra_products = getProp($anime, 'extra_products');
  6235. if ($extra_products) {
  6236. $extra_products = json_decode($extra_products, true);
  6237. }else {
  6238. $extra_products = [];
  6239. }
  6240. }else {
  6241. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6242. }
  6243. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6244. $anime_script_id = getProp($anime, 'script_id');
  6245. if ($anime_script_id && $is_single) {
  6246. $cpid = Site::getCpid();
  6247. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6248. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6249. ->where('mapping.script_id', $anime_script_id)
  6250. ->where('product.cpid', $cpid)
  6251. ->where('product.is_deleted', 0);
  6252. $mappings = $script_products_mappings->select(
  6253. 'mapping.product_id',
  6254. 'mapping.episode_number',
  6255. 'product.product_name',
  6256. 'product.type',
  6257. 'product.product',
  6258. 'product.pic_prompt',
  6259. 'product.url',
  6260. 'product.pic_task_id',
  6261. 'product.pic_task_status',
  6262. 'product.three_view_image_url'
  6263. )
  6264. ->get();
  6265. // 按 product_id 分组,合并 episode_number
  6266. $productMap = [];
  6267. foreach ($mappings as $item) {
  6268. $product_id = $item->product_id;
  6269. $product_name = $item->product_name;
  6270. // 处理product_name两边的符号
  6271. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6272. if (!isset($productMap[$product_id])) {
  6273. $productMap[$product_id] = [
  6274. 'product_id' => $product_id,
  6275. 'product_name' => $product_name,
  6276. 'type' => (int)$item->type,
  6277. 'product' => (int)$item->product,
  6278. 'pic_prompt' => $item->pic_prompt,
  6279. 'url' => $item->url,
  6280. 'pic_task_id' => $item->pic_task_id,
  6281. 'pic_task_status' => $item->pic_task_status,
  6282. 'episode_numbers' => [],
  6283. ];
  6284. }
  6285. // 添加 episode_number(去重)
  6286. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6287. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6288. }
  6289. }
  6290. // 将查询到的剧本资产合并到extra_products中
  6291. // 先构建extra_products的索引(以product_id为key,用于去重)
  6292. $extraProductsMap = [];
  6293. foreach ($extra_products as $item) {
  6294. $key = getProp($item, 'product_id');
  6295. if ($key) {
  6296. $extraProductsMap[$key] = $item;
  6297. }
  6298. }
  6299. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6300. foreach ($productMap as $product) {
  6301. $product_id = $product['product_id'];
  6302. // 如果不存在则添加(不带episode_number信息)
  6303. if (!isset($extraProductsMap[$product_id])) {
  6304. $extraProductsMap[$product_id] = [
  6305. 'product_id' => $product['product_id'],
  6306. 'product_name' => $product['product_name'],
  6307. 'type' => $product['type'],
  6308. 'product' => $product['product'],
  6309. 'pic_prompt' => $product['pic_prompt'],
  6310. 'url' => $product['url'],
  6311. 'pic_task_id' => $product['pic_task_id'],
  6312. 'pic_task_status' => $product['pic_task_status'],
  6313. ];
  6314. }
  6315. }
  6316. // 重新赋值给extra_products
  6317. $extra_products = array_values($extraProductsMap);
  6318. }
  6319. $user_anime_name = getProp($anime, 'anime_name');
  6320. $prompt = getProp($data, 'prompt');
  6321. // 处理提示词
  6322. if ($prompt && $extra_products) {
  6323. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6324. foreach($extra_products as $item) {
  6325. $product_name = getProp($item, 'product_name');
  6326. if ($product_name) {
  6327. // 替换 {product_name} 为 product_name
  6328. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6329. }
  6330. }
  6331. }
  6332. // 处理文本模型
  6333. $model = getProp($data, 'model');
  6334. if (!$model) {
  6335. // 用户没有输入,从anime表获取
  6336. $model = getProp($anime, 'model');
  6337. if (!$model) {
  6338. // anime表也没有,使用默认值
  6339. $model = 'deepseek-v4-pro';
  6340. }
  6341. }
  6342. // 验证模型是否在可用模型表中
  6343. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6344. $model = 'deepseek-v4-pro';
  6345. }
  6346. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6347. if ($is_single) {
  6348. $episode_exists = DB::table('mp_anime_episodes')
  6349. ->where('anime_id', $anime_id)
  6350. ->where('sequence', 1)
  6351. ->exists();
  6352. if ($episode_exists) {
  6353. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6354. }
  6355. }
  6356. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6357. if ($prompt) {
  6358. $question .= "本次修改要求如下:\n{$prompt}";
  6359. }
  6360. // 提取文件内容
  6361. if ($file) {
  6362. $content = $this->extractFileContent($file);
  6363. if (!$content) {
  6364. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6365. }
  6366. } elseif ($script_id) {
  6367. $content = $this->getContentByScriptId($script_id);
  6368. if (!$content) {
  6369. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6370. }
  6371. } elseif ($bid) {
  6372. $content = $this->getContentByBid($bid);
  6373. if (!$content) {
  6374. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6375. }
  6376. } elseif ($content) {
  6377. $content = filterContent($content);
  6378. }else {
  6379. $content = filterContent(getProp($anime, 'content'));
  6380. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6381. $need_generate_content = true;
  6382. }
  6383. }
  6384. // 判断是否需要生成原文内容
  6385. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6386. // 如果需要生成原文内容,添加额外的要求
  6387. $content_generation_requirement = $need_generate_content
  6388. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6389. : "";
  6390. // 美术风格
  6391. $input_art_style = getProp($data, 'art_style');
  6392. if (!$input_art_style) {
  6393. $mappedArtStyle = getProp($anime, 'art_style');
  6394. }else {
  6395. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6396. }
  6397. if (!$mappedArtStyle) {
  6398. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6399. }else {
  6400. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6401. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6402. }else {
  6403. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6404. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6405. }
  6406. }
  6407. // 构建主体、场景和道具提示词
  6408. $extra_role_prompt = "\n";
  6409. $extra_scene_prompt = "\n";
  6410. $extra_prop_prompt = "\n";
  6411. $ref_products = []; // 参考资产
  6412. if ($extra_products) {
  6413. foreach($extra_products as $item) {
  6414. $product = getProp($item, 'product');
  6415. $product_name = getProp($item, 'product_name');
  6416. if ($product_name == '旁白') continue;
  6417. $ref_products[$product_name] = $item;
  6418. $pic_prompt = getProp($item, 'pic_prompt');
  6419. if ((int)$product === 1) {
  6420. // 拼接角色信息
  6421. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6422. } elseif ((int)$product === 2) {
  6423. // 拼接场景信息
  6424. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6425. } elseif ((int)$product === 3) {
  6426. // 拼接道具信息
  6427. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6428. }
  6429. }
  6430. // 优化提示词,融入剧本
  6431. if (!empty(trim($extra_role_prompt))) {
  6432. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6433. }
  6434. if (!empty(trim($extra_scene_prompt))) {
  6435. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6436. }
  6437. if (!empty(trim($extra_prop_prompt))) {
  6438. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6439. }
  6440. }
  6441. if ($anime_script_id && $is_single) {
  6442. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6443. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6444. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6445. }else {
  6446. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6447. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6448. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6449. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6450. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6451. {$extra_role_prompt}";
  6452. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6453. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6454. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6455. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6456. {$extra_scene_prompt}";
  6457. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6458. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6459. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6460. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6461. {$extra_prop_prompt}";
  6462. }
  6463. $system_message = ['role'=>'system', 'content'=>$is_single
  6464. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6465. 强制要求:
  6466. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6467. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6468. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6469. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6470. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6471. 普通要求:
  6472. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6473. $role_demo
  6474. $scene_demo
  6475. $prop_demo
  6476. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6477. 5.1片段分割逻辑(优先级从高到低):
  6478. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6479. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6480. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6481. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6482. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6483. - 片段数量格式为: 片段数量:8
  6484. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6485. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6486. 5.3分镜结构:每个分镜包含以下字段:
  6487. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6488. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6489. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6490. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6491. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6492. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6493. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6494. - 运镜:场景+画面描述+运镜
  6495. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6496. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6497. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6498. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6499. 6.{$mappedArtStyle_prompt}\n\n
  6500. 示例如下:\n
  6501. ###剧本名:西昆仑
  6502. ###故事梗概
  6503. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6504. ###剧本亮点
  6505. 亮点1:绝境奇药,生死一线
  6506. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6507. 亮点2:结拜兄妹,化解尴尬
  6508. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6509. 亮点3:纤发夺命,情愫暗涌
  6510. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6511. ###人物关系
  6512. 阿雪与梁萧之间存在兄妹之情。
  6513. ###核心矛盾
  6514. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6515. ###主体列表
  6516. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6517. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6518. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6519. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6520. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6521. 全景,正面拍摄,青年女性,亚洲人。
  6522. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6523. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6524. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6525. ###美术风格
  6526. 基础画风风格词:厚涂古风
  6527. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6528. ###场景列表
  6529. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6530. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6531. 无人物。}
  6532. ###分段剧本
  6533. 片段数量:8
  6534. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6535. ##片段1
  6536. 时长:12s
  6537. 分镜1
  6538. 出场角色:刀疤脸
  6539. 场景:边境小镇街道
  6540. 出场道具:酒杯-高脚杯
  6541. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6542. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6543. 配音台词:
  6544. 背景音效:
  6545. 分镜2
  6546. 出场角色:刀疤脸
  6547. 场景:悦来酒馆
  6548. 出场道具:酒杯-高脚杯
  6549. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6550. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6551. 配音台词:
  6552. 背景音效:
  6553. 分镜3
  6554. 出场角色:刀疤脸
  6555. 场景:悦来酒馆
  6556. 出场道具:酒杯-高脚杯
  6557. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6558. 运镜:从中景推向令牌特写。
  6559. 配音台词:
  6560. 背景音效:
  6561. 分镜4
  6562. 出场角色:刀疤脸
  6563. 场景:悦来酒馆
  6564. 出场道具:酒杯-高脚杯
  6565. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6566. 运镜:极速推向酒水溅起的瞬间。
  6567. 配音台词:
  6568. 背景音效:
  6569. 分镜5
  6570. 出场角色:刀疤脸
  6571. 场景:悦来酒馆
  6572. 出场道具:酒杯-高脚杯
  6573. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6574. 运镜:固定机位,利用倾斜构图制造压迫感。
  6575. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6576. 背景音效:
  6577. \n\n"
  6578. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6579. 强制要求:\n
  6580. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6581. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6582. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6583. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6584. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6585. 普通要求:\n
  6586. 1.剧本名(必须生成)必须与文档内容高度相关
  6587. $role_demo
  6588. $scene_demo
  6589. $prop_demo
  6590. 5.{$mappedArtStyle_prompt}\n\n
  6591. 示例如下:\n
  6592. ###剧本名:西昆仑
  6593. ###故事梗概
  6594. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6595. ###剧本亮点
  6596. 亮点1:绝境奇药,生死一线
  6597. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6598. 亮点2:结拜兄妹,化解尴尬
  6599. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6600. 亮点3:纤发夺命,情愫暗涌
  6601. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6602. ###人物关系
  6603. 阿雪与梁萧之间存在兄妹之情。
  6604. ###核心矛盾
  6605. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6606. ###主体列表
  6607. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6608. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6609. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6610. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6611. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6612. 全景,正面拍摄,青年女性,亚洲人。
  6613. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6614. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6615. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6616. ###美术风格
  6617. 基础画风风格词:厚涂古风
  6618. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6619. ###场景列表
  6620. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6621. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6622. 无人物。}
  6623. ###道具列表
  6624. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6625. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6626. $episode_count = $this->extractEpisodeNumber($prompt);
  6627. if ((int)getProp($anime, 'is_multi') !== 1) {
  6628. yield [
  6629. 'type' => 'done',
  6630. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6631. 'reasoning' => '',
  6632. 'usage' => []
  6633. ];
  6634. return;
  6635. }
  6636. if ($episode_count) {
  6637. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6638. $system_message = [
  6639. 'role' => 'system',
  6640. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6641. 强制要求:\n
  6642. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6643. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6644. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6645. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6646. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6647. 普通要求:\n
  6648. 1.<故事梗概>控制在200-300字左右
  6649. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6650. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6651. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6652. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6653. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6654. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6655. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6656. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6657. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6658. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6659. 示例如下:\n
  6660. ###剧本名:西昆仑
  6661. ###故事梗概
  6662. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6663. ###剧本亮点
  6664. 亮点1:绝境奇药,生死一线
  6665. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6666. 亮点2:结拜兄妹,化解尴尬
  6667. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6668. 亮点3:纤发夺命,情愫暗涌
  6669. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6670. ###人物关系
  6671. 阿雪与梁萧之间存在兄妹之情。
  6672. ###核心矛盾
  6673. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6674. ###主体列表
  6675. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6676. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6677. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6678. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6679. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6680. 全景,正面拍摄,青年女性,亚洲人。
  6681. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6682. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6683. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6684. ###美术风格
  6685. 基础画风风格词:厚涂古风
  6686. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6687. ###场景列表
  6688. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6689. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6690. 无人物。}
  6691. ###分集详细内容
  6692. ##第1章 重生
  6693. 我重生了。
  6694. 源于一个男人偏执的暗恋。
  6695. ##第2章 相救
  6696. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6697. 我眼睛扫向站在锅炉后的卞大伟。"
  6698. ];
  6699. // 构建消息
  6700. $messages = [
  6701. $system_message,
  6702. [
  6703. 'role' => 'user',
  6704. 'content' => "以下是文档内容:
  6705. {$content}
  6706. 用户问题:
  6707. {$question}"
  6708. ]
  6709. ];
  6710. }else {
  6711. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6712. // 构建消息
  6713. $messages = [
  6714. $system_message,
  6715. [
  6716. 'role' => 'user',
  6717. 'content' => "以下是文档内容:
  6718. {$content}
  6719. 用户问题:
  6720. {$question}"
  6721. ]
  6722. ];
  6723. }else {
  6724. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6725. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6726. return (array)$value;
  6727. })->toArray();
  6728. array_unshift($messages, $system_message);
  6729. $messages[] = [
  6730. 'role' => 'user',
  6731. 'content' => $prompt
  6732. ];
  6733. }
  6734. }
  6735. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6736. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6737. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6738. if ($model === 'deepseek-chat') {
  6739. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6740. $model = 'deepseek-v4-flash';
  6741. $thinkingMode = 'disabled';
  6742. } elseif ($model === 'deepseek-reasoner') {
  6743. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6744. $model = 'deepseek-v4-flash';
  6745. $thinkingMode = 'enabled';
  6746. }
  6747. $post_data = [
  6748. 'model' => $model,
  6749. 'messages' => $messages,
  6750. // 'max_tokens' => 8192,
  6751. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6752. 'frequency_penalty' => 0,
  6753. 'presence_penalty' => 0,
  6754. 'response_format' => ['type' => 'text'],
  6755. 'thinking' => ['type' => $thinkingMode],
  6756. 'stream' => true // 启用流式输出
  6757. ];
  6758. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6759. // 根据模型类型选择调用方法
  6760. $fullContent = '';
  6761. $fullReasoningContent = '';
  6762. $usage = [];
  6763. // dd($post_data);
  6764. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6765. try {
  6766. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6767. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6768. } else if (in_array($model, $this->gpt_text_models)) {
  6769. // GPT-5.4 模型使用 TokenRouter API
  6770. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6771. } else {
  6772. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6773. }
  6774. // 验证返回值类型
  6775. if (!is_iterable($streamGenerator)) {
  6776. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6777. dLog('deepseek')->error('方法名流式生成器无效', [
  6778. 'generator_type' => $errorType,
  6779. 'model' => $model,
  6780. // 添加其他上下文信息
  6781. ]);
  6782. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6783. 'type' => $errorType,
  6784. 'model' => $model
  6785. ]);
  6786. yield [
  6787. 'type' => 'error',
  6788. // 根据方法返回相应的空数据结构
  6789. 'answer' => '',
  6790. 'reasoning' => '',
  6791. 'usage' => [],
  6792. 'error' => '接口返回数据异常,请重新请求'
  6793. ];
  6794. return;
  6795. }
  6796. // 处理流式输出
  6797. foreach ($streamGenerator as $chunk) {
  6798. if (isset($chunk['type'])) {
  6799. if ($chunk['type'] === 'done') {
  6800. $fullContent = $chunk['full_content'];
  6801. $fullReasoningContent = $chunk['full_reasoning'];
  6802. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6803. } else {
  6804. yield $chunk;
  6805. }
  6806. }
  6807. }
  6808. } catch (\Exception $e) {
  6809. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6810. 'model' => $model,
  6811. 'trace' => $e->getTraceAsString()
  6812. ]);
  6813. logDB('deepseek', 'error', '方法名流式处理失败', [
  6814. 'error' => $e->getMessage(),
  6815. 'model' => $model
  6816. ]);
  6817. yield [
  6818. 'type' => 'error',
  6819. // 根据方法返回相应的空数据结构
  6820. 'answer' => '',
  6821. 'reasoning' => '',
  6822. 'usage' => [],
  6823. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6824. ];
  6825. return;
  6826. }
  6827. dLog('deepseek')->info('完整内容: '.$fullContent);
  6828. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6829. // 处理完整内容并返回最终结果
  6830. $script_arr = [];
  6831. if ($fullContent) {
  6832. $script_arr = handleScriptContentForAce($fullContent);
  6833. dLog('deepseek')->info('解析内容', $script_arr);
  6834. logDB('deepseek', 'info', '解析内容', $script_arr);
  6835. }
  6836. if (empty($script_arr['roles'])) {
  6837. // 未生成剧本相关内容,保存对话记录并返回提示
  6838. dLog('deepseek')->info('未生成剧本相关的内容');
  6839. try {
  6840. $now = date('Y-m-d H:i:s');
  6841. // 保存对话记录
  6842. $records = [
  6843. [
  6844. 'uid' => $uid,
  6845. 'anime_id' => $anime_id,
  6846. 'sequence' => 0,
  6847. 'role' => 'user',
  6848. 'content' => $prompt,
  6849. 'created_at' => $now,
  6850. 'updated_at' => $now
  6851. ],
  6852. [
  6853. 'uid' => $uid,
  6854. 'anime_id' => $anime_id,
  6855. 'sequence' => 0,
  6856. 'role' => 'assistant',
  6857. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6858. 'created_at' => $now,
  6859. 'updated_at' => $now
  6860. ]
  6861. ];
  6862. DB::table('mp_anime_records')->insert($records);
  6863. } catch (\Exception $e) {
  6864. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6865. }
  6866. yield [
  6867. 'type' => 'done',
  6868. 'script' => [],
  6869. 'episode' => [],
  6870. 'answer' => $fullContent,
  6871. 'reasoning' => $fullReasoningContent,
  6872. 'usage' => $usage,
  6873. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6874. ];
  6875. return;
  6876. }
  6877. // 替换美术风格
  6878. if ($mappedArtStyle !== '') {
  6879. $script_arr['art_style'] = $mappedArtStyle;
  6880. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6881. }
  6882. if ($user_anime_name != '新剧本策划') {
  6883. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6884. // 确认对话名称唯一性
  6885. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6886. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6887. }
  6888. }else {
  6889. $anime_name = $user_anime_name;
  6890. }
  6891. $table_data = [
  6892. 'user_id' => $uid,
  6893. 'model' => $model,
  6894. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6895. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6896. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6897. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6898. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6899. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6900. 'art_style_type' => $input_art_style,
  6901. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6902. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6903. 'status' => '解析完成',
  6904. 'generate_status' => '待执行',
  6905. 'updated_at' => date('Y-m-d H:i:s')
  6906. ];
  6907. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6908. // 如果是修改集数,则将content内容更新(会改变原文)
  6909. if (isset($episode_count) && $episode_count > 0) {
  6910. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6911. $table_data['start_episode_sequence'] = 1;
  6912. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6913. }else {
  6914. // 如果需要生成原文内容,从script_arr中提取
  6915. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6916. $table_data['content'] = $script_arr['content'];
  6917. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6918. if (!$table_data['content']) {
  6919. yield [
  6920. 'type' => 'done',
  6921. 'script' => [],
  6922. 'episode' => [],
  6923. 'answer' => $fullContent,
  6924. 'reasoning' => $fullReasoningContent,
  6925. 'usage' => $usage,
  6926. 'error' => '未生成剧本内容,请调整提示词再试'
  6927. ];
  6928. return;
  6929. }
  6930. }
  6931. if (isset($table_data['content']) && $table_data['content']) {
  6932. $chapters = splitContent($table_data['content']);
  6933. $chapter_count = count($chapters);
  6934. if ($chapter_count > 0) {
  6935. $table_data['start_episode_sequence'] = 1;
  6936. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6937. }
  6938. }
  6939. }
  6940. if ($extra_products) {
  6941. $table_data['extra_products'] = json_encode($extra_products, 256);
  6942. }
  6943. $single_episode = [];
  6944. try {
  6945. DB::beginTransaction();
  6946. $now = date('Y-m-d H:i:s');
  6947. // 更新动漫大纲
  6948. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6949. if (!$boolen) {
  6950. dLog('deepseek')->info('对话修改失败', $table_data);
  6951. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6952. Utils::throwError('20003:对话修改失败');
  6953. }
  6954. // 保存对话记录
  6955. $records = [
  6956. [
  6957. 'uid' => $uid,
  6958. 'anime_id' => $anime_id,
  6959. 'sequence' => 0,
  6960. 'role' => 'user',
  6961. 'content' => $prompt,
  6962. 'created_at' => $now,
  6963. 'updated_at' => $now
  6964. ],
  6965. [
  6966. 'uid' => $uid,
  6967. 'anime_id' => $anime_id,
  6968. 'sequence' => 0,
  6969. 'role' => 'assistant',
  6970. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6971. 'content' => $fullContent,
  6972. 'created_at' => $now,
  6973. 'updated_at' => $now
  6974. ]
  6975. ];
  6976. // 保存对话记录
  6977. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6978. if (!$boolen3) {
  6979. Utils::throwError('20003:对话记录保存失败');
  6980. }
  6981. // 单剧集模式:生成并保存剧集信息
  6982. if ($is_single) {
  6983. $anime_name = getProp($anime, 'anime_name', '未命名');
  6984. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6985. if (empty($episode_arr['acts'])) {
  6986. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6987. }
  6988. $saveResult = $this->saveEpisodeVersionData(
  6989. $anime_id,
  6990. 1,
  6991. $episode_arr,
  6992. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6993. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6994. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6995. null,
  6996. null,
  6997. false,
  6998. $content,
  6999. $now,
  7000. $ref_products
  7001. );
  7002. $single_episode = $saveResult['episode'];
  7003. $episode_id = $saveResult['episode_id'];
  7004. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7005. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7006. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7007. 'props' => json_encode($saveResult['merged_props'], 256),
  7008. 'updated_at' => $now
  7009. ]);
  7010. if ($boolen5 === false) {
  7011. Utils::throwError('20003:单剧集主表资源同步失败');
  7012. }
  7013. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7014. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7015. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7016. $episode_record_content = '确认分镜大纲';
  7017. if ($content !== '') {
  7018. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7019. }
  7020. $episode_records = [
  7021. [
  7022. 'uid' => $uid,
  7023. 'anime_id' => $anime_id,
  7024. 'role' => 'user',
  7025. 'content' => $episode_record_content,
  7026. 'sequence' => 1,
  7027. 'episode_id' => $episode_id,
  7028. 'created_at' => $now,
  7029. 'updated_at' => $now
  7030. ],
  7031. [
  7032. 'uid' => $uid,
  7033. 'anime_id' => $anime_id,
  7034. 'role' => 'assistant',
  7035. 'content' => $fullContent,
  7036. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7037. 'sequence' => 1,
  7038. 'episode_id' => $episode_id,
  7039. 'created_at' => $now,
  7040. 'updated_at' => $now
  7041. ]
  7042. ];
  7043. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7044. if (!$boolen4) {
  7045. Utils::throwError('20003:单剧集分镜记录保存失败');
  7046. }
  7047. }
  7048. }catch (\Exception $e) {
  7049. DB::rollBack();
  7050. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7051. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7052. yield [
  7053. 'type' => 'done',
  7054. 'answer' => $fullContent,
  7055. 'reasoning' => $fullReasoningContent,
  7056. 'usage' => $usage,
  7057. 'error' => $e->getMessage(),
  7058. ];
  7059. return;
  7060. }
  7061. DB::commit();
  7062. dLog('deepseek')->info('保存完毕');
  7063. if ($is_single && !empty($single_episode)) {
  7064. // $this->batchSetGlobalRoleImg([
  7065. // 'anime_id' => $anime_id,
  7066. // ]);
  7067. // $this->batchSetGlobalSceneImg([
  7068. // 'anime_id' => $anime_id,
  7069. // ]);
  7070. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7071. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7072. }
  7073. $table_data['anime_id'] = $anime_id;
  7074. $table_data['roles'] = json_decode($table_data['roles'], true);
  7075. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7076. $table_data['props'] = json_decode($table_data['props'], true);
  7077. unset($table_data['updated_at']);
  7078. unset($table_data['status']);
  7079. yield [
  7080. 'type' => 'done',
  7081. 'script' => $table_data,
  7082. 'episode' => $single_episode,
  7083. 'answer' => $fullContent,
  7084. 'reasoning' => $fullReasoningContent,
  7085. 'usage' => $usage
  7086. ];
  7087. }
  7088. public function chatForAce($data) {
  7089. $uid = Site::getUid();
  7090. $anime_id = getProp($data, 'anime_id');
  7091. $file = getProp($data, 'file');
  7092. $content = getProp($data, 'content', '');
  7093. $bid = getProp($data, 'bid', 0);
  7094. $script_id = getProp($data, 'script_id', 0);
  7095. $episode_number = getProp($data, 'episode_number', 1);
  7096. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7097. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7098. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7099. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7100. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7101. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7102. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7103. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7104. $roles = is_array($roles) ? $roles : [];
  7105. $scenes = is_array($scenes) ? $scenes : [];
  7106. $extra_products = getProp($data, 'products', []);
  7107. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7108. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7109. $anime_script_id = getProp($anime, 'script_id');
  7110. if ($anime_script_id) {
  7111. $cpid = Site::getCpid();
  7112. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7113. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7114. ->where('mapping.script_id', $anime_script_id)
  7115. ->where('product.cpid', $cpid)
  7116. ->where('product.is_deleted', 0);
  7117. // 如果提供了 episode_number,则过滤指定集数
  7118. if ($episode_number !== null && $episode_number !== '') {
  7119. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7120. }
  7121. $mappings = $script_products_mappings->select(
  7122. 'mapping.product_id',
  7123. 'mapping.episode_number',
  7124. 'product.product_name',
  7125. 'product.type',
  7126. 'product.product',
  7127. 'product.pic_prompt',
  7128. 'product.url',
  7129. 'product.pic_task_id',
  7130. 'product.pic_task_status',
  7131. 'product.three_view_image_url'
  7132. )
  7133. ->get();
  7134. // 按 product_id 分组,合并 episode_number
  7135. $productMap = [];
  7136. foreach ($mappings as $item) {
  7137. $product_id = $item->product_id;
  7138. $product_name = $item->product_name;
  7139. // 处理product_name两边的符号
  7140. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7141. if (!isset($productMap[$product_id])) {
  7142. $productMap[$product_id] = [
  7143. 'product_id' => $product_id,
  7144. 'product_name' => $product_name,
  7145. 'type' => (int)$item->type,
  7146. 'product' => (int)$item->product,
  7147. 'pic_prompt' => $item->pic_prompt,
  7148. 'url' => $item->url,
  7149. 'pic_task_id' => $item->pic_task_id,
  7150. 'pic_task_status' => $item->pic_task_status,
  7151. 'episode_numbers' => [],
  7152. ];
  7153. }
  7154. // 添加 episode_number(去重)
  7155. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7156. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7157. }
  7158. }
  7159. // 将查询到的剧本资产合并到extra_products中
  7160. // 先构建extra_products的索引(以product_id+episode_number为key)
  7161. $extraProductsMap = [];
  7162. foreach ($extra_products as $item) {
  7163. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7164. $extraProductsMap[$key] = $item;
  7165. }
  7166. // 合并剧本资产(去重:product_id+episode_number)
  7167. foreach ($productMap as $product) {
  7168. foreach ($product['episode_numbers'] as $ep_num) {
  7169. $key = $product['product_id'] . '_' . $ep_num;
  7170. // 如果不存在则添加
  7171. if (!isset($extraProductsMap[$key])) {
  7172. $extraProductsMap[$key] = [
  7173. 'product_id' => $product['product_id'],
  7174. 'product_name' => $product['product_name'],
  7175. 'type' => $product['type'],
  7176. 'product' => $product['product'],
  7177. 'pic_prompt' => $product['pic_prompt'],
  7178. 'url' => $product['url'],
  7179. 'pic_task_id' => $product['pic_task_id'],
  7180. 'pic_task_status' => $product['pic_task_status'],
  7181. 'episode_number' => $ep_num,
  7182. ];
  7183. }
  7184. }
  7185. }
  7186. // 重新赋值给extra_products
  7187. $extra_products = array_values($extraProductsMap);
  7188. }
  7189. // 处理提示词
  7190. if ($prompt && $extra_products) {
  7191. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7192. foreach($extra_products as $item) {
  7193. $product_name = getProp($item, 'product_name');
  7194. if ($product_name) {
  7195. // 替换 {product_name} 为 product_name
  7196. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7197. }
  7198. }
  7199. }
  7200. // 获取最后一集序号
  7201. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7202. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7203. // 转换主体列表和场景列表的格式
  7204. // 获取参考主体或场景
  7205. if ((int)$episode_number === 1) {
  7206. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7207. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7208. }else {
  7209. $prev_episode_number = $episode_number - 1;
  7210. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7211. }
  7212. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7213. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7214. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7215. // 合并anime_products和extra_products(extra_products优先,去重)
  7216. $anime_products = getProp($anime, 'extra_products');
  7217. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7218. $ref_products = [];
  7219. foreach($anime_products as $item) {
  7220. $product_name = getProp($item, 'product_name');
  7221. $ref_products[$product_name] = $item;
  7222. }
  7223. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7224. $extra_roles = []; // 从extra_products中提取的角色
  7225. $extra_scenes = []; // 从extra_products中提取的场景
  7226. $extra_props = []; // 从extra_products中提取的道具
  7227. if ($extra_products && is_array($extra_products)) {
  7228. foreach($extra_products as $item) {
  7229. $product = (int)getProp($item, 'product');
  7230. $product_name = getProp($item, 'product_name');
  7231. if ($product_name == '旁白') continue;
  7232. $pic_prompt = getProp($item, 'pic_prompt');
  7233. $ref_products[$product_name] = $item;
  7234. if ($product === 1) {
  7235. // 角色
  7236. $extra_roles[$product_name] = [
  7237. 'role' => $product_name,
  7238. 'pic_prompt' => $pic_prompt,
  7239. 'url' => getProp($item, 'url', ''),
  7240. ];
  7241. } elseif ($product === 2) {
  7242. // 场景
  7243. $extra_scenes[$product_name] = [
  7244. 'scene' => $product_name,
  7245. 'pic_prompt' => $pic_prompt,
  7246. 'url' => getProp($item, 'url', ''),
  7247. ];
  7248. } elseif ($product === 3) {
  7249. // 道具
  7250. $extra_props[$product_name] = [
  7251. 'prop' => $product_name,
  7252. 'pic_prompt' => $pic_prompt,
  7253. 'url' => getProp($item, 'url', ''),
  7254. ];
  7255. }
  7256. }
  7257. }
  7258. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7259. $merged_roles = [];
  7260. foreach($ref_roles as $role) {
  7261. $role_name = getProp($role, 'role');
  7262. if (!isset($extra_roles[$role_name])) {
  7263. $merged_roles[$role_name] = $role;
  7264. }
  7265. }
  7266. // 添加extra_roles
  7267. foreach($extra_roles as $role_name => $role) {
  7268. $merged_roles[$role_name] = $role;
  7269. }
  7270. $ref_roles = array_values($merged_roles);
  7271. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7272. $merged_scenes = [];
  7273. foreach($ref_scenes as $scene) {
  7274. $scene_name = getProp($scene, 'scene');
  7275. if (!isset($extra_scenes[$scene_name])) {
  7276. $merged_scenes[$scene_name] = $scene;
  7277. }
  7278. }
  7279. // 添加extra_scenes
  7280. foreach($extra_scenes as $scene_name => $scene) {
  7281. $merged_scenes[$scene_name] = $scene;
  7282. }
  7283. $ref_scenes = array_values($merged_scenes);
  7284. // 合并ref_props和extra_props(extra_props优先,去重)
  7285. $merged_props = [];
  7286. foreach($ref_props as $prop) {
  7287. $prop_name = getProp($prop, 'prop');
  7288. if (!isset($extra_props[$prop_name])) {
  7289. $merged_props[$prop_name] = $prop;
  7290. }
  7291. }
  7292. // 添加extra_props
  7293. foreach($extra_props as $prop_name => $prop) {
  7294. $merged_props[$prop_name] = $prop;
  7295. }
  7296. $ref_props = array_values($merged_props);
  7297. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7298. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7299. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7300. // 构建强制主体、场景和道具提示词
  7301. $forced_roles_prompt = "";
  7302. $forced_scenes_prompt = "";
  7303. $forced_props_prompt = "";
  7304. if (!empty($extra_roles)) {
  7305. $forced_roles_list = "";
  7306. foreach($extra_roles as $role_name => $role) {
  7307. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7308. }
  7309. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7310. }
  7311. if (!empty($extra_scenes)) {
  7312. $forced_scenes_list = "";
  7313. foreach($extra_scenes as $scene_name => $scene) {
  7314. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7315. }
  7316. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7317. }
  7318. if (!empty($extra_props)) {
  7319. $forced_props_list = "";
  7320. foreach($extra_props as $prop_name => $prop) {
  7321. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7322. }
  7323. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7324. }
  7325. if ($anime_script_id) {
  7326. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7327. }else if ($roles_content) {
  7328. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7329. 主体范围:\n {$roles_content}\n
  7330. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7331. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7332. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7333. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7334. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7335. }else {
  7336. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7337. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7338. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7339. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7340. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7341. }
  7342. if ($anime_script_id) {
  7343. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7344. }else if ($scenes_content) {
  7345. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7346. 场景范围:\n {$scenes_content}\n
  7347. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7348. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7349. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7350. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7351. }else {
  7352. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7353. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7354. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7355. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7356. }
  7357. if ($anime_script_id) {
  7358. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7359. }else if ($props_content) {
  7360. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7361. 道具范围:\n {$props_content}\n
  7362. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7363. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7364. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7365. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7366. }else {
  7367. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7368. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7369. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7370. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7371. }
  7372. // 提取文件内容
  7373. if ($file) {
  7374. $uploaded_content = $this->extractFileContent($file);
  7375. if (!$uploaded_content) {
  7376. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7377. }
  7378. } elseif ($script_id) {
  7379. $uploaded_content = $this->getContentByScriptId($script_id);
  7380. if (!$uploaded_content) {
  7381. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7382. }
  7383. } elseif ($bid) {
  7384. $uploaded_content = $this->getContentByBid($bid);
  7385. if (!$uploaded_content) {
  7386. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7387. }
  7388. } elseif ($content) {
  7389. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7390. }
  7391. // elseif ($prompt) {
  7392. // $uploaded_content = filterContent($prompt);
  7393. // }
  7394. else {
  7395. $uploaded_content = '';
  7396. }
  7397. // 美术风格
  7398. $input_art_style = getProp($data, 'art_style');
  7399. if (!$input_art_style) {
  7400. $mappedArtStyle = getProp($anime, 'art_style');
  7401. }else {
  7402. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7403. }
  7404. if (!$mappedArtStyle) {
  7405. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7406. }else {
  7407. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7408. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7409. }else {
  7410. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7411. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7412. }
  7413. }
  7414. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7415. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7416. // 强制要求:
  7417. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7418. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7419. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7420. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7421. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7422. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7423. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7424. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7425. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7426. // 10.分镜要和场景列表、人物主体保持一致\n
  7427. // 普通要求:
  7428. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7429. // {$role_demo}
  7430. // {$scene_demo}
  7431. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7432. // 4.1片段分割逻辑(优先级从高到低):
  7433. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7434. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7435. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7436. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7437. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7438. // - 片段数量格式为: 片段数量:8
  7439. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7440. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7441. // 4.3分镜结构:每个分镜包含以下字段:
  7442. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7443. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7444. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7445. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7446. // - 运镜:场景+画面描述+运镜
  7447. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7448. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7449. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7450. // 5.$mappedArtStyle_prompt\n\n
  7451. // 示例格式:\n
  7452. // 第1集:隐形的守护者
  7453. // ###故事梗概
  7454. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7455. // ###美术风格
  7456. // 基础画风风格词:胡金铨武侠
  7457. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7458. // ###主体列表
  7459. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7460. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7461. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7462. // ###场景列表
  7463. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7464. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7465. // ###分段剧本
  7466. // 片段数量:8
  7467. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7468. // ##片段1
  7469. // 时长:12s
  7470. // 分镜1
  7471. // 场景:边境小镇街道
  7472. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7473. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7474. // 配音台词:
  7475. // 背景音效:
  7476. // 分镜2
  7477. // 场景:悦来酒馆
  7478. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7479. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7480. // 配音台词:
  7481. // 背景音效:
  7482. // 分镜3
  7483. // 场景:悦来酒馆
  7484. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7485. // 运镜:从中景推向令牌特写。
  7486. // 配音台词:
  7487. // 背景音效:
  7488. // 分镜4
  7489. // 场景:悦来酒馆
  7490. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7491. // 运镜:极速推向酒水溅起的瞬间。
  7492. // 配音台词:
  7493. // 背景音效:
  7494. // 分镜5
  7495. // 镜头描述
  7496. // 场景:悦来酒馆
  7497. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7498. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7499. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7500. // 背景音效:
  7501. // \n\n";
  7502. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7503. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7504. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7505. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7506. 普通要求:
  7507. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7508. {$role_demo}
  7509. {$scene_demo}
  7510. {$prop_demo}
  7511. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7512. 5.1片段分割逻辑(优先级从高到低):
  7513. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7514. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7515. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7516. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7517. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7518. - 片段数量格式为: 片段数量:8
  7519. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7520. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7521. 5.3分镜结构:每个分镜包含以下字段:
  7522. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7523. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7524. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7525. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7526. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7527. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7528. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7529. - 运镜:场景+画面描述+运镜
  7530. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7531. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7532. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7533. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7534. 6.《情绪-视听语言映射表》:
  7535. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7536. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7537. -----|---------|------------|----------------
  7538. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7539. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7540. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7541. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7542. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7543. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7544. -----|---------|------------|----------------
  7545. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7546. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7547. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7548. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7549. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7550. --------|---------|--------------|-------------
  7551. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7552. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7553. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7554. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7555. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7556. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7557. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7558. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7559. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7560. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7561. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7562. -----|---------|------------|------------
  7563. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7564. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7565. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7566. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7567. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7568. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7569. --------|---------|--------------|----------
  7570. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7571. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7572. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7573. 6.6 声音设计与潜意识影响 (Soundscape)
  7574. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7575. -----|---------|------------|------------------
  7576. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7577. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7578. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7579. 理论基石:
  7580. - The Five C's of Cinematography by Joseph V. Mascelli
  7581. - Film Art: An Introduction by David Bordwell
  7582. - Sight, Sound, Motion by Herbert Zettl
  7583. - Notes on the Cinematograph by Robert Bresson
  7584. \n\n
  7585. 7.{$mappedArtStyle_prompt}
  7586. 示例格式:\n
  7587. 第1集:隐形的守护者
  7588. ###故事梗概
  7589. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7590. ###美术风格
  7591. 基础画风风格词:胡金铨武侠
  7592. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7593. ###主体列表
  7594. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7595. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7596. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7597. ###场景列表
  7598. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7599. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7600. ###道具列表
  7601. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7602. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7603. ###分段剧本
  7604. 片段数量:8
  7605. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7606. ##片段1
  7607. 时长:12s
  7608. 分镜1
  7609. 出场角色:刀疤脸
  7610. 场景:边境小镇街道
  7611. 出场道具:酒杯-高脚杯
  7612. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7613. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7614. 配音台词:
  7615. 背景音效:
  7616. 分镜2
  7617. 出场角色:刀疤脸
  7618. 场景:悦来酒馆
  7619. 出场道具:酒杯-高脚杯
  7620. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7621. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7622. 配音台词:
  7623. 背景音效:
  7624. 分镜3
  7625. 出场角色:刀疤脸
  7626. 场景:悦来酒馆
  7627. 出场道具:酒杯-高脚杯
  7628. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7629. 运镜:从中景推向令牌特写。
  7630. 配音台词:
  7631. 背景音效:
  7632. 分镜4
  7633. 出场角色:刀疤脸
  7634. 场景:悦来酒馆
  7635. 出场道具:酒杯-高脚杯
  7636. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7637. 运镜:极速推向酒水溅起的瞬间。
  7638. 配音台词:
  7639. 背景音效:
  7640. 分镜5
  7641. 出场角色:刀疤脸
  7642. 场景:悦来酒馆
  7643. 出场道具:酒杯-高脚杯
  7644. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7645. 运镜:固定机位,利用倾斜构图制造压迫感。
  7646. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7647. 背景音效:
  7648. \n\n";
  7649. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7650. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7651. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7652. $prompt = $origin_prompt;
  7653. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7654. // 获取章节内容
  7655. $full_content = getProp($anime, 'content');
  7656. if ($uploaded_content) {
  7657. $full_content = $uploaded_content;
  7658. }
  7659. // 根据章节内容拆分章节
  7660. $chapters = splitContent($full_content);
  7661. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7662. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7663. $messages = [];
  7664. if ($prompt == '确认分镜大纲') {
  7665. // 暂时保留
  7666. $content = $chapter_content;
  7667. if ($is_single) $content = $full_content; // 单剧集使用全文
  7668. if (!$content) {
  7669. Utils::throwError('20003:章节内容无法获取,请确认');
  7670. }
  7671. $question = $is_single
  7672. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7673. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7674. // 构建消息
  7675. $messages[] =
  7676. [
  7677. 'role' => 'user',
  7678. 'content' => $question
  7679. ];
  7680. }else if ($prompt == '继续策划下一集') {
  7681. if ($is_single) {
  7682. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7683. }
  7684. $content = $chapter_content;
  7685. if (!$content) {
  7686. Utils::throwError('20003:章节内容无法获取,请确认');
  7687. }
  7688. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7689. // 获取上一集最后记录
  7690. $prev_sequence = $episode_number - 1;
  7691. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7692. // 构建消息
  7693. $messages[] =
  7694. [
  7695. 'role' => 'user',
  7696. 'content' => $question
  7697. ];
  7698. // dd($messages);
  7699. }else {
  7700. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7701. if (!$content) {
  7702. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7703. }
  7704. if (!$content) {
  7705. Utils::throwError('20003:章节内容无法获取,请确认');
  7706. }
  7707. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7708. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7709. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7710. if ($origin_prompt) {
  7711. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7712. }
  7713. $messages[] =
  7714. [
  7715. 'role' => 'user',
  7716. 'content' => $question
  7717. ];
  7718. }
  7719. // 处理文本模型
  7720. $model = getProp($data, 'model');
  7721. if (!$model) {
  7722. // 用户没有输入,从anime表获取
  7723. $model = getProp($anime, 'model');
  7724. if (!$model) {
  7725. // anime表也没有,使用默认值
  7726. $model = 'deepseek-v4-pro';
  7727. }
  7728. }
  7729. // 验证模型是否在可用模型表中
  7730. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7731. $model = 'deepseek-v4-pro';
  7732. }
  7733. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7734. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7735. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7736. if ($model === 'deepseek-chat') {
  7737. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7738. $model = 'deepseek-v4-flash';
  7739. $thinkingMode = 'disabled';
  7740. } elseif ($model === 'deepseek-reasoner') {
  7741. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7742. $model = 'deepseek-v4-flash';
  7743. $thinkingMode = 'enabled';
  7744. }
  7745. $post_data = [
  7746. 'model' => $model,
  7747. 'messages' => $messages,
  7748. // 'max_tokens' => 8192,
  7749. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7750. 'frequency_penalty' => 0,
  7751. 'presence_penalty' => 0,
  7752. 'response_format' => ['type' => 'text'],
  7753. 'thinking' => ['type' => $thinkingMode],
  7754. 'stream' => true // 启用流式输出
  7755. ];
  7756. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7757. // 根据模型类型选择调用方法
  7758. $fullContent = '';
  7759. $fullReasoningContent = '';
  7760. $usage = [];
  7761. try {
  7762. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7763. // DeepSeek 官方模型使用 DeepSeek API
  7764. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7765. } else if (in_array($model, $this->gpt_text_models)) {
  7766. // GPT-5.4 模型使用 TokenRouter API
  7767. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7768. } else {
  7769. // 其他模型使用火山引擎API
  7770. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7771. }
  7772. // 验证返回值类型
  7773. if (!is_iterable($streamGenerator)) {
  7774. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7775. dLog('deepseek')->error('chat流式生成器无效', [
  7776. 'generator_type' => $errorType,
  7777. 'model' => $model,
  7778. 'anime_id' => $anime_id,
  7779. 'episode_number' => $episode_number
  7780. ]);
  7781. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7782. 'type' => $errorType,
  7783. 'model' => $model
  7784. ]);
  7785. yield [
  7786. 'type' => 'error',
  7787. 'episode' => [],
  7788. 'answer' => '',
  7789. 'reasoning' => '',
  7790. 'usage' => [],
  7791. 'error' => '接口返回数据异常,请重新请求'
  7792. ];
  7793. return;
  7794. }
  7795. // 处理流式输出
  7796. foreach ($streamGenerator as $chunk) {
  7797. if (isset($chunk['type'])) {
  7798. if ($chunk['type'] === 'done') {
  7799. // 最终结果
  7800. $fullContent = $chunk['full_content'];
  7801. $fullReasoningContent = $chunk['full_reasoning'];
  7802. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7803. } else {
  7804. // 逐块yield数据
  7805. yield $chunk;
  7806. }
  7807. }
  7808. }
  7809. } catch (\Exception $e) {
  7810. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7811. 'model' => $model,
  7812. 'anime_id' => $anime_id,
  7813. 'episode_number' => $episode_number,
  7814. 'trace' => $e->getTraceAsString()
  7815. ]);
  7816. logDB('deepseek', 'error', 'chat流式处理失败', [
  7817. 'error' => $e->getMessage(),
  7818. 'model' => $model
  7819. ]);
  7820. yield [
  7821. 'type' => 'error',
  7822. 'episode' => [],
  7823. 'answer' => '',
  7824. 'reasoning' => '',
  7825. 'usage' => [],
  7826. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7827. ];
  7828. return;
  7829. }
  7830. dLog('deepseek')->info('完整内容: '.$fullContent);
  7831. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7832. // 处理完整内容并返回最终结果
  7833. $episode_arr = handleEpisodeContentForAce($fullContent);
  7834. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7835. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7836. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7837. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7838. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7839. // }
  7840. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7841. $max_retries = 3;
  7842. $retry_count = 0;
  7843. $validation_failed = false;
  7844. $validation_error_msg = '';
  7845. // 验证生成的内容
  7846. if ($anime_script_id) {
  7847. // 检查是否有acts数据
  7848. if (empty($episode_arr['acts'])) {
  7849. $validation_failed = true;
  7850. $validation_error_msg = '未生成分镜剧本相关的内容';
  7851. } else {
  7852. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7853. $generated_roles = array_column($episode_arr['roles'], 'role');
  7854. // 过滤掉"旁白"角色
  7855. $generated_roles = array_filter($generated_roles, function($role) {
  7856. return $role !== '旁白';
  7857. });
  7858. $expected_roles = array_keys($extra_roles);
  7859. // 找出生成的主体中不在预期列表中的主体
  7860. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7861. if (!empty($invalid_roles)) {
  7862. $validation_failed = true;
  7863. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7864. }
  7865. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7866. if (!$validation_failed) {
  7867. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7868. $expected_scenes = array_keys($extra_scenes);
  7869. // 找出生成的场景中不在预期列表中的场景
  7870. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7871. if (!empty($invalid_scenes)) {
  7872. $validation_failed = true;
  7873. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7874. }
  7875. }
  7876. }
  7877. } else {
  7878. // 如果没有anime_script_id,只检查是否有acts数据
  7879. if (empty($episode_arr['acts'])) {
  7880. $validation_failed = true;
  7881. $validation_error_msg = '未生成分镜剧本相关的内容';
  7882. }
  7883. }
  7884. // 重试逻辑
  7885. while ($validation_failed && $retry_count < $max_retries) {
  7886. $retry_count++;
  7887. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7888. 'reason' => $validation_error_msg,
  7889. 'anime_id' => $anime_id,
  7890. 'episode_number' => $episode_number
  7891. ]);
  7892. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7893. 'reason' => $validation_error_msg,
  7894. 'anime_id' => $anime_id
  7895. ]);
  7896. // 发送流式重试提示
  7897. yield [
  7898. 'type' => 'retry',
  7899. 'retry_count' => $retry_count,
  7900. 'reason' => $validation_error_msg
  7901. ];
  7902. // 构建重试提示词
  7903. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7904. if ($anime_script_id) {
  7905. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7906. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7907. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7908. } else {
  7909. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7910. }
  7911. // 添加重试消息到messages
  7912. $messages[] = [
  7913. 'role' => 'assistant',
  7914. 'content' => $fullContent
  7915. ];
  7916. $messages[] = [
  7917. 'role' => 'user',
  7918. 'content' => $retry_prompt
  7919. ];
  7920. // 更新post_data的messages
  7921. $post_data['messages'] = $messages;
  7922. // 重新调用API
  7923. try {
  7924. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7925. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7926. } else if (in_array($model, $this->gpt_text_models)) {
  7927. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7928. } else {
  7929. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7930. }
  7931. // 处理流式输出
  7932. $fullContent = '';
  7933. $fullReasoningContent = '';
  7934. foreach ($streamGenerator as $chunk) {
  7935. if (isset($chunk['type'])) {
  7936. if ($chunk['type'] === 'done') {
  7937. $fullContent = $chunk['full_content'];
  7938. $fullReasoningContent = $chunk['full_reasoning'];
  7939. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7940. } else {
  7941. yield $chunk;
  7942. }
  7943. }
  7944. }
  7945. // 重新解析内容
  7946. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7947. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7948. $episode_arr = handleEpisodeContentForAce($fullContent);
  7949. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7950. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7951. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7952. // }
  7953. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7954. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7955. // 重新验证
  7956. $validation_failed = false;
  7957. $validation_error_msg = '';
  7958. if ($anime_script_id) {
  7959. if (empty($episode_arr['acts'])) {
  7960. $validation_failed = true;
  7961. $validation_error_msg = '未生成分镜剧本相关的内容';
  7962. } else {
  7963. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7964. $generated_roles = array_column($episode_arr['roles'], 'role');
  7965. // 过滤掉"旁白"角色
  7966. $generated_roles = array_filter($generated_roles, function($role) {
  7967. return $role !== '旁白';
  7968. });
  7969. $expected_roles = array_keys($extra_roles);
  7970. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7971. if (!empty($invalid_roles)) {
  7972. $validation_failed = true;
  7973. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7974. }
  7975. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7976. if (!$validation_failed) {
  7977. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7978. $expected_scenes = array_keys($extra_scenes);
  7979. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7980. if (!empty($invalid_scenes)) {
  7981. $validation_failed = true;
  7982. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7983. }
  7984. }
  7985. }
  7986. } else {
  7987. if (empty($episode_arr['acts'])) {
  7988. $validation_failed = true;
  7989. $validation_error_msg = '未生成分镜剧本相关的内容';
  7990. }
  7991. }
  7992. } catch (\Exception $e) {
  7993. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7994. 'trace' => $e->getTraceAsString()
  7995. ]);
  7996. break;
  7997. }
  7998. }
  7999. // 如果重试后仍然失败
  8000. if ($validation_failed) {
  8001. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8002. 'retry_count' => $retry_count,
  8003. 'last_error' => $validation_error_msg
  8004. ]);
  8005. try {
  8006. $now = date('Y-m-d H:i:s');
  8007. $records = [
  8008. [
  8009. 'uid' => $uid,
  8010. 'anime_id' => $anime_id,
  8011. 'sequence' => $episode_number,
  8012. 'role' => 'user',
  8013. 'content' => $prompt,
  8014. 'created_at' => $now,
  8015. 'updated_at' => $now
  8016. ],
  8017. [
  8018. 'uid' => $uid,
  8019. 'anime_id' => $anime_id,
  8020. 'sequence' => $episode_number,
  8021. 'role' => 'assistant',
  8022. 'content' => $fullContent,
  8023. 'created_at' => $now,
  8024. 'updated_at' => $now
  8025. ]
  8026. ];
  8027. DB::table('mp_anime_records')->insert($records);
  8028. } catch (\Exception $e) {
  8029. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8030. }
  8031. yield [
  8032. 'type' => 'done',
  8033. 'episode' => [],
  8034. 'answer' => $fullContent,
  8035. 'reasoning' => $fullReasoningContent,
  8036. 'usage' => $usage,
  8037. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8038. ];
  8039. return;
  8040. }
  8041. // 验证成功,记录日志
  8042. if ($retry_count > 0) {
  8043. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8044. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8045. }
  8046. // 老逻辑
  8047. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8048. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8049. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8050. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8051. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8052. $existing_props = is_array($existing_props) ? $existing_props : [];
  8053. $now = date('Y-m-d H:i:s');
  8054. try {
  8055. DB::beginTransaction();
  8056. $saveResult = $this->saveEpisodeVersionData(
  8057. $anime_id,
  8058. $episode_number,
  8059. $episode_arr,
  8060. $existing_roles,
  8061. $existing_scenes,
  8062. $existing_props,
  8063. $current_episode,
  8064. $base_episode,
  8065. $is_regenerate_version,
  8066. $content,
  8067. $now,
  8068. $ref_products
  8069. );
  8070. $episode = $saveResult['episode'];
  8071. $episode_id = $saveResult['episode_id'];
  8072. $merged_roles = $saveResult['merged_roles'];
  8073. $merged_scenes = $saveResult['merged_scenes'];
  8074. $merged_props = $saveResult['merged_props'];
  8075. $record_content = $origin_prompt;
  8076. if ($uploaded_content !== '') {
  8077. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8078. }
  8079. $records = [
  8080. [
  8081. 'uid' => $uid,
  8082. 'anime_id' => $anime_id,
  8083. 'role' => 'user',
  8084. 'content' => $record_content,
  8085. 'sequence' => $episode_number,
  8086. 'episode_id' => $episode_id,
  8087. 'created_at' => $now,
  8088. 'updated_at' => $now
  8089. ],
  8090. [
  8091. 'uid' => $uid,
  8092. 'anime_id' => $anime_id,
  8093. 'role' => 'assistant',
  8094. 'content' => $fullContent,
  8095. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8096. 'sequence' => $episode_number,
  8097. 'episode_id' => $episode_id,
  8098. 'created_at' => $now,
  8099. 'updated_at' => $now
  8100. ]
  8101. ];
  8102. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8103. if (!$boolen4) {
  8104. Utils::throwError('20003:对话记录保存失败');
  8105. }
  8106. // 保存模型到anime表
  8107. $update_anime_data = [
  8108. 'model' => $model,
  8109. 'updated_at' => $now
  8110. ];
  8111. if ($uploaded_content) {
  8112. $update_anime_data['content'] = $uploaded_content;
  8113. }
  8114. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8115. }catch (\Exception $e) {
  8116. DB::rollBack();
  8117. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8118. yield [
  8119. 'type' => 'done',
  8120. 'answer' => $fullContent,
  8121. 'reasoning' => $fullReasoningContent,
  8122. 'usage' => $usage,
  8123. 'error' => $e->getMessage(),
  8124. ];
  8125. return;
  8126. }
  8127. DB::commit();
  8128. if ($is_global_generate_pics) {
  8129. // // 批量生成全局角色图片
  8130. // $this->batchSetGlobalRoleImg([
  8131. // 'anime_id' => $anime_id,
  8132. // ], true);
  8133. // // 批量生成全局场景图片
  8134. // $this->batchSetGlobalSceneImg([
  8135. // 'anime_id' => $anime_id,
  8136. // ], true);
  8137. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8138. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8139. }
  8140. $episode['episode_id'] = $episode_id;
  8141. $episode['roles'] = $merged_roles;
  8142. $episode['scenes'] = $merged_scenes;
  8143. $episode['props'] = $merged_props;
  8144. $episode['end_episode_sequence'] = $end_episode_sequence;
  8145. // 获取mp_animes表中的视频参数
  8146. $episode['video_params'] = [
  8147. 'video_model' => getProp($anime, 'video_model'),
  8148. 'video_resolution' => getProp($anime, 'video_resolution'),
  8149. 'ratio' => getProp($anime, 'video_ratio'),
  8150. ];
  8151. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8152. yield [
  8153. 'type' => 'done',
  8154. 'episode' => $episode,
  8155. 'answer' => $fullContent,
  8156. 'reasoning' => $fullReasoningContent,
  8157. 'usage' => $usage
  8158. ];
  8159. }
  8160. /**
  8161. * chatForAce的非流式版本 - 用于定时任务
  8162. * 只获取最终 type=done 的数据,并验证必要字段
  8163. *
  8164. * @param array $data 请求数据
  8165. * @return array 生成结果
  8166. */
  8167. public function chatForAceNonStream($data) {
  8168. $finalResult = null;
  8169. // 调用流式方法,只保存 type=done 的数据
  8170. foreach ($this->chatForAce($data) as $chunk) {
  8171. // 只关注最终结果
  8172. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8173. $finalResult = $chunk;
  8174. break; // 找到 done 就退出循环
  8175. }
  8176. }
  8177. // 验证最终结果
  8178. if (!$finalResult) {
  8179. return ['error' => '生成失败:未获取到最终结果'];
  8180. }
  8181. // 检查是否有错误
  8182. if (isset($finalResult['error']) && $finalResult['error']) {
  8183. return $finalResult;
  8184. }
  8185. // 验证必要字段
  8186. $episode = $finalResult['episode'] ?? [];
  8187. // 验证 roles
  8188. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8189. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8190. }
  8191. // 验证 scenes
  8192. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8193. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8194. }
  8195. // 验证 props(道具可以为空,但必须存在且为数组)
  8196. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8197. $episode['props'] = [];
  8198. }
  8199. // 验证 acts(分镜剧本)
  8200. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8201. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8202. }
  8203. // 更新验证后的 episode 数据
  8204. $finalResult['episode'] = $episode;
  8205. // 记录验证成功日志
  8206. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8207. 'roles_count' => count($episode['roles']),
  8208. 'scenes_count' => count($episode['scenes']),
  8209. 'props_count' => count($episode['props']),
  8210. 'acts_count' => count($episode['acts'])
  8211. ]);
  8212. return $finalResult;
  8213. }
  8214. /**
  8215. * 批量生成多个分集
  8216. *
  8217. * @param array $data 请求数据
  8218. * @return array 任务信息
  8219. */
  8220. public function batchGenerateEpisodes($data) {
  8221. $uid = Site::getUid();
  8222. $cpid = Site::getCpid();
  8223. $anime_id = getProp($data, 'anime_id');
  8224. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8225. if (!$anime_id) {
  8226. Utils::throwError('20003:anime_id参数缺失');
  8227. }
  8228. if ($generate_episode_number < 1) {
  8229. Utils::throwError('20003:生成集数必须大于0');
  8230. }
  8231. // 获取动漫信息
  8232. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8233. if (!$anime) {
  8234. Utils::throwError('20003:该剧集不存在');
  8235. }
  8236. // 检查是否是全能模式
  8237. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8238. Utils::throwError('20003:只有全能模式才支持批量生成');
  8239. }
  8240. // 检查是否是多剧集模式
  8241. if ((int)getProp($anime, 'is_multi') !== 1) {
  8242. Utils::throwError('20003:单剧集不支持批量生成');
  8243. }
  8244. // 获取当前已生成的最大集数
  8245. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8246. ->where('anime_id', $anime_id)
  8247. ->where('is_default', 1)
  8248. ->max('episode_number');
  8249. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8250. // 确定起始集数
  8251. $startEpisodeNumber = $currentMaxEpisode + 1;
  8252. // 计算结束集数
  8253. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8254. // 检查是否超过总集数限制
  8255. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8256. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8257. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8258. }
  8259. $now = date('Y-m-d H:i:s');
  8260. $createdTasks = [];
  8261. $skippedTasks = [];
  8262. // 为每一集创建详情记录
  8263. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8264. // 检查是否已有该集的任务记录
  8265. $existingTask = DB::table('mp_batch_episode_generation_details')
  8266. ->where('anime_id', $anime_id)
  8267. ->where('episode_number', $episodeNumber)
  8268. ->first();
  8269. if ($existingTask) {
  8270. // 如果已存在且未完成,跳过
  8271. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8272. $skippedTasks[] = $episodeNumber;
  8273. continue;
  8274. }
  8275. // 如果是失败状态,可以重新创建(删除旧记录)
  8276. if ($existingTask->status === 'failed') {
  8277. DB::table('mp_batch_episode_generation_details')
  8278. ->where('id', $existingTask->id)
  8279. ->delete();
  8280. }
  8281. // 如果是已完成状态,也跳过
  8282. if ($existingTask->status === 'completed') {
  8283. $skippedTasks[] = $episodeNumber;
  8284. continue;
  8285. }
  8286. }
  8287. // 准备任务数据
  8288. $taskData = [
  8289. 'anime_id' => $anime_id,
  8290. 'uid' => $uid,
  8291. 'cpid' => $cpid,
  8292. 'episode_number' => $episodeNumber,
  8293. 'status' => 'pending',
  8294. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8295. 'retry_count' => 0,
  8296. 'created_at' => $now,
  8297. 'updated_at' => $now
  8298. ];
  8299. // 创建任务记录
  8300. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8301. if ($taskId) {
  8302. $createdTasks[] = $episodeNumber;
  8303. }
  8304. }
  8305. if (empty($createdTasks)) {
  8306. if (!empty($skippedTasks)) {
  8307. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8308. } else {
  8309. Utils::throwError('20003:创建批量生成任务失败');
  8310. }
  8311. }
  8312. return [
  8313. 'anime_id' => $anime_id,
  8314. 'start_episode' => $startEpisodeNumber,
  8315. 'end_episode' => $endEpisodeNumber,
  8316. 'total_episodes' => $generate_episode_number,
  8317. 'created_episodes' => $createdTasks,
  8318. 'skipped_episodes' => $skippedTasks,
  8319. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8320. "已创建: " . implode(',', $createdTasks) .
  8321. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8322. ];
  8323. }
  8324. /**
  8325. * 获取批量生成任务状态
  8326. *
  8327. * @param array $data 请求数据
  8328. * @return array 任务状态信息
  8329. */
  8330. public function getBatchGenerationTaskStatus($data) {
  8331. $anime_id = getProp($data, 'anime_id');
  8332. if (!$anime_id) {
  8333. Utils::throwError('20003:anime_id参数缺失');
  8334. }
  8335. // 获取该anime的所有任务
  8336. $tasks = DB::table('mp_batch_episode_generation_details')
  8337. ->where('anime_id', $anime_id)
  8338. ->orderBy('episode_number')
  8339. ->get()
  8340. ->map(function($item) {
  8341. return [
  8342. 'id' => $item->id,
  8343. 'episode_number' => $item->episode_number,
  8344. 'status' => $item->status,
  8345. 'error_message' => $item->error_message,
  8346. 'retry_count' => $item->retry_count,
  8347. 'created_at' => $item->created_at,
  8348. 'updated_at' => $item->updated_at,
  8349. 'completed_at' => $item->completed_at
  8350. ];
  8351. })
  8352. ->toArray();
  8353. if (empty($tasks)) {
  8354. Utils::throwError('20003:该剧集没有批量生成任务');
  8355. }
  8356. // 统计各状态数量
  8357. $totalCount = count($tasks);
  8358. $pendingCount = 0;
  8359. $processingCount = 0;
  8360. $completedCount = 0;
  8361. $failedCount = 0;
  8362. foreach ($tasks as $task) {
  8363. switch ($task['status']) {
  8364. case 'pending':
  8365. $pendingCount++;
  8366. break;
  8367. case 'processing':
  8368. $processingCount++;
  8369. break;
  8370. case 'completed':
  8371. $completedCount++;
  8372. break;
  8373. case 'failed':
  8374. $failedCount++;
  8375. break;
  8376. }
  8377. }
  8378. // 计算进度百分比
  8379. $progress = 0;
  8380. if ($totalCount > 0) {
  8381. $progress = round(($completedCount / $totalCount) * 100, 2);
  8382. }
  8383. // 判断整体状态
  8384. $overallStatus = 'processing';
  8385. if ($completedCount === $totalCount) {
  8386. $overallStatus = 'completed';
  8387. } elseif ($pendingCount === $totalCount) {
  8388. $overallStatus = 'pending';
  8389. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8390. $overallStatus = 'failed';
  8391. }
  8392. return [
  8393. 'anime_id' => $anime_id,
  8394. 'total_episodes' => $totalCount,
  8395. 'pending_count' => $pendingCount,
  8396. 'processing_count' => $processingCount,
  8397. 'completed_count' => $completedCount,
  8398. 'failed_count' => $failedCount,
  8399. 'progress' => $progress,
  8400. 'overall_status' => $overallStatus,
  8401. 'tasks' => $tasks
  8402. ];
  8403. }
  8404. /**
  8405. * 智能匹配并替换主体和场景名称
  8406. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8407. *
  8408. * @param array $episode_arr 解析后的剧集数据
  8409. * @param array $extra_roles 强制主体设定(key为主体名称)
  8410. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8411. * @return array 替换后的剧集数据
  8412. */
  8413. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8414. $replaced_count = 0;
  8415. // 1. 处理主体列表
  8416. if (!empty($episode_arr['roles'])) {
  8417. foreach ($episode_arr['roles'] as &$role) {
  8418. $generated_role_name = $role['role'] ?? '';
  8419. // 跳过旁白
  8420. if ($generated_role_name === '旁白') {
  8421. continue;
  8422. }
  8423. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8424. if (!isset($extra_roles[$generated_role_name])) {
  8425. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8426. if ($matched_role) {
  8427. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8428. $role['role'] = $matched_role;
  8429. $replaced_count++;
  8430. }
  8431. }
  8432. }
  8433. }
  8434. // 2. 处理场景列表
  8435. if (!empty($episode_arr['scenes'])) {
  8436. foreach ($episode_arr['scenes'] as &$scene) {
  8437. $generated_scene_name = $scene['scene'] ?? '';
  8438. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8439. if (!isset($extra_scenes[$generated_scene_name])) {
  8440. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8441. if ($matched_scene) {
  8442. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8443. $scene['scene'] = $matched_scene;
  8444. $replaced_count++;
  8445. }
  8446. }
  8447. }
  8448. }
  8449. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8450. if (!empty($episode_arr['acts'])) {
  8451. foreach ($episode_arr['acts'] as &$act) {
  8452. if (!empty($act['segments'])) {
  8453. foreach ($act['segments'] as &$segment) {
  8454. if (!empty($segment['segment_content'])) {
  8455. $original_content = $segment['segment_content'];
  8456. $replaced_content = $original_content;
  8457. // 替换场景名 - 在文本中查找并替换
  8458. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8459. // 尝试找到可能的短名称
  8460. $potential_short_names = [];
  8461. // 提取场景名的主要部分(冒号之前)
  8462. if (mb_strpos($full_scene_name, ':') !== false) {
  8463. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8464. $potential_short_names[] = $short_name;
  8465. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8466. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8467. $potential_short_names[] = $short_name;
  8468. }
  8469. // 替换场景字段中的短名称
  8470. foreach ($potential_short_names as $short_name) {
  8471. if ($short_name !== $full_scene_name) {
  8472. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8473. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8474. if ($new_content !== $replaced_content) {
  8475. $replaced_content = $new_content;
  8476. $replaced_count++;
  8477. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8478. }
  8479. }
  8480. }
  8481. }
  8482. // 替换配音角色名(跳过旁白)
  8483. foreach (array_keys($extra_roles) as $full_role_name) {
  8484. if ($full_role_name === '旁白') {
  8485. continue;
  8486. }
  8487. // 尝试找到可能的短名称
  8488. $potential_short_names = [];
  8489. // 提取角色名的主要部分(短横线之前)
  8490. if (mb_strpos($full_role_name, '-') !== false) {
  8491. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8492. $potential_short_names[] = $short_name;
  8493. }
  8494. // 替换配音台词中的短名称
  8495. foreach ($potential_short_names as $short_name) {
  8496. if ($short_name !== $full_role_name) {
  8497. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8498. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8499. if ($new_content !== $replaced_content) {
  8500. $replaced_content = $new_content;
  8501. $replaced_count++;
  8502. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8503. }
  8504. }
  8505. }
  8506. }
  8507. // 如果有替换,更新segment_content
  8508. if ($replaced_content !== $original_content) {
  8509. $segment['segment_content'] = $replaced_content;
  8510. }
  8511. }
  8512. }
  8513. }
  8514. }
  8515. }
  8516. if ($replaced_count > 0) {
  8517. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8518. 'replaced_count' => $replaced_count
  8519. ]);
  8520. }
  8521. return $episode_arr;
  8522. }
  8523. /**
  8524. * 查找匹配的名称
  8525. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8526. *
  8527. * @param string $generated_name 生成的名称
  8528. * @param array $expected_names 预期的名称列表
  8529. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8530. */
  8531. private function findMatchingName($generated_name, $expected_names) {
  8532. if (empty($generated_name)) {
  8533. return null;
  8534. }
  8535. // 尝试精确匹配
  8536. if (in_array($generated_name, $expected_names)) {
  8537. return $generated_name;
  8538. }
  8539. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8540. foreach ($expected_names as $expected_name) {
  8541. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8542. if (mb_strpos($expected_name, $generated_name) === 0) {
  8543. return $expected_name;
  8544. }
  8545. }
  8546. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8547. // 这样可以处理一些变体,但优先级较低
  8548. foreach ($expected_names as $expected_name) {
  8549. if (mb_strpos($expected_name, $generated_name) !== false) {
  8550. return $expected_name;
  8551. }
  8552. }
  8553. return null;
  8554. }
  8555. /**
  8556. * 重新生成分段剧本
  8557. * @param array $data 包含以下字段:
  8558. * - prompt: string|null 用户修改要求(可选)
  8559. * - template_id: int|null 提示词模板ID(可选)
  8560. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8561. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8562. * @return array 返回生成结果
  8563. */
  8564. public function regenerateSegmentScript($data) {
  8565. $uid = Site::getUid();
  8566. $prompt = trim((string)getProp($data, 'prompt', ''));
  8567. $template_id = getProp($data, 'template_id', 0);
  8568. $act_id = getProp($data, 'act_id', 0);
  8569. $episode_id = getProp($data, 'episode_id', 0);
  8570. // 验证:prompt和template_id至少提供一个
  8571. if (empty($prompt) && empty($template_id)) {
  8572. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8573. }
  8574. // 验证:act_id和episode_id二选一
  8575. if (empty($act_id) && empty($episode_id)) {
  8576. Utils::throwError('20003:请提供片段ID或剧集ID');
  8577. }
  8578. if (!empty($act_id) && !empty($episode_id)) {
  8579. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8580. }
  8581. // 如果提供了template_id,获取模板提示词
  8582. $template_prompt = '';
  8583. if ($template_id > 0) {
  8584. $template = DB::table('mp_prompt_templates')
  8585. ->where('id', $template_id)
  8586. ->where('is_deleted', 0)
  8587. ->first();
  8588. if (!$template) {
  8589. Utils::throwError('20003:提示词模板不存在或已删除');
  8590. }
  8591. $template_prompt = $template->template_prompt ?? '';
  8592. }
  8593. // 合并用户提示词和模板提示词
  8594. $final_prompt = '';
  8595. if (!empty($template_prompt)) {
  8596. $final_prompt = $template_prompt;
  8597. if (!empty($prompt)) {
  8598. $final_prompt .= "\n\n补充要求:" . $prompt;
  8599. }
  8600. } else {
  8601. $final_prompt = $prompt;
  8602. }
  8603. // 获取需要重新生成的内容参考
  8604. $reference_content = '';
  8605. $target_episode_id = 0;
  8606. $target_anime_id = 0;
  8607. $target_episode_number = 0;
  8608. if ($act_id > 0) {
  8609. // 单个片段模式:获取该片段的内容
  8610. $segment = DB::table('mp_episode_segments')
  8611. ->where('id', $act_id)
  8612. ->first();
  8613. if (!$segment) {
  8614. Utils::throwError('20003:片段不存在');
  8615. }
  8616. $target_episode_id = $segment->episode_id;
  8617. $target_anime_id = $segment->anime_id;
  8618. $target_episode_number = $segment->episode_number;
  8619. $reference_content = $segment->act_content ?? '';
  8620. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8621. } else {
  8622. // 整个剧集模式:获取所有片段的内容
  8623. $segments = DB::table('mp_episode_segments')
  8624. ->where('episode_id', $episode_id)
  8625. ->orderBy('act_number')
  8626. ->get();
  8627. if ($segments->isEmpty()) {
  8628. Utils::throwError('20003:该剧集没有片段数据');
  8629. }
  8630. $target_episode_id = $episode_id;
  8631. $target_anime_id = $segments[0]->anime_id;
  8632. $target_episode_number = $segments[0]->episode_number;
  8633. // 拼接所有片段内容,保留格式用于AI理解
  8634. $act_contents = [];
  8635. foreach ($segments as $seg) {
  8636. $act_number = $seg->act_number;
  8637. $act_content = $seg->act_content ?? '';
  8638. if (!empty($act_content)) {
  8639. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8640. }
  8641. }
  8642. $reference_content = implode("\n\n", $act_contents);
  8643. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8644. if ($episode_content) {
  8645. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8646. }else {
  8647. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8648. }
  8649. }
  8650. if (empty($reference_content)) {
  8651. Utils::throwError('20003:没有可参考的片段内容');
  8652. }
  8653. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8654. $episode = DB::table('mp_anime_episodes')
  8655. ->where('id', $target_episode_id)
  8656. ->first();
  8657. if (!$episode) {
  8658. Utils::throwError('20003:剧集不存在');
  8659. }
  8660. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8661. $anime_script_id = getProp($anime, 'script_id');
  8662. $intro = $episode->intro ?? '';
  8663. $art_style = $episode->art_style ?? '';
  8664. $roles = json_decode($episode->roles ?? '[]', true);
  8665. $scenes = json_decode($episode->scenes ?? '[]', true);
  8666. $props = json_decode($episode->props ?? '[]', true);
  8667. // 构建提示词中的主体列表和场景列表参考
  8668. $roles_ref = '';
  8669. if (!empty($roles) && is_array($roles)) {
  8670. $roles_list = [];
  8671. foreach ($roles as $role) {
  8672. $role_name = getProp($role, 'role', '');
  8673. $role_desc = getProp($role, 'description', '');
  8674. $pic_prompt = getProp($role, 'pic_prompt', '');
  8675. $voice_prompt = getProp($role, 'voice_prompt', '');
  8676. if (!empty($role_name)) {
  8677. $role_line = $role_name;
  8678. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8679. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8680. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8681. $roles_list[] = $role_line;
  8682. }
  8683. }
  8684. if (!empty($roles_list)) {
  8685. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8686. }
  8687. }
  8688. $scenes_ref = '';
  8689. if (!empty($scenes) && is_array($scenes)) {
  8690. $scenes_list = [];
  8691. foreach ($scenes as $scene) {
  8692. $scene_name = getProp($scene, 'scene', '');
  8693. $scene_desc = getProp($scene, 'description', '');
  8694. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8695. if (!empty($scene_name)) {
  8696. $scene_line = $scene_name;
  8697. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8698. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8699. $scenes_list[] = $scene_line;
  8700. }
  8701. }
  8702. if (!empty($scenes_list)) {
  8703. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8704. }
  8705. }
  8706. $props_ref = '';
  8707. if (!empty($props) && is_array($props)) {
  8708. $props_list = [];
  8709. foreach ($props as $prop) {
  8710. $prop_name = getProp($prop, 'prop', '');
  8711. $prop_desc = getProp($prop, 'description', '');
  8712. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8713. if (!empty($prop_name)) {
  8714. $prop_line = $prop_name;
  8715. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8716. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8717. $props_list[] = $prop_line;
  8718. }
  8719. }
  8720. if (!empty($props_list)) {
  8721. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8722. }
  8723. }
  8724. // 构建美术风格参考
  8725. $art_style_ref = '';
  8726. if (!empty($art_style)) {
  8727. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8728. }
  8729. // 构建内容简介参考
  8730. $intro_ref = '';
  8731. if (!empty($intro)) {
  8732. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8733. }
  8734. // 构建完整的AI提示词
  8735. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8736. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8737. $user_prompt .= $intro_ref;
  8738. $user_prompt .= $art_style_ref;
  8739. $user_prompt .= $reference_content;
  8740. // $user_prompt .= $roles_ref;
  8741. // $user_prompt .= $scenes_ref;
  8742. $system_prompt = "\n\n【强制要求】\n";
  8743. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8744. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8745. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8746. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8747. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8748. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8749. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8750. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8751. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8752. ###分段剧本
  8753. 片段数量:8
  8754. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8755. ##片段1
  8756. 时长:12s
  8757. 分镜1
  8758. 出场角色:刀疤脸
  8759. 场景:边境小镇街道
  8760. 出场道具:酒杯-高脚杯
  8761. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8762. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8763. 配音台词:
  8764. 背景音效:
  8765. 分镜2
  8766. 出场角色:刀疤脸
  8767. 场景:悦来酒馆
  8768. 出场道具:酒杯-高脚杯
  8769. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8770. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8771. 配音台词:
  8772. 背景音效:
  8773. 分镜3
  8774. 出场角色:刀疤脸
  8775. 场景:悦来酒馆
  8776. 出场道具:酒杯-高脚杯
  8777. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8778. 运镜:从中景推向令牌特写。
  8779. 配音台词:
  8780. 背景音效:
  8781. 分镜4
  8782. 出场角色:刀疤脸
  8783. 场景:悦来酒馆
  8784. 出场道具:酒杯-高脚杯
  8785. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8786. 运镜:极速推向酒水溅起的瞬间。
  8787. 配音台词:
  8788. 背景音效:
  8789. 分镜5
  8790. 出场角色:刀疤脸
  8791. 场景:悦来酒馆
  8792. 出场道具:酒杯-高脚杯
  8793. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8794. 运镜:固定机位,利用倾斜构图制造压迫感。
  8795. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8796. 背景音效:";
  8797. // 获取模型配置
  8798. $model = getProp($data, 'model');
  8799. if (!$model) {
  8800. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8801. }
  8802. // 验证模型是否在可用模型表中
  8803. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8804. $model = 'deepseek-v4-pro';
  8805. }
  8806. // 模型兼容性处理
  8807. $thinkingMode = 'disabled';
  8808. $reasoningEffort = 'high';
  8809. if ($model === 'deepseek-chat') {
  8810. $model = 'deepseek-v4-flash';
  8811. $thinkingMode = 'disabled';
  8812. } elseif ($model === 'deepseek-reasoner') {
  8813. $model = 'deepseek-v4-flash';
  8814. $thinkingMode = 'enabled';
  8815. }
  8816. // 构建消息
  8817. $messages = [
  8818. [
  8819. 'role' => 'system',
  8820. 'content' => $system_prompt
  8821. ],
  8822. [
  8823. 'role' => 'user',
  8824. 'content' => $user_prompt
  8825. ]
  8826. ];
  8827. // dd($messages);
  8828. // 构建请求参数
  8829. $post_data = [
  8830. 'model' => $model,
  8831. 'messages' => $messages,
  8832. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8833. 'frequency_penalty' => 0,
  8834. 'presence_penalty' => 0,
  8835. 'response_format' => ['type' => 'text'],
  8836. 'thinking' => ['type' => $thinkingMode],
  8837. 'stream' => false // 非流式输出
  8838. ];
  8839. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8840. // 调用AI生成新的分段剧本
  8841. try {
  8842. $fullContent = '';
  8843. $usage = [];
  8844. // 根据模型类型选择调用方法
  8845. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8846. // DeepSeek 官方模型使用 DeepSeek API
  8847. $chatResult = $this->chatOnly($post_data);
  8848. } else if (in_array($model, $this->gpt_text_models)) {
  8849. // GPT 模型使用 TokenRouter API
  8850. $chatResult = $this->gpt54ChatOnly($post_data);
  8851. } else {
  8852. // 其他模型使用火山引擎API
  8853. $chatResult = $this->volcEngineChatCompletion($post_data);
  8854. }
  8855. if (is_array($chatResult)) {
  8856. $fullContent = $chatResult['fullContent'] ?? '';
  8857. $usage = $chatResult['usage'] ?? [];
  8858. }
  8859. $generated_content = $fullContent;
  8860. if (empty($generated_content)) {
  8861. Utils::throwError('20003:AI生成内容为空,请重试');
  8862. }
  8863. // 解析生成的内容 - 按片段分割
  8864. $parsed_segments = [];
  8865. // 先在开头添加换行符,确保第1片段也能被正确分割
  8866. $normalizedText = "\n" . $generated_content;
  8867. $parts = preg_split('/\n\s*##/', $normalizedText);
  8868. foreach ($parts as $part) {
  8869. $part = trim($part);
  8870. if (empty($part)) continue;
  8871. // 匹配"片段X"格式
  8872. if (!preg_match('/^片段\d+/', $part)) {
  8873. continue;
  8874. }
  8875. // 分离标题和内容
  8876. $lines = explode("\n", $part, 2);
  8877. $actTitle = trim($lines[0]);
  8878. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8879. // 解析标题,提取序号
  8880. $actNumber = 0;
  8881. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8882. $actNumber = intval($segmentTitleMatch[1]);
  8883. } else {
  8884. $actNumber = count($parsed_segments) + 1;
  8885. }
  8886. // 提取时长(仅保留数字)
  8887. $actDuration = 0;
  8888. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8889. $actDurationStr = trim($actDurationMatch[1]);
  8890. // 提取数字部分(支持整数和小数)
  8891. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8892. $actDuration = (float)$numMatch[1];
  8893. }
  8894. }
  8895. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8896. // 只保留分镜内容,并确保分镜标记使用【】格式
  8897. $cleaned_content = '';
  8898. $content_lines = explode("\n", $actContent);
  8899. $is_capturing = false; // 标记是否开始捕获分镜内容
  8900. $count = 0;
  8901. foreach ($content_lines as $line) {
  8902. $trimmed_line = trim($line);
  8903. // 跳过时长和旁白音色行
  8904. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8905. continue;
  8906. }
  8907. // 检测是否是分镜开始
  8908. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8909. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8910. $count++;
  8911. $is_capturing = true;
  8912. // 如果没有【】,则添加
  8913. if (!preg_match('/^【/u', $trimmed_line)) {
  8914. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8915. }
  8916. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8917. }
  8918. // 如果已经开始捕获,则添加该行
  8919. if ($is_capturing && !empty($trimmed_line)) {
  8920. $cleaned_content .= $trimmed_line."\n";
  8921. }
  8922. }
  8923. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8924. $parsed_segments[] = [
  8925. 'act_number' => $actNumber,
  8926. 'act_title' => $actTitle,
  8927. 'act_duration' => $actDuration,
  8928. 'act_content' => $cleaned_content,
  8929. ];
  8930. }
  8931. if (empty($parsed_segments)) {
  8932. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8933. }
  8934. // 收集所有资产名称(角色、场景、道具)
  8935. $product_names = [];
  8936. // 收集角色名称
  8937. if (!empty($roles) && is_array($roles)) {
  8938. foreach ($roles as $role) {
  8939. $role_name = getProp($role, 'role', '');
  8940. if (!empty($role_name)) {
  8941. $product_names[] = $role_name;
  8942. }
  8943. }
  8944. }
  8945. // 收集场景名称
  8946. if (!empty($scenes) && is_array($scenes)) {
  8947. foreach ($scenes as $scene) {
  8948. $scene_name = getProp($scene, 'scene', '');
  8949. if (!empty($scene_name)) {
  8950. $product_names[] = $scene_name;
  8951. }
  8952. }
  8953. }
  8954. // 收集道具名称
  8955. if (!empty($props) && is_array($props)) {
  8956. foreach ($props as $prop) {
  8957. $prop_name = getProp($prop, 'prop', '');
  8958. if (!empty($prop_name)) {
  8959. $product_names[] = $prop_name;
  8960. }
  8961. }
  8962. }
  8963. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8964. $product_names = array_unique($product_names);
  8965. usort($product_names, function($a, $b) {
  8966. return mb_strlen($b) - mb_strlen($a);
  8967. });
  8968. // 处理每个片段的 act_show_content
  8969. foreach ($parsed_segments as &$segment) {
  8970. $act_content = getProp($segment, 'act_content', '');
  8971. if (empty($act_content)) {
  8972. $segment['act_show_content'] = '';
  8973. continue;
  8974. }
  8975. $processed_content = $act_content;
  8976. // 统一替换所有资产名称为 {资产名} 格式
  8977. // 使用占位符避免嵌套替换问题
  8978. $placeholder_map = [];
  8979. $placeholder_index = 0;
  8980. foreach ($product_names as $product_name) {
  8981. // 转义特殊字符
  8982. $escaped_product = preg_quote($product_name, '/');
  8983. // 检查是否匹配且未被 {} 包裹
  8984. $processed_content = preg_replace_callback(
  8985. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8986. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8987. // 使用唯一占位符
  8988. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8989. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8990. $placeholder_index++;
  8991. return $placeholder;
  8992. },
  8993. $processed_content
  8994. );
  8995. }
  8996. // 将所有占位符替换回实际内容
  8997. foreach ($placeholder_map as $placeholder => $replacement) {
  8998. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8999. }
  9000. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9001. $shot_counter = 0;
  9002. $processed_content = preg_replace_callback(
  9003. '/【(?:镜头|分镜)(\d+)】/u',
  9004. function($matches) use (&$shot_counter) {
  9005. $shot_counter++;
  9006. return '【镜头' . $shot_counter . '】';
  9007. },
  9008. $processed_content
  9009. );
  9010. $segment['act_show_content'] = $processed_content;
  9011. }
  9012. unset($segment); // 解除引用
  9013. // 保存到数据库
  9014. $now = date('Y-m-d H:i:s');
  9015. $saved_acts = []; // 用于记录保存后的片段信息
  9016. if ($act_id > 0) {
  9017. // 单个片段模式:更新单条记录
  9018. if (count($parsed_segments) > 0) {
  9019. $new_segment = $parsed_segments[0];
  9020. $update_data = [
  9021. 'act_content' => getProp($new_segment, 'act_content', ''),
  9022. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9023. 'act_title' => getProp($new_segment, 'act_title', ''),
  9024. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9025. 'updated_at' => $now,
  9026. ];
  9027. DB::table('mp_episode_segments')
  9028. ->where('id', $act_id)
  9029. ->update($update_data);
  9030. // 获取更新后的记录
  9031. $updated_act = DB::table('mp_episode_segments')
  9032. ->where('id', $act_id)
  9033. ->first();
  9034. if ($updated_act) {
  9035. $saved_acts[] = [
  9036. 'act_id' => $updated_act->id,
  9037. 'act_number' => $updated_act->act_number,
  9038. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9039. 'act_content' => $updated_act->act_content,
  9040. 'act_show_content' => $updated_act->act_show_content,
  9041. 'video_url' => $updated_act->video_url ?? '',
  9042. 'video_duration' => $updated_act->video_duration ?? 0,
  9043. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9044. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9045. ];
  9046. }
  9047. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9048. }
  9049. } else {
  9050. // 整个剧集模式:删除原有记录并批量保存新记录
  9051. DB::beginTransaction();
  9052. try {
  9053. // 删除原有的所有片段记录
  9054. DB::table('mp_episode_segments')
  9055. ->where('episode_id', $target_episode_id)
  9056. ->delete();
  9057. // 批量插入新的片段记录
  9058. $segments_to_insert = [];
  9059. foreach ($parsed_segments as $index => $segment) {
  9060. $act_number = $index + 1;
  9061. $segments_to_insert[] = [
  9062. 'anime_id' => $target_anime_id,
  9063. 'episode_id' => $target_episode_id,
  9064. 'episode_number' => $target_episode_number,
  9065. 'act_number' => $act_number,
  9066. 'act_title' => getProp($segment, 'act_title', ''),
  9067. 'act_duration' => getProp($segment, 'act_duration', 0),
  9068. 'act_content' => getProp($segment, 'act_content', ''),
  9069. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9070. 'created_at' => $now,
  9071. 'updated_at' => $now,
  9072. ];
  9073. }
  9074. if (!empty($segments_to_insert)) {
  9075. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9076. }
  9077. DB::commit();
  9078. // 查询保存后的所有片段记录
  9079. $saved_segments = DB::table('mp_episode_segments')
  9080. ->where('episode_id', $target_episode_id)
  9081. ->orderBy('act_number')
  9082. ->get();
  9083. foreach ($saved_segments as $saved_segment) {
  9084. $saved_acts[] = [
  9085. 'act_id' => $saved_segment->id,
  9086. 'act_number' => $saved_segment->act_number,
  9087. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9088. 'act_content' => $saved_segment->act_content,
  9089. 'act_show_content' => $saved_segment->act_show_content,
  9090. 'video_url' => $saved_segment->video_url ?? '',
  9091. 'video_duration' => $saved_segment->video_duration ?? 0,
  9092. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9093. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9094. ];
  9095. }
  9096. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9097. 'episode_id' => $target_episode_id,
  9098. 'segments_count' => count($segments_to_insert)
  9099. ]);
  9100. } catch (\Exception $e) {
  9101. DB::rollBack();
  9102. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9103. Utils::throwError('20003:保存失败,请重试');
  9104. }
  9105. }
  9106. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9107. return [
  9108. 'anime_id' => $target_anime_id,
  9109. 'episode_id' => $target_episode_id,
  9110. 'title' => getProp($episode, 'title', ''),
  9111. 'episode_number' => $target_episode_number,
  9112. 'is_generated' => getProp($episode, 'is_generated', 0),
  9113. 'acts' => $saved_acts,
  9114. ];
  9115. } catch (\Exception $e) {
  9116. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9117. throw $e;
  9118. }
  9119. }
  9120. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9121. {
  9122. $episode_arr = [
  9123. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9124. 'intro' => getProp($script_arr, 'intro'),
  9125. 'art_style' => getProp($script_arr, 'art_style'),
  9126. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9127. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9128. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9129. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9130. ];
  9131. if (empty($episode_arr['acts'])) {
  9132. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9133. if (!empty($fallback_episode_arr['acts'])) {
  9134. $episode_arr = array_merge($fallback_episode_arr, [
  9135. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9136. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9137. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9138. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9139. ]);
  9140. }
  9141. }
  9142. // if (!getProp($episode_arr, 'episode_title')) {
  9143. // $episode_title = '';
  9144. // $episodes = getProp($script_arr, 'episodes', []);
  9145. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9146. // $episode_title = '第1集:' . $episodes[0]['title'];
  9147. // }
  9148. // if (!$episode_title) {
  9149. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9150. // }
  9151. // $episode_arr['episode_title'] = $episode_title;
  9152. // }
  9153. return $episode_arr;
  9154. }
  9155. private function saveEpisodeVersionData(
  9156. int $anime_id,
  9157. int $episode_number,
  9158. array $episode_arr,
  9159. array $existing_roles,
  9160. array $existing_scenes,
  9161. array $existing_props,
  9162. $current_episode,
  9163. $base_episode,
  9164. bool $is_regenerate_version,
  9165. string $content,
  9166. string $now,
  9167. array $ref_products = []
  9168. ): array {
  9169. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9170. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9171. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9172. // 过滤掉关键字段为空的条目
  9173. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9174. return !empty($item['role'] ?? null);
  9175. }));
  9176. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9177. return !empty($item['scene'] ?? null);
  9178. }));
  9179. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9180. return !empty($item['prop'] ?? null);
  9181. }));
  9182. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9183. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9184. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9185. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9186. $ace_mode = getProp($anime, 'ace_mode');
  9187. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9188. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9189. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9190. $global_roles = is_array($global_roles) ? $global_roles : [];
  9191. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9192. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9193. $art_style_type = getProp($anime, 'art_style_type');
  9194. // 检查并创建 roles 的图片生成任务
  9195. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9196. // 检查并创建 scenes 的图片生成任务
  9197. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9198. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9199. if ($arr && is_array($arr)) {
  9200. $merged_roles = $arr['roles'];
  9201. $merged_scenes = $arr['scenes'];
  9202. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9203. }
  9204. // 确保数据是数组类型
  9205. if (!is_array($merged_roles)) {
  9206. dLog('deepseek')->error('merged_roles不是数组类型', [
  9207. 'type' => gettype($merged_roles),
  9208. 'value' => $merged_roles
  9209. ]);
  9210. $merged_roles = [];
  9211. }
  9212. if (!is_array($merged_scenes)) {
  9213. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9214. 'type' => gettype($merged_scenes),
  9215. 'value' => $merged_scenes
  9216. ]);
  9217. $merged_scenes = [];
  9218. }
  9219. if (!is_array($merged_props)) {
  9220. dLog('deepseek')->error('merged_props不是数组类型', [
  9221. 'type' => gettype($merged_props),
  9222. 'value' => $merged_props
  9223. ]);
  9224. $merged_props = [];
  9225. }
  9226. // 同步新出现的主体和场景到全局
  9227. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9228. $role_arr = [];
  9229. foreach ($merged_roles as $item) {
  9230. $role_arr[$item['role']] = $item;
  9231. }
  9232. $version_count = DB::table('mp_anime_episodes')
  9233. ->where('anime_id', $anime_id)
  9234. ->where('episode_number', $episode_number)
  9235. ->count('id');
  9236. $episode = [
  9237. 'anime_id' => $anime_id,
  9238. 'episode_number' => $episode_number,
  9239. 'title' => getProp($episode_arr, 'episode_title'),
  9240. 'content' => $content,
  9241. 'intro' => getProp($episode_arr, 'intro'),
  9242. 'art_style' => getProp($episode_arr, 'art_style'),
  9243. 'roles' => json_encode($merged_roles, 256),
  9244. 'scenes' => json_encode($merged_scenes, 256),
  9245. 'props' => json_encode($merged_props, 256),
  9246. 'generate_status' => '待执行',
  9247. 'generate_at' => $now,
  9248. 'is_default' => 1,
  9249. 'updated_at' => $now,
  9250. ];
  9251. $del_flag = false;
  9252. if ($is_regenerate_version) {
  9253. DB::table('mp_anime_episodes')
  9254. ->where('anime_id', $anime_id)
  9255. ->where('episode_number', $episode_number)
  9256. ->update(['is_default' => 0, 'updated_at' => $now]);
  9257. $episode['sequence'] = $version_count + 1;
  9258. $episode['created_at'] = $now;
  9259. $episode['cpid'] = Site::getCpid();
  9260. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9261. if (!$episode_id) {
  9262. Utils::throwError('20003:创建剧集版本失败');
  9263. }
  9264. } else {
  9265. $target_episode = $current_episode ?: $base_episode;
  9266. if ($target_episode) {
  9267. $episode_id = getProp($target_episode, 'id');
  9268. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9269. DB::table('mp_anime_episodes')
  9270. ->where('anime_id', $anime_id)
  9271. ->where('episode_number', $episode_number)
  9272. ->where('id', '<>', $episode_id)
  9273. ->update(['is_default' => 0, 'updated_at' => $now]);
  9274. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9275. if ($boolen === false) {
  9276. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9277. Utils::throwError('20003:分集内容保存失败');
  9278. }
  9279. $del_flag = true;
  9280. } else {
  9281. DB::table('mp_anime_episodes')
  9282. ->where('anime_id', $anime_id)
  9283. ->where('episode_number', $episode_number)
  9284. ->update(['is_default' => 0, 'updated_at' => $now]);
  9285. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9286. $episode['created_at'] = $now;
  9287. $episode['cpid'] = Site::getCpid();
  9288. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9289. if (!$episode_id) {
  9290. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9291. Utils::throwError('20003:分集内容保存失败');
  9292. }
  9293. }
  9294. }
  9295. $segments = [];
  9296. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9297. // 如果是第2集及以后,获取上一集的主体音色数据
  9298. $previous_roles_voice = [];
  9299. if ($episode_number >= 2) {
  9300. $previous_episode = DB::table('mp_anime_episodes')
  9301. ->where('anime_id', $anime_id)
  9302. ->where('episode_number', $episode_number - 1)
  9303. ->where('is_default', 1)
  9304. ->first();
  9305. if ($previous_episode) {
  9306. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9307. if (is_array($previous_roles)) {
  9308. foreach ($previous_roles as $prev_role) {
  9309. $role_name = getProp($prev_role, 'role');
  9310. if ($role_name) {
  9311. $previous_roles_voice[$role_name] = [
  9312. 'voice_name' => getProp($prev_role, 'voice_name'),
  9313. 'voice_type' => getProp($prev_role, 'voice_type'),
  9314. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9315. ];
  9316. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9317. if ($voice_prompt) {
  9318. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9319. }
  9320. }
  9321. }
  9322. }
  9323. }
  9324. }
  9325. // 将继承的音色数据同步到当前集的主体列表
  9326. if (!empty($previous_roles_voice)) {
  9327. foreach ($merged_roles as &$role) {
  9328. $role_name = getProp($role, 'role');
  9329. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9330. // 强制继承上一集的音色数据
  9331. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9332. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9333. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9334. // 如果上一集有 voice_prompt 则继承,否则跳过
  9335. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9336. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9337. }
  9338. }
  9339. }
  9340. unset($role); // 解除引用
  9341. // 更新 role_arr 以便后续使用
  9342. $role_arr = [];
  9343. foreach ($merged_roles as $item) {
  9344. $role_arr[$item['role']] = $item;
  9345. }
  9346. }
  9347. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9348. $emotion_list = array_flip($emotion_list);
  9349. foreach ($acts as $act) {
  9350. $act_segments = getProp($act, 'segments', []);
  9351. if (!is_array($act_segments)) {
  9352. continue;
  9353. }
  9354. if ((int)$ace_mode === 1) {
  9355. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9356. $merged_parts = [];
  9357. foreach ($act_segments as $seg) {
  9358. $seg_num = getProp($seg, 'segment_number');
  9359. $seg_content = getProp($seg, 'segment_content');
  9360. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9361. }
  9362. $act_content = implode("\n", $merged_parts);
  9363. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9364. $segments[] = [
  9365. 'anime_id' => $anime_id,
  9366. 'episode_id' => $episode_id,
  9367. 'episode_number' => $episode_number,
  9368. 'act_number' => getProp($act, 'act_number'),
  9369. 'act_title' => getProp($act, 'act_title'),
  9370. 'act_duration' => getProp($act, 'act_duration'),
  9371. 'act_content' => $act_content,
  9372. 'created_at' => $now,
  9373. 'updated_at' => $now
  9374. ];
  9375. } else {
  9376. foreach ($act_segments as $segment) {
  9377. $voice_actor = getProp($segment, 'voice_actor');
  9378. // 优先从上一集继承音色数据
  9379. $timbre_info = [];
  9380. if (isset($previous_roles_voice[$voice_actor])) {
  9381. // 从上一集继承音色数据
  9382. $timbre_info = $previous_roles_voice[$voice_actor];
  9383. } elseif (isset($role_arr[$voice_actor])) {
  9384. // 使用当前集的主体音色数据
  9385. $timbre_info = $role_arr[$voice_actor];
  9386. }
  9387. $voice_type = getProp($timbre_info, 'voice_type');
  9388. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9389. if ($timbre_emotion) {
  9390. $timbre_emotion = explode(',', $timbre_emotion);
  9391. } else {
  9392. $timbre_emotion = [];
  9393. }
  9394. $emotion = getProp($segment, 'emotion', '中性');
  9395. if (!in_array($emotion, $timbre_emotion)) {
  9396. $emotion = '中性';
  9397. }
  9398. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9399. $segments[] = [
  9400. 'anime_id' => $anime_id,
  9401. 'episode_id' => $episode_id,
  9402. 'episode_number' => $episode_number,
  9403. 'act_number' => getProp($act, 'act_number'),
  9404. 'act_title' => getProp($act, 'act_title'),
  9405. 'act_duration' => getProp($act, 'act_duration'),
  9406. 'segment_id' => getProp($segment, 'segment_id'),
  9407. 'segment_number' => getProp($segment, 'segment_number'),
  9408. 'segment_content' => getProp($segment, 'segment_content'),
  9409. 'description' => getProp($segment, 'description'),
  9410. 'composition' => getProp($segment, 'composition'),
  9411. 'camera_movement' => getProp($segment, 'camera_movement'),
  9412. 'voice_actor' => $voice_actor,
  9413. 'dialogue' => getProp($segment, 'dialogue'),
  9414. 'frame_type' => getProp($segment, 'frame_type'),
  9415. 'scene' => getProp($segment, 'scene'),
  9416. 'characters' => getProp($segment, 'characters'),
  9417. 'tail_frame' => getProp($segment, 'tail_frame'),
  9418. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9419. 'voice_type' => $voice_type,
  9420. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9421. 'emotion' => $emotion,
  9422. 'emotion_type' => $emotion_type,
  9423. 'gender' => getProp($segment, 'gender', '0'),
  9424. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9425. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9426. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9427. 'pitch' => getProp($segment, 'pitch', 0),
  9428. 'created_at' => $now,
  9429. 'updated_at' => $now
  9430. ];
  9431. }
  9432. }
  9433. }
  9434. if ($segments) {
  9435. if ($del_flag) {
  9436. DB::table('mp_episode_segments')
  9437. ->where('anime_id', $anime_id)
  9438. ->where('episode_id', $episode_id)
  9439. ->delete();
  9440. }
  9441. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9442. if (!$boolen) {
  9443. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9444. Utils::throwError('20003:分镜内容保存失败');
  9445. }
  9446. }
  9447. dLog('deepseek')->info('segments', $segments);
  9448. // ace_mode=1: acts 返回值按合并格式调整
  9449. if ((int)$ace_mode === 1) {
  9450. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9451. $act_map = [];
  9452. foreach ($table_act_data as $item) {
  9453. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9454. }
  9455. $restructured_acts = [];
  9456. foreach ($acts as $act) {
  9457. $act_segments = getProp($act, 'segments', []);
  9458. if (!is_array($act_segments)) {
  9459. continue;
  9460. }
  9461. $merged_parts = [];
  9462. foreach ($act_segments as $seg) {
  9463. $seg_num = getProp($seg, 'segment_number');
  9464. $seg_content = getProp($seg, 'segment_content');
  9465. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9466. }
  9467. $act_content = implode("\n", $merged_parts);
  9468. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9469. $restructured_acts[] = [
  9470. 'anime_id' => $anime_id,
  9471. 'episode_id' => $episode_id,
  9472. 'episode_number' => $episode_number,
  9473. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9474. 'act_number' => getProp($act, 'act_number'),
  9475. 'act_title' => getProp($act, 'act_title'),
  9476. 'act_duration' => getProp($act, 'act_duration'),
  9477. 'act_content' => $act_content,
  9478. 'created_at' => $now,
  9479. 'updated_at' => $now,
  9480. ];
  9481. }
  9482. $acts = $restructured_acts;
  9483. }
  9484. $episode['episode_id'] = $episode_id;
  9485. $episode['roles'] = $merged_roles;
  9486. $episode['scenes'] = $merged_scenes;
  9487. $episode['props'] = $merged_props;
  9488. $episode['acts'] = $acts;
  9489. return [
  9490. 'episode' => $episode,
  9491. 'episode_id' => $episode_id,
  9492. 'merged_roles' => $merged_roles,
  9493. 'merged_scenes' => $merged_scenes,
  9494. 'merged_props' => $merged_props,
  9495. ];
  9496. }
  9497. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9498. {
  9499. $content = '';
  9500. foreach ($items as $item) {
  9501. $name = trim((string)getProp($item, $nameKey));
  9502. if ($name === '' || $name === '旁白') {
  9503. continue;
  9504. }
  9505. $description = trim((string)getProp($item, 'description'));
  9506. $content .= $name . ': ' . $description;
  9507. if ($nameKey == 'role') {
  9508. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9509. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9510. $voice_name = trim(getProp($item, 'voice_name'));
  9511. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9512. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9513. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9514. }else {
  9515. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9516. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9517. }
  9518. $content .= "\n";
  9519. }
  9520. return trim($content);
  9521. }
  9522. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9523. if ((int)$sequence <= 0) {
  9524. return [];
  9525. }
  9526. $origin_content = '';
  9527. if ($content) {
  9528. $origin_content = '本集剧情内容:'.$content;
  9529. }else {
  9530. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9531. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9532. }
  9533. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9534. // 获取分集信息
  9535. $episode = DB::table('mp_anime_episodes')
  9536. ->where('anime_id', $animeId)
  9537. ->where('episode_number', $sequence)
  9538. ->where('is_default', 1)
  9539. ->first();
  9540. if (!$episode) {
  9541. return [];
  9542. }
  9543. $episode_id = getProp($episode, 'id');
  9544. $episode_number = getProp($episode, 'episode_number');
  9545. $title = getProp($episode, 'title');
  9546. $intro = getProp($episode, 'intro');
  9547. $art_style = getProp($episode, 'art_style');
  9548. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9549. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9550. // 组装纯文本内容
  9551. $content = '';
  9552. // 添加分集标题和梗概
  9553. $content .= "###第{$episode_number}集:{$title}\n\n";
  9554. $content .= "###故事梗概\n";
  9555. $content .= trim($intro) . "\n\n";
  9556. // 添加美术风格
  9557. $content .= "###美术风格\n";
  9558. $content .= trim($art_style) . "\n\n";
  9559. // 添加主体列表
  9560. $content .= "###主体列表\n";
  9561. $pangbai_voice_prompt = "";
  9562. foreach ($roles as $role) {
  9563. $name = getProp($role, 'role');
  9564. $description = getProp($role, 'description');
  9565. $pic_prompt = getProp($role, 'pic_prompt');
  9566. $voice_prompt = getProp($role, 'voice_prompt');
  9567. $voice_name = getProp($role, 'voice_name');
  9568. $content .= "{$name}: {$description}";
  9569. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9570. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9571. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9572. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9573. $content .= "\n";
  9574. }
  9575. $content .= "\n";
  9576. // 添加场景列表
  9577. $content .= "###场景列表\n";
  9578. foreach ($scenes as $scene) {
  9579. $name = getProp($scene, 'scene');
  9580. $description = getProp($scene, 'description');
  9581. $pic_prompt = getProp($scene, 'pic_prompt');
  9582. $content .= "{$name}: {$description}";
  9583. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9584. $content .= "\n";
  9585. }
  9586. $content .= "\n";
  9587. // 获取分镜信息
  9588. $segments = DB::table('mp_episode_segments')
  9589. ->where('anime_id', $animeId)
  9590. ->where('episode_id', $episode_id)
  9591. ->orderBy('segment_number')
  9592. ->get();
  9593. if ($segments && count($segments) > 0) {
  9594. if ((int)$ace_mode === 1) {
  9595. $content .= "###分段剧本\n";
  9596. // 获取片段数量
  9597. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9598. $content .= "片段数量:{$act_count}\n";
  9599. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9600. $content .= "\n";
  9601. }else {
  9602. $content .= "###分镜剧本\n";
  9603. }
  9604. // 按幕分组
  9605. $currentAct = null;
  9606. foreach ($segments as $segment) {
  9607. $act_number = getProp($segment, 'act_number');
  9608. $act_title = getProp($segment, 'act_title');
  9609. $act_duration = getProp($segment, 'act_duration');
  9610. $segment_number = getProp($segment, 'segment_number');
  9611. $segment_content = getProp($segment, 'segment_content');
  9612. $scene_description = getProp($segment, 'scene_description');
  9613. $scene_name = getProp($segment, 'scene_name');
  9614. $composition = getProp($segment, 'composition');
  9615. $camera_movement = getProp($segment, 'camera_movement');
  9616. $voice_type = getProp($segment, 'voice_type');
  9617. $characters = getProp($segment, 'characters');
  9618. $dialogue = getProp($segment, 'dialogue');
  9619. $frame_type = getProp($segment, 'frame_type');
  9620. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9621. // 判断是否是全能模式
  9622. if ((int)$ace_mode === 1) { // 全能模式
  9623. // 如果是新的分段,添加分段标题
  9624. if ($act_number !== $currentAct) {
  9625. $currentAct = $act_number;
  9626. $content .= "##{$act_title}\n";
  9627. $content .= "时长:{$act_duration}s\n";
  9628. }
  9629. }else {
  9630. // 如果是新的幕,添加幕标题
  9631. if ($act_number !== $currentAct) {
  9632. $currentAct = $act_number;
  9633. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9634. }
  9635. }
  9636. // 添加分镜信息
  9637. $content .= "分镜{$segment_number}\n";
  9638. $content .= "分镜内容:\n{$segment_content}\n";
  9639. // $content .= "画面描述:{$scene_description}\n";
  9640. // $content .= "场景:{$scene_name}\n";
  9641. // $content .= "构图设计:{$composition}\n";
  9642. // $content .= "运镜调度:{$camera_movement}\n";
  9643. // if (!empty($voice_type)) {
  9644. // $content .= "配音角色:{$voice_type}\n";
  9645. // }
  9646. // if (!empty($characters)) {
  9647. // $content .= "出镜角色:{$characters}\n";
  9648. // }
  9649. // if (!empty($dialogue)) {
  9650. // $content .= "台词内容:\"{$dialogue}\"\n";
  9651. // }
  9652. // $content .= "画面类型:{$frame_type}\n";
  9653. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9654. $content .= "\n";
  9655. }
  9656. }
  9657. $content = trim($content);
  9658. if($content) $content = "上集剧本内容:\n{$content}";
  9659. return [
  9660. [
  9661. 'role' => 'user',
  9662. 'content' => $origin_content
  9663. ],
  9664. [
  9665. 'role' => 'assistant',
  9666. 'content' => $content
  9667. ]
  9668. ];
  9669. }
  9670. private function getEpisodeChatMessages($animeId, $sequence): array
  9671. {
  9672. if ((int)$sequence <= 0) {
  9673. return [];
  9674. }
  9675. return DB::table('mp_anime_records')
  9676. ->where('anime_id', $animeId)
  9677. ->where('sequence', $sequence)
  9678. ->where('episode_id', '>', 0)
  9679. ->select('role', 'content')
  9680. ->orderBy('created_at')
  9681. ->orderBy('id')
  9682. ->get()
  9683. ->map(function ($value) {
  9684. return (array)$value;
  9685. })
  9686. ->toArray();
  9687. }
  9688. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9689. {
  9690. $existingMap = [];
  9691. foreach ($existingItems as $item) {
  9692. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9693. if ($itemKey === '') {
  9694. continue;
  9695. }
  9696. $existingMap[$itemKey] = $item;
  9697. }
  9698. if (!$generatedItems) {
  9699. return array_values($existingItems);
  9700. }
  9701. $merged = [];
  9702. foreach ($generatedItems as $item) {
  9703. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9704. if ($itemKey === '') {
  9705. continue;
  9706. }
  9707. if (isset($existingMap[$itemKey])) {
  9708. if (trim((string)getProp($item, 'description')) === '') {
  9709. $merged[] = $existingMap[$itemKey];
  9710. continue;
  9711. }
  9712. // 检查内容是否发生变化
  9713. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9714. if (!$isChanged) {
  9715. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9716. $mergedItem = [
  9717. $nameKey => trim((string)getProp($item, $nameKey)),
  9718. 'description' => trim((string)getProp($item, 'description')),
  9719. ];
  9720. // 如果有 pic_prompt,添加到合并项中
  9721. $picPrompt = getProp($item, 'pic_prompt');
  9722. if (!empty($picPrompt)) {
  9723. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9724. }
  9725. // 继承现有项的 URL
  9726. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9727. if (!empty($existingUrl)) {
  9728. $mergedItem['url'] = $existingUrl;
  9729. }
  9730. // 继承现有项的 task_id
  9731. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9732. if (!empty($existingTaskId)) {
  9733. $mergedItem['task_id'] = $existingTaskId;
  9734. }
  9735. // 继承现有项的 task_status
  9736. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9737. if (!empty($existingTaskStatus)) {
  9738. $mergedItem['task_status'] = $existingTaskStatus;
  9739. }
  9740. // 保留生成项的音色字段
  9741. $voiceName = getProp($item, 'voice_name');
  9742. if (!empty($voiceName)) {
  9743. $mergedItem['voice_name'] = $voiceName;
  9744. }
  9745. $voiceType = getProp($item, 'voice_type');
  9746. if (!empty($voiceType)) {
  9747. $mergedItem['voice_type'] = $voiceType;
  9748. }
  9749. $audioUrl = getProp($item, 'voice_audio_url');
  9750. if (!empty($audioUrl)) {
  9751. $mergedItem['voice_audio_url'] = $audioUrl;
  9752. }
  9753. $merged[] = $mergedItem;
  9754. } else {
  9755. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9756. $mergedItem = [
  9757. $nameKey => trim((string)getProp($item, $nameKey)),
  9758. 'description' => trim((string)getProp($item, 'description')),
  9759. ];
  9760. // 如果有 pic_prompt,添加到合并项中
  9761. $picPrompt = getProp($item, 'pic_prompt');
  9762. if (!empty($picPrompt)) {
  9763. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9764. }
  9765. // 保留生成项的音色字段
  9766. $voiceName = getProp($item, 'voice_name');
  9767. if (!empty($voiceName)) {
  9768. $mergedItem['voice_name'] = $voiceName;
  9769. }
  9770. $voiceType = getProp($item, 'voice_type');
  9771. if (!empty($voiceType)) {
  9772. $mergedItem['voice_type'] = $voiceType;
  9773. }
  9774. $audioUrl = getProp($item, 'voice_audio_url');
  9775. if (!empty($audioUrl)) {
  9776. $mergedItem['voice_audio_url'] = $audioUrl;
  9777. }
  9778. // 不继承 URL、task_id 和 task_status(重置状态)
  9779. $merged[] = $mergedItem;
  9780. }
  9781. } else {
  9782. // 新增项,保留生成项的所有字段
  9783. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9784. }
  9785. }
  9786. return $merged ?: array_values($existingItems);
  9787. }
  9788. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9789. {
  9790. $resetItem = [
  9791. $nameKey => trim((string)getProp($item, $nameKey)),
  9792. 'description' => trim((string)getProp($item, 'description')),
  9793. ];
  9794. // 保留指定的字段
  9795. foreach ($preserveFields as $field) {
  9796. $value = getProp($item, $field);
  9797. if (!empty($value)) {
  9798. $resetItem[$field] = $value;
  9799. }
  9800. }
  9801. return $resetItem;
  9802. }
  9803. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9804. {
  9805. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9806. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9807. if ($existingKey !== $generatedKey) {
  9808. return true;
  9809. }
  9810. // 比较 description 是否变化
  9811. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9812. return true;
  9813. }
  9814. // 比较 pic_prompt 是否变化
  9815. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9816. }
  9817. private function normalizeEpisodeResourceKey($value): string
  9818. {
  9819. $value = trim((string)$value);
  9820. if ($value === '') {
  9821. return '';
  9822. }
  9823. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9824. }
  9825. // 生成全局角色图片
  9826. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9827. $anime_id = getProp($data, 'anime_id');
  9828. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9829. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9830. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9831. $art_style = getProp($anime, 'art_style');
  9832. $update_flag = false;
  9833. foreach ($roles as &$role) {
  9834. $role_name = getProp($role, 'role');
  9835. if ($role_name == '旁白') continue;
  9836. // 优先使用 pic_prompt,如果没有则使用 description
  9837. $pic_prompt = getProp($role, 'pic_prompt');
  9838. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9839. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9840. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9841. // 参考图地址
  9842. $ref_img_url = getProp($role, 'url');
  9843. if (!$is_force && $ref_img_url) continue;
  9844. $update_flag = true;
  9845. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9846. try {
  9847. $params = [
  9848. 'prompt' => $description,
  9849. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9850. 'ref_img_urls' => []
  9851. ];
  9852. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9853. $task_id = $task->id;
  9854. if (!$task_id) {
  9855. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9856. }
  9857. $role['task_id'] = $task_id;
  9858. $role['task_status'] = 'processing';
  9859. } catch (\Exception $e) {
  9860. Utils::throwError("20003:" . $e->getMessage());
  9861. }
  9862. }
  9863. if (!$update_flag) return true;
  9864. // 保存角色信息
  9865. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9866. 'roles' => json_encode($roles, 256),
  9867. 'generate_status' => '执行中',
  9868. 'generate_at' => date('Y-m-d H:i:s'),
  9869. 'updated_at' => date('Y-m-d H:i:s')
  9870. ]);
  9871. if (!$boolen) {
  9872. Utils::throwError('20003:保存角色信息失败');
  9873. }
  9874. return $boolen;
  9875. }
  9876. // 生成全局场景图片
  9877. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9878. $anime_id = getProp($data, 'anime_id');
  9879. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9880. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9881. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9882. $art_style = getProp($anime, 'art_style');
  9883. $update_flag = false;
  9884. foreach ($scenes as &$scene) {
  9885. $scene_name = getProp($scene, 'scene');
  9886. // 优先使用 pic_prompt,如果没有则使用 description
  9887. $pic_prompt = getProp($scene, 'pic_prompt');
  9888. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9889. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9890. // 参考图地址
  9891. $ref_img_url = getProp($scene, 'url');
  9892. if (!$is_force && $ref_img_url) continue;
  9893. $update_flag = true;
  9894. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9895. try {
  9896. $params = [
  9897. 'prompt' => $description,
  9898. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9899. 'ref_img_urls' => []
  9900. ];
  9901. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9902. $task_id = $task->id;
  9903. if (!$task_id) {
  9904. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9905. }
  9906. $scene['task_id'] = $task_id;
  9907. $scene['task_status'] = 'processing';
  9908. } catch (\Exception $e) {
  9909. Utils::throwError("20003:" . $e->getMessage());
  9910. }
  9911. }
  9912. if (!$update_flag) return true;
  9913. // 保存角色信息
  9914. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9915. 'scenes' => json_encode($scenes, 256),
  9916. 'generate_status' => '执行中',
  9917. 'generate_at' => date('Y-m-d H:i:s'),
  9918. 'updated_at' => date('Y-m-d H:i:s')
  9919. ]);
  9920. if (!$boolen) {
  9921. Utils::throwError('20003:保存角色信息失败');
  9922. }
  9923. return $boolen;
  9924. }
  9925. // 生成分镜主体、场景和道具图片
  9926. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9927. $character_prefix = '';
  9928. $scene_prefix = '';
  9929. $prop_prefix = '';
  9930. if ($art_style_type) {
  9931. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9932. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9933. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9934. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9935. }
  9936. $update_flag = false;
  9937. // 获取上一集的roles、scenes和props数据
  9938. $prev_roles = [];
  9939. $prev_scenes = [];
  9940. $prev_props = [];
  9941. if ($episode_number > 1) {
  9942. $prev_episode = DB::table('mp_anime_episodes')
  9943. ->where('anime_id', $anime_id)
  9944. ->where('episode_number', $episode_number - 1)
  9945. ->where('is_default', 1)
  9946. ->first();
  9947. if ($prev_episode) {
  9948. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9949. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9950. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9951. dLog('deepseek')->info("获取上一集数据成功", [
  9952. 'anime_id' => $anime_id,
  9953. 'prev_episode_number' => $episode_number - 1,
  9954. 'prev_roles_count' => count($prev_roles),
  9955. 'prev_scenes_count' => count($prev_scenes),
  9956. 'prev_props_count' => count($prev_props)
  9957. ]);
  9958. }
  9959. }
  9960. // 处理角色图片生成
  9961. foreach ($roles as &$role) {
  9962. $role_name = getProp($role, 'role');
  9963. if ($role_name == '旁白') continue;
  9964. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9965. if (isset($ref_products[$role_name])) {
  9966. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9967. if ($role['url']) continue;
  9968. }
  9969. $role_description = getProp($role, 'description');
  9970. $role_pic_prompt = getProp($role, 'pic_prompt');
  9971. $role_url = getProp($role, 'url');
  9972. // 检查是否可以从上一集继承
  9973. $inherited = false;
  9974. if (!$is_force && !empty($prev_roles)) {
  9975. foreach ($prev_roles as $prev_role) {
  9976. $prev_role_name = getProp($prev_role, 'role');
  9977. $prev_description = getProp($prev_role, 'description');
  9978. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9979. $prev_url = getProp($prev_role, 'url');
  9980. $prev_task_id = getProp($prev_role, 'task_id');
  9981. $prev_task_status = getProp($prev_role, 'task_status');
  9982. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9983. if ($role_name == $prev_role_name
  9984. && $role_description == $prev_description
  9985. && $role_pic_prompt == $prev_pic_prompt
  9986. && !empty($prev_url)) {
  9987. $role['task_id'] = $prev_task_id;
  9988. $role['task_status'] = $prev_task_status;
  9989. $role['url'] = $prev_url;
  9990. $inherited = true;
  9991. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9992. 'anime_id' => $anime_id,
  9993. 'episode_number' => $episode_number,
  9994. 'task_id' => $prev_task_id,
  9995. 'url' => $prev_url
  9996. ]);
  9997. break;
  9998. }
  9999. }
  10000. }
  10001. // 如果已继承或已有url,跳过生成
  10002. if ($inherited || (!$is_force && $role_url)) {
  10003. continue;
  10004. }
  10005. // 优先使用 pic_prompt,如果没有则使用 description
  10006. $pic_prompt = getProp($role, 'pic_prompt');
  10007. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10008. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10009. $update_flag = true;
  10010. // 调用AIImageGenerationService的生成图片任务接口
  10011. try {
  10012. $params = [
  10013. 'prompt' => $description,
  10014. 'ref_img_urls' => []
  10015. ];
  10016. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10017. $task_id = $task->id;
  10018. if (!$task_id) {
  10019. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10020. continue; // 不中断,继续处理其他角色
  10021. }
  10022. $role['task_id'] = $task_id;
  10023. $role['task_status'] = 'processing';
  10024. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10025. 'anime_id' => $anime_id,
  10026. 'episode_number' => $episode_number,
  10027. 'task_id' => $task_id
  10028. ]);
  10029. } catch (\Exception $e) {
  10030. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10031. // 不抛出异常,继续处理其他角色
  10032. }
  10033. }
  10034. // 处理场景图片生成
  10035. foreach ($scenes as &$scene) {
  10036. $scene_name = getProp($scene, 'scene');
  10037. $scene_description = getProp($scene, 'description');
  10038. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10039. $scene_url = getProp($scene, 'url');
  10040. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10041. if (isset($ref_products[$scene_name])) {
  10042. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10043. if ($scene['url']) continue;
  10044. }
  10045. // 检查是否可以从上一集继承
  10046. $inherited = false;
  10047. if (!$is_force && !empty($prev_scenes)) {
  10048. foreach ($prev_scenes as $prev_scene) {
  10049. $prev_scene_name = getProp($prev_scene, 'scene');
  10050. $prev_description = getProp($prev_scene, 'description');
  10051. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10052. $prev_url = getProp($prev_scene, 'url');
  10053. $prev_task_id = getProp($prev_scene, 'task_id');
  10054. $prev_task_status = getProp($prev_scene, 'task_status');
  10055. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10056. if ($scene_name == $prev_scene_name
  10057. && $scene_description == $prev_description
  10058. && $scene_pic_prompt == $prev_pic_prompt
  10059. && !empty($prev_url)) {
  10060. $scene['task_id'] = $prev_task_id;
  10061. $scene['task_status'] = $prev_task_status;
  10062. $scene['url'] = $prev_url;
  10063. $inherited = true;
  10064. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10065. 'anime_id' => $anime_id,
  10066. 'episode_number' => $episode_number,
  10067. 'task_id' => $prev_task_id,
  10068. 'url' => $prev_url
  10069. ]);
  10070. break;
  10071. }
  10072. }
  10073. }
  10074. // 如果已继承或已有url,跳过生成
  10075. if ($inherited || (!$is_force && $scene_url)) {
  10076. continue;
  10077. }
  10078. // 优先使用 pic_prompt,如果没有则使用 description
  10079. $pic_prompt = getProp($scene, 'pic_prompt');
  10080. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10081. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10082. $update_flag = true;
  10083. // 调用AIImageGenerationService的生成图片任务接口
  10084. try {
  10085. $params = [
  10086. 'prompt' => $description,
  10087. 'ref_img_urls' => []
  10088. ];
  10089. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10090. $task_id = $task->id;
  10091. if (!$task_id) {
  10092. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10093. continue; // 不中断,继续处理其他场景
  10094. }
  10095. $scene['task_id'] = $task_id;
  10096. $scene['task_status'] = 'processing';
  10097. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10098. 'anime_id' => $anime_id,
  10099. 'episode_number' => $episode_number,
  10100. 'task_id' => $task_id
  10101. ]);
  10102. } catch (\Exception $e) {
  10103. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10104. // 不抛出异常,继续处理其他场景
  10105. }
  10106. }
  10107. // 处理道具图片生成(逻辑与场景一致)
  10108. foreach ($props as &$prop) {
  10109. $prop_name = getProp($prop, 'prop');
  10110. $prop_description = getProp($prop, 'description');
  10111. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10112. $prop_url = getProp($prop, 'url');
  10113. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10114. if (isset($ref_products[$prop_name])) {
  10115. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10116. if ($prop['url']) continue;
  10117. }
  10118. // 检查是否可以从上一集继承
  10119. $inherited = false;
  10120. if (!$is_force && !empty($prev_props)) {
  10121. foreach ($prev_props as $prev_prop) {
  10122. $prev_prop_name = getProp($prev_prop, 'prop');
  10123. $prev_description = getProp($prev_prop, 'description');
  10124. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10125. $prev_url = getProp($prev_prop, 'url');
  10126. $prev_task_id = getProp($prev_prop, 'task_id');
  10127. $prev_task_status = getProp($prev_prop, 'task_status');
  10128. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10129. if ($prop_name == $prev_prop_name
  10130. && $prop_description == $prev_description
  10131. && $prop_pic_prompt == $prev_pic_prompt
  10132. && !empty($prev_url)) {
  10133. $prop['task_id'] = $prev_task_id;
  10134. $prop['task_status'] = $prev_task_status;
  10135. $prop['url'] = $prev_url;
  10136. $inherited = true;
  10137. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10138. 'anime_id' => $anime_id,
  10139. 'episode_number' => $episode_number,
  10140. 'task_id' => $prev_task_id,
  10141. 'url' => $prev_url
  10142. ]);
  10143. break;
  10144. }
  10145. }
  10146. }
  10147. // 如果已继承或已有url,跳过生成
  10148. if ($inherited || (!$is_force && $prop_url)) {
  10149. continue;
  10150. }
  10151. // 优先使用 pic_prompt,如果没有则使用 description
  10152. $pic_prompt = getProp($prop, 'pic_prompt');
  10153. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10154. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10155. $update_flag = true;
  10156. // 调用AIImageGenerationService的生成图片任务接口
  10157. try {
  10158. $params = [
  10159. 'prompt' => $description,
  10160. 'ref_img_urls' => []
  10161. ];
  10162. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10163. $task_id = $task->id;
  10164. if (!$task_id) {
  10165. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10166. continue; // 不中断,继续处理其他道具
  10167. }
  10168. $prop['task_id'] = $task_id;
  10169. $prop['task_status'] = 'processing';
  10170. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10171. 'anime_id' => $anime_id,
  10172. 'episode_number' => $episode_number,
  10173. 'task_id' => $task_id
  10174. ]);
  10175. } catch (\Exception $e) {
  10176. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10177. // 不抛出异常,继续处理其他道具
  10178. }
  10179. }
  10180. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10181. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10182. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10183. // // 保存剧集的角色和场景信息
  10184. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10185. // 'roles' => json_encode($roles, 256),
  10186. // 'scenes' => json_encode($scenes, 256),
  10187. // 'generate_status' => '执行中',
  10188. // 'generate_at' => date('Y-m-d H:i:s'),
  10189. // 'updated_at' => date('Y-m-d H:i:s')
  10190. // ]);
  10191. // if (!$boolen) {
  10192. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10193. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10194. // }
  10195. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10196. // 'episode_id' => $episode_id,
  10197. 'roles_count' => count($roles),
  10198. 'scenes_count' => count($scenes),
  10199. 'props_count' => count($props)
  10200. ]);
  10201. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10202. }
  10203. /**
  10204. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10205. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10206. *
  10207. * @param int $anime_id 动漫对话ID
  10208. * @param array $episode_roles 剧集角色数据
  10209. * @param array $episode_scenes 剧集场景数据
  10210. * @param array $episode_props 剧集道具数据
  10211. * @return bool
  10212. */
  10213. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10214. // 获取全局数据
  10215. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10216. if (!$anime) {
  10217. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10218. return false;
  10219. }
  10220. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10221. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10222. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10223. $roles_added = false;
  10224. $roles_updated = false;
  10225. $scenes_added = false;
  10226. $props_added = false;
  10227. // 处理角色同步
  10228. foreach ($episode_roles as $episode_role) {
  10229. $episode_role_name = getProp($episode_role, 'role');
  10230. $episode_description = getProp($episode_role, 'description');
  10231. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10232. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10233. // 跳过旁白
  10234. if ($episode_role_name == '旁白') {
  10235. continue;
  10236. }
  10237. // 检查全局中是否已存在相同的角色
  10238. $exists = false;
  10239. $global_role_index = -1;
  10240. foreach ($global_roles as $index => $global_role) {
  10241. $global_role_name = getProp($global_role, 'role');
  10242. $global_description = getProp($global_role, 'description');
  10243. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10244. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10245. if ($episode_role_name == $global_role_name
  10246. && $episode_description == $global_description
  10247. && $episode_pic_prompt == $global_pic_prompt) {
  10248. $exists = true;
  10249. $global_role_index = $index;
  10250. break;
  10251. }
  10252. }
  10253. // 如果不存在,则添加到全局
  10254. if (!$exists) {
  10255. $global_roles[] = $episode_role;
  10256. $roles_added = true;
  10257. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10258. 'anime_id' => $anime_id,
  10259. 'role' => $episode_role_name
  10260. ]);
  10261. } else {
  10262. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10263. if (!empty($episode_voice_prompt)) {
  10264. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10265. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10266. if ($global_voice_prompt !== $episode_voice_prompt) {
  10267. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10268. $roles_updated = true;
  10269. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10270. 'anime_id' => $anime_id,
  10271. 'role' => $episode_role_name,
  10272. 'voice_prompt' => $episode_voice_prompt
  10273. ]);
  10274. }
  10275. }
  10276. }
  10277. }
  10278. // 处理场景同步
  10279. foreach ($episode_scenes as $episode_scene) {
  10280. $episode_scene_name = getProp($episode_scene, 'scene');
  10281. $episode_description = getProp($episode_scene, 'description');
  10282. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10283. // 检查全局中是否已存在相同的场景
  10284. $exists = false;
  10285. foreach ($global_scenes as $global_scene) {
  10286. $global_scene_name = getProp($global_scene, 'scene');
  10287. $global_description = getProp($global_scene, 'description');
  10288. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10289. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10290. if ($episode_scene_name == $global_scene_name
  10291. && $episode_description == $global_description
  10292. && $episode_pic_prompt == $global_pic_prompt) {
  10293. $exists = true;
  10294. break;
  10295. }
  10296. }
  10297. // 如果不存在,则添加到全局
  10298. if (!$exists) {
  10299. $global_scenes[] = $episode_scene;
  10300. $scenes_added = true;
  10301. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10302. 'anime_id' => $anime_id,
  10303. 'scene' => $episode_scene_name
  10304. ]);
  10305. }
  10306. }
  10307. // 处理道具同步(逻辑与场景一致)
  10308. foreach ($episode_props as $episode_prop) {
  10309. $episode_prop_name = getProp($episode_prop, 'prop');
  10310. $episode_description = getProp($episode_prop, 'description');
  10311. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10312. // 检查全局中是否已存在相同的道具
  10313. $exists = false;
  10314. foreach ($global_props as $global_prop) {
  10315. $global_prop_name = getProp($global_prop, 'prop');
  10316. $global_description = getProp($global_prop, 'description');
  10317. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10318. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10319. if ($episode_prop_name == $global_prop_name
  10320. && $episode_description == $global_description
  10321. && $episode_pic_prompt == $global_pic_prompt) {
  10322. $exists = true;
  10323. break;
  10324. }
  10325. }
  10326. // 如果不存在,则添加到全局
  10327. if (!$exists) {
  10328. $global_props[] = $episode_prop;
  10329. $props_added = true;
  10330. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10331. 'anime_id' => $anime_id,
  10332. 'prop' => $episode_prop_name
  10333. ]);
  10334. }
  10335. }
  10336. // 如果有新增或更新,则更新全局数据
  10337. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10338. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10339. if ($roles_added || $roles_updated) {
  10340. $update_data['roles'] = json_encode($global_roles, 256);
  10341. }
  10342. if ($scenes_added) {
  10343. $update_data['scenes'] = json_encode($global_scenes, 256);
  10344. }
  10345. if ($props_added) {
  10346. $update_data['props'] = json_encode($global_props, 256);
  10347. }
  10348. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10349. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10350. 'anime_id' => $anime_id,
  10351. 'roles_added' => $roles_added,
  10352. 'roles_updated' => $roles_updated,
  10353. 'scenes_added' => $scenes_added,
  10354. 'props_added' => $props_added,
  10355. 'global_roles_count' => count($global_roles),
  10356. 'global_scenes_count' => count($global_scenes),
  10357. 'global_props_count' => count($global_props)
  10358. ]);
  10359. }
  10360. return true;
  10361. }
  10362. /**
  10363. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10364. *
  10365. * @param int $anime_id 动漫对话ID
  10366. * @param int $episode_id 分集ID
  10367. * @return bool
  10368. */
  10369. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10370. // 获取全局角色和场景数据
  10371. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10372. if (!$anime) {
  10373. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10374. return false;
  10375. }
  10376. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10377. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10378. // 获取指定的分集
  10379. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10380. if (!$episode) {
  10381. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10382. return false;
  10383. }
  10384. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10385. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10386. $roles_updated = false;
  10387. $scenes_updated = false;
  10388. // 继承角色的task_id、task_status和url
  10389. foreach ($episode_roles as &$episode_role) {
  10390. $episode_role_name = getProp($episode_role, 'role');
  10391. $episode_description = getProp($episode_role, 'description');
  10392. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10393. $episode_url = getProp($episode_role, 'url');
  10394. // 跳过旁白角色
  10395. if ($episode_role_name == '旁白') {
  10396. continue;
  10397. }
  10398. // 如果剧集中已有URL,跳过
  10399. if (!empty($episode_url)) {
  10400. continue;
  10401. }
  10402. // 遍历全局角色数据,查找匹配的角色
  10403. foreach ($global_roles as $global_role) {
  10404. $global_role_name = getProp($global_role, 'role');
  10405. $global_description = getProp($global_role, 'description');
  10406. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10407. $global_url = getProp($global_role, 'url');
  10408. $global_task_id = getProp($global_role, 'task_id');
  10409. $global_task_status = getProp($global_role, 'task_status');
  10410. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10411. if ($episode_role_name == $global_role_name
  10412. && $episode_description == $global_description
  10413. && $episode_pic_prompt == $global_pic_prompt) {
  10414. // 继承 task_id、task_status 和 url
  10415. if (!empty($global_task_id)) {
  10416. $episode_role['task_id'] = $global_task_id;
  10417. $episode_role['task_status'] = $global_task_status;
  10418. $roles_updated = true;
  10419. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10420. 'episode_id' => $episode_id,
  10421. 'role' => $episode_role_name,
  10422. 'task_id' => $global_task_id,
  10423. 'task_status' => $global_task_status
  10424. ]);
  10425. }
  10426. if (!empty($global_url)) {
  10427. $episode_role['url'] = $global_url;
  10428. $roles_updated = true;
  10429. dLog('deepseek')->info('剧集角色继承全局url', [
  10430. 'episode_id' => $episode_id,
  10431. 'role' => $episode_role_name,
  10432. 'url' => $global_url
  10433. ]);
  10434. }
  10435. break;
  10436. }
  10437. }
  10438. }
  10439. // 继承场景的task_id、task_status和url
  10440. foreach ($episode_scenes as &$episode_scene) {
  10441. $episode_scene_name = getProp($episode_scene, 'scene');
  10442. $episode_description = getProp($episode_scene, 'description');
  10443. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10444. $episode_url = getProp($episode_scene, 'url');
  10445. // 如果剧集中已有URL,跳过
  10446. if (!empty($episode_url)) {
  10447. continue;
  10448. }
  10449. // 遍历全局场景数据,查找匹配的场景
  10450. foreach ($global_scenes as $global_scene) {
  10451. $global_scene_name = getProp($global_scene, 'scene');
  10452. $global_description = getProp($global_scene, 'description');
  10453. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10454. $global_url = getProp($global_scene, 'url');
  10455. $global_task_id = getProp($global_scene, 'task_id');
  10456. $global_task_status = getProp($global_scene, 'task_status');
  10457. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10458. if ($episode_scene_name == $global_scene_name
  10459. && $episode_description == $global_description
  10460. && $episode_pic_prompt == $global_pic_prompt) {
  10461. // 继承 task_id、task_status 和 url
  10462. if (!empty($global_task_id)) {
  10463. $episode_scene['task_id'] = $global_task_id;
  10464. $episode_scene['task_status'] = $global_task_status;
  10465. $scenes_updated = true;
  10466. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10467. 'episode_id' => $episode_id,
  10468. 'scene' => $episode_scene_name,
  10469. 'task_id' => $global_task_id,
  10470. 'task_status' => $global_task_status
  10471. ]);
  10472. }
  10473. if (!empty($global_url)) {
  10474. $episode_scene['url'] = $global_url;
  10475. $scenes_updated = true;
  10476. dLog('deepseek')->info('剧集场景继承全局url', [
  10477. 'episode_id' => $episode_id,
  10478. 'scene' => $episode_scene_name,
  10479. 'url' => $global_url
  10480. ]);
  10481. }
  10482. break;
  10483. }
  10484. }
  10485. }
  10486. // 如果有更新,则保存到数据库
  10487. if ($roles_updated || $scenes_updated) {
  10488. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10489. if ($roles_updated) {
  10490. $update_data['roles'] = json_encode($episode_roles, 256);
  10491. }
  10492. if ($scenes_updated) {
  10493. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10494. }
  10495. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10496. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10497. 'episode_id' => $episode_id,
  10498. 'roles_updated' => $roles_updated,
  10499. 'scenes_updated' => $scenes_updated
  10500. ]);
  10501. }
  10502. return true;
  10503. }
  10504. public function chatChangeImg($data) {
  10505. $segment = getProp($data, 'segment');
  10506. $segment_content = getProp($segment, 'segment_content');
  10507. $prompt = getProp($data, 'prompt');
  10508. $ref_img = getProp($data, 'ref_img');
  10509. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10510. // 处理文本模型
  10511. $model = getProp($data, 'model');
  10512. if (!$model) {
  10513. // 用户没有输入,从anime表获取
  10514. $segment_id = getProp($segment, 'segment_id');
  10515. if ($segment_id) {
  10516. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10517. if ($episode_id) {
  10518. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10519. if ($anime_id) {
  10520. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10521. }
  10522. }
  10523. }
  10524. if (!$model) {
  10525. // anime表也没有,使用默认值
  10526. $model = 'doubao-seed-2-0-mini-260215';
  10527. }
  10528. }
  10529. // 验证模型是否在可用模型表中
  10530. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10531. $model = 'doubao-seed-2-0-mini-260215';
  10532. }
  10533. $messages[] =
  10534. [
  10535. 'role' => 'user',
  10536. 'content' => $question
  10537. ];
  10538. $post_data = [
  10539. 'model' => $model,
  10540. 'messages' => $messages,
  10541. // 'max_tokens' => 8192,
  10542. 'temperature' => 0.7,
  10543. 'frequency_penalty' => 0,
  10544. 'presence_penalty' => 0,
  10545. 'response_format' => ['type' => 'text'],
  10546. 'stream' => false // 是否启用流式输出
  10547. ];
  10548. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10549. // DeepSeek 官方模型使用 DeepSeek API
  10550. $chatResult = $this->chatOnly($post_data);
  10551. } else if (in_array($model, $this->gpt_text_models)) {
  10552. // GPT-5.4 模型使用 TokenRouter API
  10553. $chatResult = $this->gpt54ChatOnly($post_data);
  10554. } else {
  10555. // 其他模型使用火山引擎API
  10556. $chatResult = $this->volcEngineChatCompletion($post_data);
  10557. }
  10558. if (is_array($chatResult)) {
  10559. extract($chatResult);
  10560. }else {
  10561. Utils::throwError('20003: 接口调用失败!');
  10562. }
  10563. return [
  10564. 'type' => 'done',
  10565. // 'episode' => $episode,
  10566. 'answer' => $fullContent,
  10567. 'reasoning' => $fullReasoningContent,
  10568. 'usage' => $usage
  10569. ];
  10570. }
  10571. // 仅调用deepseek对话接口
  10572. private function chatOnly($post_data) {
  10573. $post_data['max_tokens'] = 300000;
  10574. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10575. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10576. $response = $result->getBody()->getContents();
  10577. $response_arr = json_decode($response, true);
  10578. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10579. $fullContent = '';
  10580. $fullReasoningContent = [];
  10581. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10582. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10583. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10584. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10585. }
  10586. return [
  10587. 'fullContent' => $fullContent,
  10588. 'fullReasoningContent' => $fullReasoningContent,
  10589. 'usage' => $usage
  10590. ];
  10591. }
  10592. // 仅调用 GPT-5.4 对话接口(非流式)
  10593. private function gpt54ChatOnly($post_data) {
  10594. $apiKey = env('GPT_54_API_KEY');
  10595. if (empty($apiKey)) {
  10596. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10597. }
  10598. // 先探活,服务不可用时自动重试
  10599. $this->ensureGptServiceAvailable();
  10600. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10601. $headers = [
  10602. 'Authorization' => 'Bearer ' . $apiKey,
  10603. 'Content-Type' => 'application/json'
  10604. ];
  10605. // 移除 thinking 参数,GPT-5.4 不支持
  10606. if (isset($post_data['thinking'])) {
  10607. unset($post_data['thinking']);
  10608. }
  10609. if (isset($post_data['reasoning_effort'])) {
  10610. unset($post_data['reasoning_effort']);
  10611. }
  10612. $post_data['max_completion_tokens'] = 100000;
  10613. // 确保 stream 为 false
  10614. $post_data['stream'] = false;
  10615. $maxRetries = $this->gptRetryTimes();
  10616. $interval = $this->gptRetryInterval();
  10617. $attempt = 0;
  10618. while (true) {
  10619. try {
  10620. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10621. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10622. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10623. 'json' => $post_data,
  10624. 'headers' => $headers
  10625. ]);
  10626. $response = $result->getBody()->getContents();
  10627. $response_arr = json_decode($response, true);
  10628. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10629. $fullContent = '';
  10630. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10631. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10632. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10633. }
  10634. return [
  10635. 'fullContent' => $fullContent,
  10636. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10637. 'usage' => $usage
  10638. ];
  10639. } catch (\Exception $e) {
  10640. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10641. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10642. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10643. throw $e;
  10644. }
  10645. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10646. 'retry' => $attempt + 1,
  10647. 'max_retries' => $maxRetries,
  10648. 'error' => $e->getMessage()
  10649. ]);
  10650. sleep($interval);
  10651. $attempt++;
  10652. }
  10653. }
  10654. }
  10655. private function splitContent($content) {
  10656. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10657. $chapters = [];
  10658. // 匹配章节标题格式:
  10659. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10660. // 2. 格式支持:
  10661. // - **第一集**
  10662. // - 第一集:
  10663. // - ###第1章 重生
  10664. // - ##第2章 相救
  10665. // - 第三章 共处一室
  10666. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10667. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10668. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10669. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10670. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10671. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10672. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10673. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10674. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10675. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10676. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10677. // 用正则找出所有章节标题的位置
  10678. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10679. $titleCount = count($matches[0]);
  10680. for ($i = 0; $i < $titleCount; $i++) {
  10681. // 获取当前章节标题
  10682. $titleLine = trim($matches[0][$i][0]);
  10683. // 去除标题开头的特殊符号
  10684. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10685. // 去除标题结尾的冒号和特殊符号
  10686. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10687. $cleanTitle = trim($cleanTitle);
  10688. // 获取当前标题的结束位置
  10689. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10690. // 获取下一个章节标题的开始位置(如果存在)
  10691. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10692. // 提取章节内容(从标题结束到下一个标题开始)
  10693. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10694. // 清理内容:去除前后空白和分隔线
  10695. $chapterContent = trim($chapterContent);
  10696. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10697. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10698. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10699. $chapters[] = [
  10700. 'title' => $cleanTitle,
  10701. 'content' => $chapterContent
  10702. ];
  10703. }
  10704. }
  10705. } else {
  10706. // 如果没有匹配到章节,返回整个内容
  10707. $chapters[] = [
  10708. 'title' => '',
  10709. 'content' => $content
  10710. ];
  10711. }
  10712. return $chapters;
  10713. }
  10714. public function getContentByBid($bid) {
  10715. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10716. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10717. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10718. $content = '';
  10719. foreach ($chapters as $chapter) {
  10720. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10721. }
  10722. return $content;
  10723. }
  10724. public function getContentByScriptId($script_id) {
  10725. $content = '';
  10726. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10727. if ($contents) {
  10728. $content = implode(PHP_EOL, $contents);
  10729. }else {
  10730. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10731. }
  10732. return $content;
  10733. }
  10734. /**
  10735. * 根据文件类型提取文本内容
  10736. *
  10737. * @param mixed $file 文件对象或文件路径
  10738. * @return string
  10739. */
  10740. public function extractFileContent($file) {
  10741. // 获取文件路径和扩展名
  10742. if (is_string($file)) {
  10743. $filePath = $file;
  10744. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10745. } else {
  10746. // Laravel UploadedFile 对象
  10747. $filePath = $file->getRealPath();
  10748. $extension = strtolower($file->getClientOriginalExtension());
  10749. }
  10750. $content = '';
  10751. switch ($extension) {
  10752. case 'txt':
  10753. $content = $this->extractTxtContent($filePath);
  10754. break;
  10755. case 'pdf':
  10756. $content = $this->extractPdfContent($filePath);
  10757. break;
  10758. case 'doc':
  10759. case 'docx':
  10760. $content = $this->extractWordContent($filePath);
  10761. break;
  10762. // case 'jpg':
  10763. // case 'jpeg':
  10764. // case 'png':
  10765. // case 'gif':
  10766. // case 'bmp':
  10767. // case 'webp':
  10768. // $content = $this->extractImageContent($filePath);
  10769. // break;
  10770. default:
  10771. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10772. }
  10773. return $content;
  10774. }
  10775. /**
  10776. * 提取 TXT 文件内容
  10777. */
  10778. private function extractTxtContent($filePath) {
  10779. if (!file_exists($filePath)) {
  10780. Utils::throwError('20003:文件不存在');
  10781. }
  10782. $content = file_get_contents($filePath);
  10783. // 尝试检测并转换编码
  10784. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10785. if ($encoding && $encoding !== 'UTF-8') {
  10786. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10787. }
  10788. return trim($content);
  10789. }
  10790. /**
  10791. * 提取 PDF 文件内容
  10792. */
  10793. private function extractPdfContent($filePath) {
  10794. if (!file_exists($filePath)) {
  10795. Utils::throwError('20003:文件不存在');
  10796. }
  10797. try {
  10798. $parser = new PdfParser();
  10799. $pdf = $parser->parseFile($filePath);
  10800. $content = $pdf->getText();
  10801. return trim($content);
  10802. } catch (\Exception $e) {
  10803. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10804. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10805. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10806. }
  10807. }
  10808. /**
  10809. * 提取 Word 文件内容(支持 doc 和 docx)
  10810. */
  10811. private function extractWordContent($filePath) {
  10812. if (!file_exists($filePath)) {
  10813. Utils::throwError('20003:文件不存在');
  10814. }
  10815. try {
  10816. $phpWord = WordIOFactory::load($filePath);
  10817. $content = '';
  10818. foreach ($phpWord->getSections() as $section) {
  10819. foreach ($section->getElements() as $element) {
  10820. $content .= $this->extractWordElementText($element);
  10821. }
  10822. }
  10823. return trim($content);
  10824. } catch (\Exception $e) {
  10825. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10826. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10827. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10828. }
  10829. }
  10830. /**
  10831. * 递归提取 Word 元素中的文本
  10832. */
  10833. private function extractWordElementText($element) {
  10834. $text = '';
  10835. if (method_exists($element, 'getText')) {
  10836. $text .= $element->getText() . "\n";
  10837. } elseif (method_exists($element, 'getElements')) {
  10838. foreach ($element->getElements() as $childElement) {
  10839. $text .= $this->extractWordElementText($childElement);
  10840. }
  10841. }
  10842. return $text;
  10843. }
  10844. /**
  10845. * 提取图片内容(使用火山引擎 OCR)
  10846. */
  10847. private function extractImageContent($filePath) {
  10848. if (!file_exists($filePath)) {
  10849. Utils::throwError('20003:文件不存在');
  10850. }
  10851. try {
  10852. // 读取图片并转换为 base64
  10853. $imageData = file_get_contents($filePath);
  10854. $base64Image = base64_encode($imageData);
  10855. // 调用火山引擎 OCR 服务
  10856. $content = $this->callVolcEngineOCR($base64Image);
  10857. return trim($content);
  10858. } catch (\Exception $e) {
  10859. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10860. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10861. Utils::throwError('20003:图片识别失败');
  10862. }
  10863. }
  10864. /**
  10865. * 调用火山引擎 OCR 服务识别图片文字
  10866. *
  10867. * @param string $base64Image base64 编码的图片数据
  10868. * @return string 识别的文字内容
  10869. */
  10870. private function callVolcEngineOCR($base64Image) {
  10871. $method = 'POST';
  10872. $service = 'cv';
  10873. $host = 'visual.volcengineapi.com';
  10874. $region = env('VOLC_REGION', 'cn-north-1');
  10875. $access_key = env('VOLC_AK');
  10876. $secret_key = env('VOLC_SK');
  10877. $action = 'OCRNormal';
  10878. $version = '2020-08-26';
  10879. if (!$access_key || !$secret_key) {
  10880. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10881. }
  10882. // 请求体
  10883. $body = json_encode([
  10884. 'image_base64' => $base64Image
  10885. ]);
  10886. // 生成签名
  10887. $headers = $this->getVolcEngineSignHeaders(
  10888. $method, $service, $host, $region,
  10889. "Action={$action}&Version={$version}",
  10890. $access_key, $secret_key, $body
  10891. );
  10892. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10893. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10894. 'headers' => $headers,
  10895. 'body' => $body
  10896. ]);
  10897. $response_arr = json_decode($response->getBody()->getContents(), true);
  10898. // 提取识别的文字
  10899. $textLines = [];
  10900. if (isset($response_arr['data']['line_texts'])) {
  10901. $textLines = $response_arr['data']['line_texts'];
  10902. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10903. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10904. if (isset($info['text'])) {
  10905. $textLines[] = $info['text'];
  10906. }
  10907. }
  10908. }
  10909. if (empty($textLines)) {
  10910. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10911. return '';
  10912. }
  10913. return implode("\n", $textLines);
  10914. }
  10915. /**
  10916. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10917. */
  10918. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10919. $contentType = 'application/json';
  10920. $accept = 'application/json';
  10921. // 获取当前UTC时间
  10922. $t = new DateTime('now', new DateTimeZone('UTC'));
  10923. $xDate = $t->format('Ymd\THis\Z');
  10924. $dateStamp = $t->format('Ymd');
  10925. // 计算 body 的 sha256 哈希
  10926. $payloadHash = hash('sha256', $body);
  10927. // 1. 拼接规范请求串
  10928. $canonicalUri = '/';
  10929. $canonicalQueryString = $queryString;
  10930. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10931. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10932. $canonicalRequest = implode("\n", [
  10933. $method,
  10934. $canonicalUri,
  10935. $canonicalQueryString,
  10936. $canonicalHeaders,
  10937. $signedHeaders,
  10938. $payloadHash
  10939. ]);
  10940. // 2. 拼接待签名字符串
  10941. $algorithm = 'HMAC-SHA256';
  10942. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10943. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10944. $stringToSign = implode("\n", [
  10945. $algorithm,
  10946. $xDate,
  10947. $credentialScope,
  10948. $hashedCanonicalRequest
  10949. ]);
  10950. // 3. 计算签名
  10951. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10952. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10953. // 4. 添加签名到请求头
  10954. $authorizationHeader = sprintf(
  10955. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10956. $algorithm,
  10957. $access_key,
  10958. $credentialScope,
  10959. $signedHeaders,
  10960. $signature
  10961. );
  10962. return [
  10963. 'Accept' => $accept,
  10964. 'Content-Type' => $contentType,
  10965. 'Host' => $host,
  10966. 'X-Date' => $xDate,
  10967. 'X-Content-Sha256'=> $payloadHash,
  10968. 'Authorization' => $authorizationHeader
  10969. ];
  10970. }
  10971. public function generateScriptWords($cid, $model = 'r1') {
  10972. ini_set('max_execution_time', 0);
  10973. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10974. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10975. // 模型兼容性处理和思考模式设置
  10976. $thinkingMode = 'disabled';
  10977. $reasoningEffort = 'high';
  10978. if ($model == 'r1') {
  10979. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10980. $thinkingMode = 'enabled';
  10981. } else {
  10982. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10983. $thinkingMode = 'disabled';
  10984. }
  10985. $messages = [
  10986. [
  10987. 'role' => 'system',
  10988. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10989. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10990. 2.非对话部分请全部用旁白角色代替
  10991. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10992. ],
  10993. [
  10994. 'role' => 'user',
  10995. 'content' => $content
  10996. ]
  10997. ];
  10998. $post_data = [
  10999. 'model' => $model,
  11000. 'messages' => $messages,
  11001. // 'max_tokens' => 8192,
  11002. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11003. 'frequency_penalty' => 0,
  11004. 'presence_penalty' => 0,
  11005. 'thinking' => ['type' => $thinkingMode],
  11006. 'response_format' => [
  11007. 'type' => 'text'
  11008. ],
  11009. 'stream' => false
  11010. ];
  11011. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11012. // 根据模型类型选择调用方法
  11013. $fullContent = '';
  11014. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11015. // DeepSeek 官方模型使用 DeepSeek API
  11016. $chatResult = $this->chatOnly($post_data);
  11017. } else if (in_array($model, $this->gpt_text_models)) {
  11018. // GPT-5.4 模型使用 TokenRouter API
  11019. $chatResult = $this->gpt54ChatOnly($post_data);
  11020. } else {
  11021. // 其他模型使用火山引擎API
  11022. $chatResult = $this->volcEngineChatCompletion($post_data);
  11023. }
  11024. if (is_array($chatResult)) {
  11025. $fullContent = $chatResult['fullContent'];
  11026. }
  11027. return $fullContent;
  11028. }
  11029. /**
  11030. * 智能化解析集数信息
  11031. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11032. *
  11033. * @param string $prompt 用户输入的提示词
  11034. * @return int|null 解析出的集数,如果没有找到则返回null
  11035. */
  11036. private function extractEpisodeNumber($prompt)
  11037. {
  11038. if (empty($prompt)) {
  11039. return null;
  11040. }
  11041. // 定义各种可能的表达模式
  11042. $patterns = [
  11043. // 基本模式:改成N集、调整成N集、修改成N集
  11044. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11045. // 扩展模式:分成N集、拆分成N集、分割成N集
  11046. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11047. // 数量模式:N集、共N集、总共N集
  11048. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11049. // 制作模式:制作N集、生成N集、创建N集
  11050. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11051. // 计划模式:计划N集、预计N集、打算N集
  11052. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11053. // 需要模式:需要N集、要N集
  11054. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11055. // 中文数字模式:改成三集、调整成五集等
  11056. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11057. // 英文数字模式
  11058. '/(?: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',
  11059. ];
  11060. // 中文数字转阿拉伯数字的映射
  11061. $chineseNumbers = [
  11062. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11063. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11064. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11065. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11066. ];
  11067. // 逐个尝试匹配模式
  11068. foreach ($patterns as $pattern) {
  11069. if (preg_match($pattern, $prompt, $matches)) {
  11070. $number = trim($matches[1]);
  11071. // 如果是中文数字,转换为阿拉伯数字
  11072. if (isset($chineseNumbers[$number])) {
  11073. return $chineseNumbers[$number];
  11074. }
  11075. // 如果是阿拉伯数字,直接返回
  11076. if (is_numeric($number)) {
  11077. $episodeNum = intval($number);
  11078. // 合理性检查:集数应该在1-100之间
  11079. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11080. return $episodeNum;
  11081. }
  11082. }
  11083. }
  11084. }
  11085. return null;
  11086. }
  11087. /**
  11088. * 调用火山引擎对话(Chat) API
  11089. *
  11090. * @param array $params 包含以下参数:
  11091. * - model: 模型ID(必填)
  11092. * - messages: 消息列表(必填)
  11093. * - stream: 是否流式输出(可选,默认false)
  11094. * - max_tokens: 最大输出token数(可选)
  11095. * - temperature: 采样温度(可选,默认1)
  11096. * - top_p: 核采样概率(可选,默认0.7)
  11097. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11098. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11099. * - stop: 停止词(可选)
  11100. * - tools: 工具列表(可选)
  11101. * @return array|Generator 非流式返回数组,流式返回生成器
  11102. */
  11103. public function volcEngineChatCompletion(array $params)
  11104. {
  11105. $apiKey = env('VOLC_AI_API_KEY');
  11106. if (empty($apiKey)) {
  11107. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11108. }
  11109. // 构建请求参数
  11110. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11111. $requestData = [
  11112. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11113. 'messages' => $params['messages'] ?? [],
  11114. ];
  11115. if (!in_array($originalModel, $this->valid_text_models)) {
  11116. Utils::throwError('20003:该模型不支持!');
  11117. }
  11118. // 添加可选参数
  11119. if (isset($params['stream'])) {
  11120. $requestData['stream'] = $params['stream'];
  11121. }
  11122. if (isset($params['stream_options'])) {
  11123. $requestData['stream_options'] = $params['stream_options'];
  11124. }
  11125. if (isset($params['max_tokens'])) {
  11126. $requestData['max_tokens'] = $params['max_tokens'];
  11127. }else if (isset($params['max_completion_tokens'])) {
  11128. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11129. }else {
  11130. $requestData['max_completion_tokens'] = 100000;
  11131. }
  11132. if (isset($params['temperature'])) {
  11133. $requestData['temperature'] = $params['temperature'];
  11134. }
  11135. if (isset($params['top_p'])) {
  11136. $requestData['top_p'] = $params['top_p'];
  11137. }
  11138. if (isset($params['frequency_penalty'])) {
  11139. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11140. }
  11141. if (isset($params['presence_penalty'])) {
  11142. $requestData['presence_penalty'] = $params['presence_penalty'];
  11143. }
  11144. if (isset($params['stop'])) {
  11145. $requestData['stop'] = $params['stop'];
  11146. }
  11147. if (isset($params['tools'])) {
  11148. $requestData['tools'] = $params['tools'];
  11149. }
  11150. if (isset($params['tool_choice'])) {
  11151. $requestData['tool_choice'] = $params['tool_choice'];
  11152. }
  11153. if (isset($params['response_format'])) {
  11154. $requestData['response_format'] = $params['response_format'];
  11155. }
  11156. if (isset($params['thinking'])) {
  11157. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11158. if (is_array($params['thinking'])) {
  11159. $requestData['thinking'] = $params['thinking'];
  11160. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11161. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11162. }
  11163. } else {
  11164. $requestData['thinking'] = ['type' => $params['thinking']];
  11165. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11166. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11167. }
  11168. }
  11169. } else {
  11170. $requestData['thinking'] = ['type' => 'disabled'];
  11171. }
  11172. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11173. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11174. try {
  11175. // 判断是否为流式输出
  11176. $isStream = isset($params['stream']) && $params['stream'] === true;
  11177. if ($isStream) {
  11178. // 流式输出
  11179. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11180. } else {
  11181. // 非流式输出
  11182. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11183. 'headers' => [
  11184. 'Authorization' => 'Bearer ' . $apiKey,
  11185. 'Content-Type' => 'application/json',
  11186. ],
  11187. 'json' => $requestData
  11188. ]);
  11189. $responseData = json_decode($response->getBody(), true);
  11190. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11191. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11192. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11193. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11194. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11195. }
  11196. return [
  11197. 'fullContent' => $fullContent,
  11198. 'fullReasoningContent' => $fullReasoningContent,
  11199. 'usage' => $usage
  11200. ];
  11201. }
  11202. } catch (\Exception $e) {
  11203. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11204. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11205. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11206. }
  11207. }
  11208. /**
  11209. * 火山引擎对话API流式输出
  11210. *
  11211. * @param Client $client HTTP客户端
  11212. * @param string $apiKey API密钥
  11213. * @param array $requestData 请求数据
  11214. * @return Generator
  11215. */
  11216. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11217. {
  11218. try {
  11219. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11220. 'headers' => [
  11221. 'Authorization' => 'Bearer ' . $apiKey,
  11222. 'Content-Type' => 'application/json',
  11223. ],
  11224. 'json' => $requestData,
  11225. 'stream' => true
  11226. ]);
  11227. $body = $response->getBody();
  11228. $buffer = '';
  11229. $fullContent = '';
  11230. $fullReasoningContent = '';
  11231. $usage = [];
  11232. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11233. // 逐行读取流式响应
  11234. while (!$body->eof()) {
  11235. $chunk = $body->read(1024);
  11236. $buffer .= $chunk;
  11237. // 按行分割
  11238. $lines = explode("\n", $buffer);
  11239. $buffer = array_pop($lines);
  11240. foreach ($lines as $line) {
  11241. $line = trim($line);
  11242. if (empty($line)) {
  11243. continue;
  11244. }
  11245. // 检查是否是SSE数据行
  11246. if (strpos($line, 'data: ') !== 0) {
  11247. continue;
  11248. }
  11249. $data = substr($line, 6);
  11250. if ($data === '[DONE]') {
  11251. dLog('deepseek')->info('收到结束标记');
  11252. break 2;
  11253. }
  11254. try {
  11255. $json = json_decode($data, true);
  11256. if (json_last_error() !== JSON_ERROR_NONE) {
  11257. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11258. continue;
  11259. }
  11260. if (isset($json['choices'][0]['delta'])) {
  11261. $delta = $json['choices'][0]['delta'];
  11262. // 处理思维链内容
  11263. if (isset($delta['reasoning_content'])) {
  11264. $fullReasoningContent .= $delta['reasoning_content'];
  11265. yield [
  11266. 'type' => 'reasoning',
  11267. 'content' => $delta['reasoning_content'],
  11268. 'full_reasoning' => $fullReasoningContent
  11269. ];
  11270. }
  11271. // 处理回答内容
  11272. if (isset($delta['content'])) {
  11273. $fullContent .= $delta['content'];
  11274. yield [
  11275. 'type' => 'content',
  11276. 'content' => $delta['content'],
  11277. ];
  11278. }
  11279. }
  11280. // 获取使用统计信息
  11281. if (isset($json['usage'])) {
  11282. $usage = $json['usage'];
  11283. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11284. }
  11285. } catch (\Exception $e) {
  11286. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11287. continue;
  11288. }
  11289. }
  11290. }
  11291. dLog('deepseek')->info('流式读取完成', [
  11292. 'content_length' => strlen($fullContent),
  11293. 'reasoning_length' => strlen($fullReasoningContent)
  11294. ]);
  11295. yield [
  11296. 'type' => 'done',
  11297. 'full_content' => $fullContent,
  11298. 'full_reasoning' => $fullReasoningContent,
  11299. 'usage' => $usage
  11300. ];
  11301. } catch (\Exception $e) {
  11302. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11303. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11304. throw $e;
  11305. }
  11306. }
  11307. /**
  11308. * 检查并创建图片生成任务
  11309. *
  11310. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11311. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11312. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11313. * @param string $art_style 美术风格
  11314. * @return array 更新后的资源列表
  11315. */
  11316. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11317. {
  11318. // 确保参数为数组
  11319. $merged_items = is_array($merged_items) ? $merged_items : [];
  11320. $global_items = is_array($global_items) ? $global_items : [];
  11321. // 构建全局资源映射表,用于快速查找
  11322. $global_map = [];
  11323. foreach ($global_items as $item) {
  11324. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11325. if ($itemKey === '') {
  11326. continue;
  11327. }
  11328. $global_map[$itemKey] = $item;
  11329. }
  11330. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11331. foreach ($merged_items as &$item) {
  11332. $item_name = getProp($item, $nameKey);
  11333. $item_description = getProp($item, 'description');
  11334. // $item_url = getProp($item, 'url');
  11335. // // 如果已有图片URL,跳过
  11336. // if (!empty($item_url)) {
  11337. // continue;
  11338. // }
  11339. // 如果是旁白角色,跳过
  11340. if ($nameKey === 'role' && $item_name === '旁白') {
  11341. continue;
  11342. }
  11343. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11344. if ($itemKey === '') {
  11345. continue;
  11346. }
  11347. $need_create_task = false;
  11348. // 条件1:在全局资源中找不到匹配的名称
  11349. if (!isset($global_map[$itemKey])) {
  11350. $need_create_task = true;
  11351. } else {
  11352. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11353. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11354. $current_description = trim((string)$item_description);
  11355. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11356. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11357. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11358. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11359. $need_create_task = true;
  11360. }
  11361. }
  11362. // 如果需要创建任务,调用图片生成服务
  11363. if ($need_create_task) {
  11364. try {
  11365. // 优先使用 pic_prompt,如果没有则使用 description
  11366. $pic_prompt = getProp($item, 'pic_prompt');
  11367. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11368. // 添加美术风格前缀
  11369. if ($art_style) {
  11370. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11371. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11372. $description = "{$prefix}:{$description}";
  11373. }
  11374. $params = [
  11375. 'prompt' => $description,
  11376. 'ref_img_urls' => []
  11377. ];
  11378. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11379. $task_id = $task->id;
  11380. if ($task_id) {
  11381. $item['task_id'] = $task_id;
  11382. $item['task_status'] = 'processing';
  11383. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11384. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11385. }
  11386. } catch (\Exception $e) {
  11387. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11388. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11389. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11390. // 不抛出异常,继续处理其他资源
  11391. }
  11392. }
  11393. }
  11394. return $merged_items;
  11395. }
  11396. /**
  11397. * 同步新出现的主体和场景到全局
  11398. *
  11399. * @param int $anime_id 动漫ID
  11400. * @param array $merged_roles 合并后的角色列表
  11401. * @param array $merged_scenes 合并后的场景列表
  11402. * @param array $global_roles 全局角色列表
  11403. * @param array $global_scenes 全局场景列表
  11404. * @return void
  11405. */
  11406. private function syncNewResourcesToGlobal(
  11407. int $anime_id,
  11408. array $merged_roles,
  11409. array $merged_scenes,
  11410. array $global_roles,
  11411. array $global_scenes
  11412. ): void {
  11413. // 构建全局角色映射表
  11414. $global_role_map = [];
  11415. foreach ($global_roles as $role) {
  11416. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11417. if ($roleKey !== '') {
  11418. $global_role_map[$roleKey] = $role;
  11419. }
  11420. }
  11421. // 构建全局场景映射表
  11422. $global_scene_map = [];
  11423. foreach ($global_scenes as $scene) {
  11424. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11425. if ($sceneKey !== '') {
  11426. $global_scene_map[$sceneKey] = $scene;
  11427. }
  11428. }
  11429. $need_update = false;
  11430. $new_global_roles = $global_roles;
  11431. $new_global_scenes = $global_scenes;
  11432. // 检查并添加新角色到全局
  11433. foreach ($merged_roles as $role) {
  11434. $role_name = getProp($role, 'role');
  11435. // 跳过旁白
  11436. if ($role_name === '旁白') {
  11437. continue;
  11438. }
  11439. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11440. if ($roleKey === '') {
  11441. continue;
  11442. }
  11443. // 如果全局中不存在该角色,添加到全局
  11444. if (!isset($global_role_map[$roleKey])) {
  11445. $new_global_roles[] = [
  11446. 'role' => $role_name,
  11447. 'description' => getProp($role, 'description', ''),
  11448. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11449. 'voice_name' => getProp($role, 'voice_name', ''),
  11450. 'voice_type' => getProp($role, 'voice_type', ''),
  11451. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11452. 'url' => getProp($role, 'url', ''),
  11453. 'task_id' => getProp($role, 'task_id', ''),
  11454. 'task_status' => getProp($role, 'task_status', ''),
  11455. ];
  11456. $global_role_map[$roleKey] = true; // 标记已添加
  11457. $need_update = true;
  11458. dLog('deepseek')->info("新角色同步到全局", [
  11459. 'anime_id' => $anime_id,
  11460. 'role' => $role_name,
  11461. 'task_id' => getProp($role, 'task_id', ''),
  11462. ]);
  11463. }
  11464. // else {
  11465. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11466. // $global_role = $global_role_map[$roleKey];
  11467. // if (is_array($global_role)) {
  11468. // $updated = false;
  11469. // $update_fields = [];
  11470. // // 检查描述是否更新
  11471. // $current_description = trim((string)getProp($role, 'description'));
  11472. // $global_description = trim((string)getProp($global_role, 'description'));
  11473. // if ($current_description !== '' && $current_description !== $global_description) {
  11474. // $updated = true;
  11475. // $update_fields[] = 'description';
  11476. // }
  11477. // // 检查pic_prompt是否更新
  11478. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11479. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11480. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11481. // $updated = true;
  11482. // $update_fields[] = 'pic_prompt';
  11483. // }
  11484. // // 检查图片任务信息是否更新
  11485. // $current_task_id = getProp($role, 'task_id');
  11486. // $global_task_id = getProp($global_role, 'task_id');
  11487. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11488. // $updated = true;
  11489. // $update_fields[] = 'task_id';
  11490. // }
  11491. // // 如果有更新,同步到全局
  11492. // if ($updated) {
  11493. // foreach ($new_global_roles as &$global_role_item) {
  11494. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11495. // if ($global_role_key === $roleKey) {
  11496. // if (in_array('description', $update_fields)) {
  11497. // $global_role_item['description'] = $current_description;
  11498. // }
  11499. // if (in_array('pic_prompt', $update_fields)) {
  11500. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11501. // }
  11502. // if (in_array('task_id', $update_fields)) {
  11503. // $global_role_item['task_id'] = $current_task_id;
  11504. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11505. // $global_role_item['url'] = getProp($role, 'url', '');
  11506. // }
  11507. // break;
  11508. // }
  11509. // }
  11510. // $need_update = true;
  11511. // dLog('deepseek')->info("角色信息更新到全局", [
  11512. // 'anime_id' => $anime_id,
  11513. // 'role' => $role_name,
  11514. // 'update_fields' => implode(',', $update_fields),
  11515. // ]);
  11516. // }
  11517. // }
  11518. // }
  11519. }
  11520. // 检查并添加新场景到全局
  11521. foreach ($merged_scenes as $scene) {
  11522. $scene_name = getProp($scene, 'scene');
  11523. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11524. if ($sceneKey === '') {
  11525. continue;
  11526. }
  11527. // 如果全局中不存在该场景,添加到全局
  11528. if (!isset($global_scene_map[$sceneKey])) {
  11529. $new_global_scenes[] = [
  11530. 'scene' => $scene_name,
  11531. 'description' => getProp($scene, 'description', ''),
  11532. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11533. 'url' => getProp($scene, 'url', ''),
  11534. 'task_id' => getProp($scene, 'task_id', ''),
  11535. 'task_status' => getProp($scene, 'task_status', ''),
  11536. ];
  11537. $global_scene_map[$sceneKey] = true; // 标记已添加
  11538. $need_update = true;
  11539. dLog('deepseek')->info("新场景同步到全局", [
  11540. 'anime_id' => $anime_id,
  11541. 'scene' => $scene_name,
  11542. 'task_id' => getProp($scene, 'task_id', ''),
  11543. ]);
  11544. }
  11545. // else {
  11546. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11547. // $global_scene = $global_scene_map[$sceneKey];
  11548. // if (is_array($global_scene)) {
  11549. // $updated = false;
  11550. // $update_fields = [];
  11551. // // 检查描述是否更新
  11552. // $current_description = trim((string)getProp($scene, 'description'));
  11553. // $global_description = trim((string)getProp($global_scene, 'description'));
  11554. // if ($current_description !== '' && $current_description !== $global_description) {
  11555. // $updated = true;
  11556. // $update_fields[] = 'description';
  11557. // }
  11558. // // 检查pic_prompt是否更新
  11559. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11560. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11561. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11562. // $updated = true;
  11563. // $update_fields[] = 'pic_prompt';
  11564. // }
  11565. // // 检查图片任务信息是否更新
  11566. // $current_task_id = getProp($scene, 'task_id');
  11567. // $global_task_id = getProp($global_scene, 'task_id');
  11568. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11569. // $updated = true;
  11570. // $update_fields[] = 'task_id';
  11571. // }
  11572. // // 如果有更新,同步到全局
  11573. // if ($updated) {
  11574. // foreach ($new_global_scenes as &$global_scene_item) {
  11575. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11576. // if ($global_scene_key === $sceneKey) {
  11577. // if (in_array('description', $update_fields)) {
  11578. // $global_scene_item['description'] = $current_description;
  11579. // }
  11580. // if (in_array('pic_prompt', $update_fields)) {
  11581. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11582. // }
  11583. // if (in_array('task_id', $update_fields)) {
  11584. // $global_scene_item['task_id'] = $current_task_id;
  11585. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11586. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11587. // }
  11588. // break;
  11589. // }
  11590. // }
  11591. // $need_update = true;
  11592. // dLog('deepseek')->info("场景信息更新到全局", [
  11593. // 'anime_id' => $anime_id,
  11594. // 'scene' => $scene_name,
  11595. // 'update_fields' => implode(',', $update_fields),
  11596. // ]);
  11597. // }
  11598. // }
  11599. // }
  11600. }
  11601. // 如果有新增或更新,更新数据库
  11602. if ($need_update) {
  11603. $update_data = [
  11604. 'roles' => json_encode($new_global_roles, 256),
  11605. 'scenes' => json_encode($new_global_scenes, 256),
  11606. 'updated_at' => date('Y-m-d H:i:s'),
  11607. ];
  11608. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11609. if ($result !== false) {
  11610. dLog('deepseek')->info("全局角色和场景更新成功", [
  11611. 'anime_id' => $anime_id,
  11612. 'roles_count' => count($new_global_roles),
  11613. 'scenes_count' => count($new_global_scenes),
  11614. ]);
  11615. } else {
  11616. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11617. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11618. }
  11619. }
  11620. }
  11621. }