DeepSeekService.php 728 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147
  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. $originalName = $file->getClientOriginalName();
  244. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  245. if (!$script_name) {
  246. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  247. }
  248. // 如果同一用户的剧本名存在则提示
  249. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  250. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  251. }
  252. // 插入数据到mp_scripts表
  253. $script_id = DB::table('mp_scripts')->insertGetId([
  254. 'script_name' => $script_name,
  255. 'user_id' => $uid,
  256. 'cpid' => $cpid,
  257. 'content' => $content,
  258. 'created_at' => date('Y-m-d H:i:s'),
  259. 'updated_at' => date('Y-m-d H:i:s')
  260. ]);
  261. return [
  262. 'script_id' => $script_id,
  263. 'script_name' => $script_name
  264. ];
  265. }
  266. /**
  267. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  268. *
  269. * @param array $data 请求参数
  270. * @return array 返回结果数组
  271. */
  272. public function newGenerateText($data) {
  273. // 获取请求参数
  274. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  275. $messages = getProp($data, 'messages', []);
  276. $systemPrompt = getProp($data, 'system_prompt', '');
  277. $prompt = getProp($data, 'prompt', '');
  278. $images = getProp($data, 'images', []); // 支持多张图片
  279. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  280. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  281. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  282. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  283. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  284. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  285. $generateTaskId = 0;
  286. if ($script_id > 0) {
  287. $uid = Site::getUid();
  288. $existingTask = DB::table('mp_script_generate_tasks')
  289. ->where('uid', $uid)
  290. ->where('script_id', $script_id)
  291. ->orderByDesc('id')
  292. ->first();
  293. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  294. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  295. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  296. }
  297. }
  298. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  299. $originalContent = '';
  300. if ($script_id > 0) {
  301. $script = DB::table('mp_scripts')
  302. ->where('id', $script_id)
  303. ->where('is_deleted', 0)
  304. ->first();
  305. if (!$script) {
  306. Utils::throwError('20003:剧本不存在或已删除');
  307. }
  308. $originalContent = $script->content ?? '';
  309. if (empty($originalContent)) {
  310. Utils::throwError('20003:剧本内容为空');
  311. }
  312. // 将剧本内容添加到提示词前面
  313. if (!empty($originalContent)) {
  314. if (!empty($prompt)) {
  315. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  316. } else {
  317. $prompt = "原文内容:\n" . $originalContent;
  318. }
  319. }
  320. }
  321. // 新增: 如果提供了template_id,从数据库获取template_prompt
  322. if ($templateId > 0) {
  323. $template = DB::table('mp_prompt_templates')
  324. ->where('id', $templateId)
  325. ->where('is_deleted', 0)
  326. ->first();
  327. if (!$template) {
  328. Utils::throwError('20003:模板不存在或已删除');
  329. }
  330. $templatePrompt = $template->template_prompt ?? '';
  331. // 将模板提示词和用户输入的prompt组合
  332. // 模板为准,用户输入作为补充要求
  333. if (!empty($templatePrompt)) {
  334. if (!empty($prompt)) {
  335. $prompt = $templatePrompt . "\n\n" . $prompt;
  336. } else {
  337. $prompt = $templatePrompt;
  338. }
  339. }
  340. }
  341. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  342. if (empty($messages)) {
  343. $messages = [];
  344. // 添加系统提示词
  345. if (!empty($systemPrompt)) {
  346. $messages[] = [
  347. 'role' => 'system',
  348. 'content' => $systemPrompt
  349. ];
  350. }
  351. // 构建用户消息内容(支持文本+图片)
  352. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  353. $userMessage = [
  354. 'role' => 'user',
  355. 'content' => []
  356. ];
  357. // 添加文本内容
  358. if (!empty($prompt)) {
  359. $userMessage['content'][] = [
  360. 'type' => 'text',
  361. 'text' => $prompt
  362. ];
  363. }
  364. // 处理上传的图片文件
  365. if (!empty($images)) {
  366. if (!is_array($images)) {
  367. $images = [$images];
  368. }
  369. foreach ($images as $image) {
  370. $imageBase64 = $this->processImageToBase64($image);
  371. if ($imageBase64) {
  372. $userMessage['content'][] = [
  373. 'type' => 'image_url',
  374. 'image_url' => [
  375. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  376. ]
  377. ];
  378. }
  379. }
  380. }
  381. // 处理图片URL
  382. if (!empty($imageUrls)) {
  383. if (!is_array($imageUrls)) {
  384. $imageUrls = [$imageUrls];
  385. }
  386. foreach ($imageUrls as $url) {
  387. if (!empty($url)) {
  388. $userMessage['content'][] = [
  389. 'type' => 'image_url',
  390. 'image_url' => [
  391. 'url' => $url
  392. ]
  393. ];
  394. }
  395. }
  396. }
  397. // 如果只有文本内容,简化为字符串格式
  398. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  399. $userMessage['content'] = $userMessage['content'][0]['text'];
  400. }
  401. $messages[] = $userMessage;
  402. }
  403. }
  404. // 验证messages不为空
  405. if (empty($messages)) {
  406. Utils::throwError('20003:请提供有效的对话内容');
  407. }
  408. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  409. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  410. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  411. if ($model === 'deepseek-chat') {
  412. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  413. $model = 'deepseek-v4-flash';
  414. $thinkingMode = 'disabled';
  415. } elseif ($model === 'deepseek-reasoner') {
  416. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  417. $model = 'deepseek-v4-flash';
  418. $thinkingMode = 'enabled';
  419. }
  420. // 构建请求参数(非流式)
  421. $post_data = [
  422. 'model' => $model,
  423. 'messages' => $messages,
  424. 'temperature' => getProp($data, 'temperature', 1),
  425. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  426. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  427. 'thinking' => ['type' => $thinkingMode],
  428. 'stream' => false // 非流式输出
  429. ];
  430. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  431. // 添加可选参数
  432. if (isset($data['top_p'])) {
  433. $post_data['top_p'] = $data['top_p'];
  434. }
  435. // 新增: 根据response_format设置响应格式
  436. if ($responseFormat === 'json') {
  437. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  438. $hasJsonKeyword = false;
  439. foreach ($post_data['messages'] as $message) {
  440. if (isset($message['content'])) {
  441. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  442. if (stripos($content, 'json') !== false) {
  443. $hasJsonKeyword = true;
  444. break;
  445. }
  446. }
  447. }
  448. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  449. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  450. if (!$hasJsonKeyword) {
  451. $lastMessageIndex = count($post_data['messages']) - 1;
  452. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  453. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  454. // 如果content是字符串,直接追加
  455. if (is_string($lastContent)) {
  456. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  457. }
  458. // 如果content是数组(包含文本和图片),在文本部分追加
  459. else if (is_array($lastContent)) {
  460. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  461. if ($contentPart['type'] === 'text') {
  462. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  463. break;
  464. }
  465. }
  466. }
  467. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  468. }
  469. }
  470. // 设置response_format参数(所有支持的模型)
  471. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  472. // DeepSeek模型
  473. $post_data['response_format'] = ['type' => 'json_object'];
  474. } else if (in_array($model, $this->gpt_text_models)) {
  475. // GPT模型
  476. $post_data['response_format'] = ['type' => 'json_object'];
  477. } else if (in_array($model, $this->valid_text_models)) {
  478. // 火山引擎模型
  479. $post_data['response_format'] = ['type' => 'json_object'];
  480. }
  481. }
  482. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  483. if ($script_id > 0) {
  484. $uid = Site::getUid();
  485. // 创建新的生成任务
  486. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  487. 'uid' => $uid,
  488. 'script_id' => $script_id,
  489. 'sequence' => $sequence,
  490. 'status' => 'processing',
  491. 'prompt' => getProp($data, 'prompt', ''),
  492. 'started_at' => date('Y-m-d H:i:s'),
  493. 'created_at' => date('Y-m-d H:i:s'),
  494. 'updated_at' => date('Y-m-d H:i:s')
  495. ]);
  496. }
  497. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  498. try {
  499. $aiResult = null;
  500. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  501. // DeepSeek 官方模型使用现有的 chatOnly 方法
  502. $result = $this->chatOnly($post_data);
  503. // 记录实际使用的模型
  504. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  505. $aiResult = [
  506. 'content' => $result['fullContent'],
  507. 'reasoning_content' => $result['fullReasoningContent'],
  508. 'usage' => $result['usage'],
  509. 'model' => $model,
  510. 'finish_reason' => 'stop'
  511. ];
  512. } else if (in_array($model, $this->gpt_text_models)) {
  513. // GPT 模型使用现有的 gpt54ChatOnly 方法
  514. $result = $this->gpt54ChatOnly($post_data);
  515. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  516. $aiResult = [
  517. 'content' => $result['fullContent'],
  518. 'reasoning_content' => '',
  519. 'usage' => $result['usage'],
  520. 'model' => $model,
  521. 'finish_reason' => 'stop'
  522. ];
  523. } else if (in_array($model, $this->valid_text_models)) {
  524. // 火山引擎支持的模型使用火山引擎 API(非流式)
  525. $post_data['stream'] = false;
  526. $result = $this->volcEngineChatCompletion($post_data);
  527. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  528. 'requested_model' => $model,
  529. 'result_keys' => array_keys($result),
  530. 'has_fullContent' => isset($result['fullContent']),
  531. 'has_content' => isset($result['content'])
  532. ]);
  533. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  534. $aiResult = [
  535. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  536. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  537. 'usage' => $result['usage'] ?? [],
  538. 'model' => $model,
  539. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  540. ];
  541. } else {
  542. Utils::throwError('20003:不支持的模型: ' . $model);
  543. }
  544. } catch (\Exception $e) {
  545. // 生成失败,更新任务状态
  546. if ($generateTaskId) {
  547. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  548. 'status' => 'failed',
  549. 'error_message' => $e->getMessage(),
  550. 'completed_at' => date('Y-m-d H:i:s'),
  551. 'updated_at' => date('Y-m-d H:i:s')
  552. ]);
  553. }
  554. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  555. }
  556. // 生成成功,更新任务状态
  557. if ($generateTaskId && $aiResult) {
  558. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  559. 'status' => 'success',
  560. 'result' => getProp($aiResult, 'content', ''),
  561. 'completed_at' => date('Y-m-d H:i:s'),
  562. 'updated_at' => date('Y-m-d H:i:s')
  563. ]);
  564. $aiResult['generate_task_id'] = $generateTaskId;
  565. }
  566. // 新增: 如果提供了script_id,保存对话记录
  567. if ($script_id > 0 && $aiResult) {
  568. try {
  569. $uid = Site::getUid();
  570. $now = now();
  571. // 获取用户原始的prompt(不包含剧本内容)
  572. $originalPrompt = getProp($data, 'prompt', '');
  573. $recordsToInsert = [
  574. [
  575. 'uid' => $uid,
  576. 'script_id' => $script_id,
  577. 'sequence' => $sequence,
  578. 'role' => 'user',
  579. 'content' => $originalPrompt,
  580. 'created_at' => $now,
  581. 'updated_at' => $now,
  582. ],
  583. [
  584. 'uid' => $uid,
  585. 'script_id' => $script_id,
  586. 'sequence' => $sequence,
  587. 'role' => 'assistant',
  588. 'content' => $aiResult['content'],
  589. 'created_at' => $now,
  590. 'updated_at' => $now,
  591. ]
  592. ];
  593. DB::table('mp_script_records')->insert($recordsToInsert);
  594. // 获取刚插入的记录ID(假设按插入顺序返回)
  595. $insertedRecords = DB::table('mp_script_records')
  596. ->where('uid', $uid)
  597. ->where('script_id', $script_id)
  598. ->where('sequence', $sequence)
  599. ->orderBy('id', 'desc')
  600. ->limit(2)
  601. ->get()
  602. ->map(function ($record) {
  603. return [
  604. 'rid' => $record->id,
  605. 'script_id' => $record->script_id,
  606. 'sequence' => $record->sequence,
  607. 'role' => $record->role,
  608. 'content' => $record->content,
  609. 'created_at' => $record->created_at,
  610. ];
  611. })
  612. ->reverse()
  613. ->values()
  614. ->toArray();
  615. // 将记录信息添加到返回结果中
  616. $aiResult['records'] = $insertedRecords;
  617. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  618. } catch (\Exception $e) {
  619. // 记录错误但不影响主流程
  620. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  621. }
  622. }
  623. return $aiResult;
  624. }
  625. /**
  626. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  627. *
  628. * @param array $data
  629. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  630. */
  631. public function getScriptGenerateTasks($data) {
  632. $uid = Site::getUid();
  633. return DB::table('mp_script_generate_tasks as t')
  634. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  635. ->where('t.uid', $uid)
  636. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  637. ->orderByDesc('t.id')
  638. ->paginate(15);
  639. }
  640. public function saveScriptChatHistory($data) {
  641. $uid = Site::getUid();
  642. $rid = getProp($data, 'rid');
  643. $script_id = getProp($data, 'script_id');
  644. $sequence = getProp($data, 'sequence', 0);
  645. $content = getProp($data, 'content');
  646. if (!$rid) {
  647. Utils::throwError('20003:请选择对话记录ID');
  648. }
  649. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  650. if (!$record) {
  651. Utils::throwError('20003:对话记录不存在');
  652. }
  653. if (!$script_id) {
  654. Utils::throwError('20003:请选择剧本');
  655. }
  656. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  657. if (!$script) {
  658. Utils::throwError('20003:剧本不存在');
  659. }
  660. // 批量插入数据
  661. return DB::table('mp_script_records')->where('id', $rid)->update([
  662. 'content' => $content,
  663. 'updated_at' => date('Y-m-d H:i:s')
  664. ]);
  665. }
  666. /**
  667. * 获取剧本的历史对话记录
  668. *
  669. * @param array $data 请求参数
  670. * @return array 返回历史记录数组
  671. */
  672. public function getScriptChatHistory($data) {
  673. $uid = Site::getUid();
  674. $script_id = getProp($data, 'script_id');
  675. $rid = getProp($data, 'rid');
  676. $sequence = getProp($data, 'sequence', null);
  677. if (!$script_id) {
  678. Utils::throwError('20003:请提供剧本ID');
  679. }
  680. // 验证剧本是否存在
  681. $script = DB::table('mp_scripts')
  682. ->where('id', $script_id)
  683. ->where('is_deleted', 0)
  684. ->first();
  685. if (!$script) {
  686. Utils::throwError('20003:剧本不存在');
  687. }
  688. // 构建查询
  689. $query = DB::table('mp_script_records')
  690. ->where('script_id', $script_id);
  691. // ->where('uid', $uid);
  692. // 如果提供了 sequence,则过滤指定剧集
  693. if ($sequence !== null) {
  694. $query->where('sequence', $sequence);
  695. }
  696. // 记录ID筛选
  697. if ($rid) {
  698. $query->where('id', $rid);
  699. }
  700. // 查询记录并按 id 正序排序
  701. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  702. ->orderBy('created_at', 'asc')
  703. ->orderBy('id', 'asc')
  704. ->get()
  705. ->map(function ($record) {
  706. return [
  707. 'rid' => $record->id,
  708. 'script_id' => $record->script_id,
  709. 'sequence' => $record->sequence,
  710. 'role' => $record->role,
  711. 'content' => $record->content,
  712. 'products' => $record->products ? json_decode($record->products) : [],
  713. 'created_at' => $record->created_at,
  714. ];
  715. })
  716. ->toArray();
  717. return $records;
  718. }
  719. /**
  720. * 处理图片转换为base64
  721. *
  722. * @param mixed $image 图片文件对象或文件路径
  723. * @return string|null base64编码的图片数据
  724. */
  725. private function processImageToBase64($image) {
  726. try {
  727. // 获取文件路径
  728. if (is_string($image)) {
  729. $filePath = $image;
  730. } else {
  731. // Laravel UploadedFile 对象
  732. $filePath = $image->getRealPath();
  733. }
  734. if (!file_exists($filePath)) {
  735. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  736. return null;
  737. }
  738. // 验证是否为图片文件
  739. $imageInfo = @getimagesize($filePath);
  740. if ($imageInfo === false) {
  741. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  742. return null;
  743. }
  744. // 读取图片并转换为base64
  745. $imageData = file_get_contents($filePath);
  746. $base64Image = base64_encode($imageData);
  747. dLog('deepseek')->info('图片转换成功', [
  748. 'size' => strlen($imageData),
  749. 'type' => $imageInfo['mime']
  750. ]);
  751. return $base64Image;
  752. } catch (\Exception $e) {
  753. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  754. return null;
  755. }
  756. }
  757. private function getArtStylePromptMappings($art_style='')
  758. {
  759. $arr = [
  760. '唯美真人风格' => [
  761. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  762. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  763. ],
  764. '真人古风风格' => [
  765. 'aliases' => ['真人古风风格', '真人古风'],
  766. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  767. ],
  768. '日系动漫风格' => [
  769. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  770. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  771. ],
  772. '国漫风格' => [
  773. 'aliases' => ['国漫风格', '国漫'],
  774. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  775. ],
  776. 'Q版卡通风格' => [
  777. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  778. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  779. ],
  780. '简约扁平风格' => [
  781. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  782. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  783. ],
  784. '武侠风格' => [
  785. 'aliases' => ['武侠风格', '武侠'],
  786. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  787. ],
  788. '古风仙侠风格' => [
  789. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  790. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  791. ],
  792. '新中式水墨风格' => [
  793. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  794. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  795. ],
  796. '写实插画风格' => [
  797. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  798. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  799. ],
  800. '3D卡通风格' => [
  801. 'aliases' => ['3D卡通风格', '3D卡通'],
  802. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  803. ],
  804. '条漫风格' => [
  805. 'aliases' => ['条漫风格', '条漫'],
  806. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  807. ],
  808. '赛博朋克风格' => [
  809. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  810. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  811. ],
  812. '暗黑悬疑风格' => [
  813. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  814. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  815. ],
  816. '治愈清新风格' => [
  817. 'aliases' => ['治愈清新风格', '治愈清新'],
  818. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  819. ],
  820. '3D真人风格' => [
  821. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  822. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  823. ],
  824. ];
  825. if($art_style) {
  826. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  827. }
  828. return $arr;
  829. $arr = [
  830. '唯美真人风格' => [
  831. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  832. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  833. 2. 色彩色调
  834. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  835. 3. 画质精度
  836. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  837. 4. 画面观感
  838. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  839. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  840. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  841. ],
  842. '真人古风风格' => [
  843. 'aliases' => ['真人古风风格', '真人古风'],
  844. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  845. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  846. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  847. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  848. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  849. ],
  850. '日系动漫风格' => [
  851. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  852. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  853. 正向提示词(中文)
  854. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  855. 必须遵守规则
  856. • 全程保持日系动漫风格,不混入其他画风
  857. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  858. • 画面适配所选画面比例,构图居中,主体突出
  859. • 线条干净、色彩统一,不杂乱、不突兀
  860. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  861. ],
  862. '国漫风格' => [
  863. 'aliases' => ['国漫风格', '国漫'],
  864. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  865. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  866. 必须遵守规则
  867. • 严格保持国漫画风,不串风格、不混画风
  868. • 角色形象统一,不随意改变五官、身材、服饰
  869. • 画面构图稳定,适合漫剧叙事展示
  870. • 色调统一,不出现脏色、杂色
  871. 禁止/避免词汇
  872. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  873. ],
  874. 'Q版卡通风格' => [
  875. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  876. 'prompt' => "风格说明
  877. 头大身小,造型可爱圆润,简约干净
  878. 正向提示词(中文)
  879. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  880. 必须遵守规则
  881. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  882. • 角色造型统一,表情可爱,不诡异
  883. • 画面简洁清爽,无多余复杂元素
  884. • 色彩明亮柔和,不刺眼
  885. 禁止/避免词汇
  886. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  887. ],
  888. '简约扁平风格' => [
  889. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  890. 'prompt' => "风格说明
  891. 色块简洁、无复杂渐变,现代极简风
  892. 正向提示词(中文)
  893. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  894. 必须遵守规则
  895. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  896. • 构图简洁,主体突出,无多余装饰
  897. • 色彩统一、干净,不杂乱
  898. 禁止/避免词汇
  899. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  900. ],
  901. '武侠风格' => [
  902. 'aliases' => ['武侠风格', '武侠'],
  903. 'prompt' => "风格说明
  904. 江湖气息,线条硬朗,动作感强
  905. 正向提示词(中文)
  906. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  907. 必须遵守规则
  908. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  909. • 角色形象、服饰、身材比例统一
  910. • 画面动作自然,不扭曲、不畸形
  911. 禁止/避免词汇
  912. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  913. ],
  914. '古风仙侠风格' => [
  915. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  916. 'prompt' => "风格说明
  917. 飘逸汉服、云雾仙气、唯美空灵
  918. 正向提示词(中文)
  919. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  920. 必须遵守规则
  921. • 保持古风仙侠统一画风,不混入现代、科幻元素
  922. • 角色服饰、发型、形象前后一致
  923. • 场景仙气飘逸,色调清雅统一
  924. • 画面唯美柔和,不阴暗、不诡异
  925. 禁止/避免词汇
  926. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  927. ],
  928. '新中式水墨风格' => [
  929. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  930. 'prompt' => "风格说明
  931. 淡墨渲染,毛笔笔触,留白意境
  932. 正向提示词(中文)
  933. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  934. 必须遵守规则
  935. • 严格保持水墨质感,不混入厚涂、写实、卡通
  936. • 色调淡雅统一,不浓艳杂乱
  937. • 画面干净有意境,不堆砌元素
  938. 禁止/避免词汇
  939. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  940. ],
  941. '写实插画风格' => [
  942. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  943. 'prompt' => "风格说明
  944. 接近真人比例,光影真实,质感细腻
  945. 正向提示词(中文)
  946. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  947. 必须遵守规则
  948. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  949. • 角色五官、身材、服饰高度统一
  950. • 画面清晰、光影自然、不扭曲
  951. 禁止/避免词汇
  952. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  953. ],
  954. '3D卡通风格' => [
  955. 'aliases' => ['3D卡通风格', '3D卡通'],
  956. 'prompt' => "风格说明
  957. 3D建模质感,柔和渲染,圆润可爱
  958. 正向提示词(中文)
  959. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  960. 必须遵守规则
  961. • 保持3D卡通统一质感,不出现2D杂乱线条
  962. • 角色模型、比例、形象前后一致
  963. • 画面干净,不模糊、不穿模
  964. 禁止/避免词汇
  965. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  966. ],
  967. '条漫风格' => [
  968. 'aliases' => ['条漫风格', '条漫'],
  969. 'prompt' => "风格说明
  970. 纵向分镜,上下滑动阅读,轻量化
  971. 正向提示词(中文)
  972. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  973. 必须遵守规则
  974. • 保持条漫纵向阅读逻辑,构图简洁
  975. • 画风统一,不混写实、3D、水墨
  976. • 画面干净,不杂乱
  977. 禁止/避免词汇
  978. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  979. ],
  980. '赛博朋克风格' => [
  981. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  982. 'prompt' => "风格说明
  983. 霓虹灯光、未来都市、暗色调、科技机械
  984. 正向提示词(中文)
  985. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  986. 必须遵守规则
  987. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  988. • 色调以暗调+霓虹为主,色彩统一
  989. • 画面科技感强,不杂乱
  990. 禁止/避免词汇
  991. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  992. ],
  993. '暗黑悬疑风格' => [
  994. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  995. 'prompt' => "风格说明
  996. 低饱和、冷色调、阴影重、神秘压抑
  997. 正向提示词(中文)
  998. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  999. 必须遵守规则
  1000. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1001. • 画面氛围压抑神秘,但不低俗、不血腥
  1002. • 角色形象统一,不崩坏
  1003. 禁止/避免词汇
  1004. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1005. ],
  1006. '治愈清新风格' => [
  1007. 'aliases' => ['治愈清新风格', '治愈清新'],
  1008. 'prompt' => "风格说明
  1009. 马卡龙色系、柔光、温暖干净
  1010. 正向提示词(中文)
  1011. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1012. 必须遵守规则
  1013. • 保持治愈清新统一色调,不阴暗、不诡异
  1014. • 画面柔和干净,无杂乱元素
  1015. • 角色形象柔和可爱,不狰狞
  1016. 禁止/避免词汇
  1017. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1018. ],
  1019. ];
  1020. return $arr;
  1021. }
  1022. public function getArtStylePromptByInput($inputArtStyle): string
  1023. {
  1024. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1025. if ($normalizedInput === '') {
  1026. return '';
  1027. }
  1028. return $this->getArtStylePromptMappings($normalizedInput);
  1029. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1030. // foreach ($mapping['aliases'] as $alias) {
  1031. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1032. // if ($normalizedAlias === '') {
  1033. // continue;
  1034. // }
  1035. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1036. // return $mapping['prompt'];
  1037. // }
  1038. // }
  1039. // }
  1040. return '';
  1041. }
  1042. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1043. $stylePrefixes = [
  1044. '唯美真人风格' => [
  1045. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1046. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1047. ],
  1048. '真人古风风格' => [
  1049. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1050. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1051. ],
  1052. '日系动漫风格' => [
  1053. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1054. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1055. ],
  1056. '国漫风格' => [
  1057. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1058. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1059. ],
  1060. 'Q版卡通风格' => [
  1061. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1062. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1063. ],
  1064. '简约扁平风格' => [
  1065. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1066. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1067. ],
  1068. '武侠风格' => [
  1069. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1070. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1071. ],
  1072. '古风仙侠风格' => [
  1073. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1074. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1075. ],
  1076. '新中式水墨风格' => [
  1077. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1078. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1079. ],
  1080. '写实插画风格' => [
  1081. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1082. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1083. ],
  1084. '3D卡通风格' => [
  1085. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1086. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1087. ],
  1088. '条漫风格' => [
  1089. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1090. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1091. ],
  1092. '赛博朋克风格' => [
  1093. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1094. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1095. ],
  1096. '暗黑悬疑风格' => [
  1097. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1098. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1099. ],
  1100. '治愈清新风格' => [
  1101. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1102. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1103. ]
  1104. ];
  1105. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1106. }
  1107. private function normalizeArtStyleInput($value): string
  1108. {
  1109. $value = trim((string)$value);
  1110. if ($value === '') {
  1111. return '';
  1112. }
  1113. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1114. return mb_strtolower($value, 'UTF-8');
  1115. }
  1116. private function replaceArtStyleSection(string $content, string $artStyle): string
  1117. {
  1118. if ($content === '' || $artStyle === '') {
  1119. return $content;
  1120. }
  1121. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1122. if (!preg_match($pattern, $content)) {
  1123. return $content;
  1124. }
  1125. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1126. }
  1127. /**
  1128. * DeepSeek流式输出处理方法
  1129. *
  1130. * @param array $post_data DeepSeek API请求参数
  1131. * @return \Generator 返回生成器,用于流式输出
  1132. */
  1133. private function deepSeekStreamResponse($post_data) {
  1134. // 设置最大输出tokens
  1135. $post_data['max_tokens'] = 300000;
  1136. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1137. $response = $client->post($this->url, [
  1138. 'json' => $post_data,
  1139. 'headers' => $this->headers,
  1140. 'stream' => true // 启用流式响应
  1141. ]);
  1142. $body = $response->getBody();
  1143. $fullContent = '';
  1144. $fullReasoningContent = '';
  1145. $usage = [];
  1146. $buffer = '';
  1147. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1148. // 逐行读取流式响应
  1149. while (!$body->eof()) {
  1150. $chunk = $body->read(1024); // 每次读取 1KB
  1151. $buffer .= $chunk;
  1152. // 按行分割
  1153. $lines = explode("\n", $buffer);
  1154. // 保留最后一个不完整的行
  1155. $buffer = array_pop($lines);
  1156. foreach ($lines as $line) {
  1157. $line = trim($line);
  1158. // 跳过空行
  1159. if (empty($line)) {
  1160. continue;
  1161. }
  1162. // 检查是否是 SSE 数据行
  1163. if (strpos($line, 'data: ') !== 0) {
  1164. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1165. continue;
  1166. }
  1167. $data = substr($line, 6); // 移除 "data: " 前缀
  1168. if ($data === '[DONE]') {
  1169. dLog('deepseek')->info('收到结束标记');
  1170. break 2; // 跳出两层循环
  1171. }
  1172. try {
  1173. $json = json_decode($data, true);
  1174. if (json_last_error() !== JSON_ERROR_NONE) {
  1175. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1176. continue;
  1177. }
  1178. if (isset($json['choices'][0]['delta'])) {
  1179. $delta = $json['choices'][0]['delta'];
  1180. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1181. if (isset($delta['reasoning_content'])) {
  1182. $fullReasoningContent .= $delta['reasoning_content'];
  1183. yield [
  1184. 'type' => 'reasoning',
  1185. 'content' => $delta['reasoning_content'],
  1186. 'full_reasoning' => $fullReasoningContent
  1187. ];
  1188. }
  1189. // 处理最终回答内容
  1190. if (isset($delta['content'])) {
  1191. $fullContent .= $delta['content'];
  1192. yield [
  1193. 'type' => 'content',
  1194. 'content' => $delta['content'],
  1195. ];
  1196. }
  1197. }
  1198. // 获取使用统计信息
  1199. if (isset($json['usage'])) {
  1200. $usage = $json['usage'];
  1201. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1202. }
  1203. } catch (\Exception $e) {
  1204. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1205. continue;
  1206. }
  1207. }
  1208. }
  1209. dLog('deepseek')->info('流式读取完成', [
  1210. 'content_length' => strlen($fullContent),
  1211. 'reasoning_length' => strlen($fullReasoningContent)
  1212. ]);
  1213. yield [
  1214. 'type' => 'done',
  1215. 'full_content' => $fullContent,
  1216. 'full_reasoning' => $fullReasoningContent,
  1217. 'usage' => $usage
  1218. ];
  1219. }
  1220. /**
  1221. * GPT 重试次数(env 可配置,默认 5 次)
  1222. */
  1223. private function gptRetryTimes()
  1224. {
  1225. return (int)env('GPT_RETRY_TIMES', 5);
  1226. }
  1227. /**
  1228. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1229. */
  1230. private function gptRetryInterval()
  1231. {
  1232. return (int)env('GPT_RETRY_INTERVAL', 10);
  1233. }
  1234. /**
  1235. * 判断 GPT 请求异常是否可重试
  1236. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1237. */
  1238. private function isGptRetryableException(\Exception $e)
  1239. {
  1240. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1241. return false;
  1242. }
  1243. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1244. $status = $e->getResponse()->getStatusCode();
  1245. return $status >= 500 || $status == 429;
  1246. }
  1247. return true;
  1248. }
  1249. /**
  1250. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1251. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1252. */
  1253. private function checkGptServiceAvailable()
  1254. {
  1255. $apiKey = env('GPT_54_API_KEY');
  1256. if (empty($apiKey)) {
  1257. return false;
  1258. }
  1259. try {
  1260. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1261. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1262. 'headers' => [
  1263. 'Authorization' => 'Bearer ' . $apiKey,
  1264. 'Content-Type' => 'application/json'
  1265. ]
  1266. ]);
  1267. $status = $response->getStatusCode();
  1268. return $status < 500 && $status != 429;
  1269. } catch (\Exception $e) {
  1270. return false;
  1271. }
  1272. }
  1273. /**
  1274. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1275. * 全部失败抛出友好错误
  1276. */
  1277. private function ensureGptServiceAvailable()
  1278. {
  1279. $maxRetries = $this->gptRetryTimes();
  1280. $interval = $this->gptRetryInterval();
  1281. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1282. if ($this->checkGptServiceAvailable()) {
  1283. return;
  1284. }
  1285. if ($attempt < $maxRetries) {
  1286. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1287. 'retry' => $attempt + 1,
  1288. 'max_retries' => $maxRetries
  1289. ]);
  1290. sleep($interval);
  1291. }
  1292. }
  1293. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1294. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1295. 'max_retries' => $maxRetries,
  1296. 'interval' => $interval
  1297. ]);
  1298. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1299. }
  1300. /**
  1301. * GPT 流式输出处理方法
  1302. *
  1303. * @param array $post_data GPT API请求参数
  1304. * @return \Generator 返回生成器,用于流式输出
  1305. */
  1306. private function gpt54StreamResponse($post_data) {
  1307. $apiKey = env('GPT_54_API_KEY');
  1308. if (empty($apiKey)) {
  1309. Utils::throwError('20003:GPT API Key未配置');
  1310. }
  1311. // 先探活,服务不可用时自动重试
  1312. $this->ensureGptServiceAvailable();
  1313. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1314. $headers = [
  1315. 'Authorization' => 'Bearer ' . $apiKey,
  1316. 'Content-Type' => 'application/json'
  1317. ];
  1318. // 移除 thinking 参数,GPT-5.4 不支持
  1319. if (isset($post_data['thinking'])) {
  1320. unset($post_data['thinking']);
  1321. }
  1322. if (isset($post_data['reasoning_effort'])) {
  1323. unset($post_data['reasoning_effort']);
  1324. }
  1325. $post_data['max_completion_tokens'] = 100000;
  1326. $maxRetries = $this->gptRetryTimes();
  1327. $interval = $this->gptRetryInterval();
  1328. $attempt = 0;
  1329. while (true) {
  1330. $fullContent = '';
  1331. $usage = [];
  1332. $buffer = '';
  1333. try {
  1334. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1335. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1336. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1337. 'json' => $post_data,
  1338. 'headers' => $headers,
  1339. 'stream' => true // 启用流式响应
  1340. ]);
  1341. $body = $response->getBody();
  1342. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1343. // 逐行读取流式响应
  1344. while (!$body->eof()) {
  1345. $chunk = $body->read(1024); // 每次读取 1KB
  1346. $buffer .= $chunk;
  1347. // 按行分割
  1348. $lines = explode("\n", $buffer);
  1349. // 保留最后一个不完整的行
  1350. $buffer = array_pop($lines);
  1351. foreach ($lines as $line) {
  1352. $line = trim($line);
  1353. // 跳过空行
  1354. if (empty($line)) {
  1355. continue;
  1356. }
  1357. // 检查是否是 SSE 数据行
  1358. if (strpos($line, 'data: ') !== 0) {
  1359. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1360. continue;
  1361. }
  1362. $data = substr($line, 6); // 移除 "data: " 前缀
  1363. if ($data === '[DONE]') {
  1364. dLog('deepseek')->info('收到结束标记');
  1365. break 2; // 跳出 foreach 和流读取循环
  1366. }
  1367. try {
  1368. $json = json_decode($data, true);
  1369. if (json_last_error() !== JSON_ERROR_NONE) {
  1370. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1371. continue;
  1372. }
  1373. if (isset($json['choices'][0]['delta'])) {
  1374. $delta = $json['choices'][0]['delta'];
  1375. // 处理回答内容
  1376. if (isset($delta['content'])) {
  1377. $fullContent .= $delta['content'];
  1378. yield [
  1379. 'type' => 'content',
  1380. 'content' => $delta['content'],
  1381. ];
  1382. }
  1383. }
  1384. // 获取使用统计信息
  1385. if (isset($json['usage'])) {
  1386. $usage = $json['usage'];
  1387. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1388. }
  1389. } catch (\Exception $e) {
  1390. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1391. continue;
  1392. }
  1393. }
  1394. }
  1395. dLog('deepseek')->info('流式读取完成', [
  1396. 'content_length' => strlen($fullContent)
  1397. ]);
  1398. yield [
  1399. 'type' => 'done',
  1400. 'full_content' => $fullContent,
  1401. 'full_reasoning' => '',
  1402. 'usage' => $usage
  1403. ];
  1404. return;
  1405. } catch (\Exception $e) {
  1406. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1407. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1408. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1409. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1410. throw $e;
  1411. }
  1412. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1413. 'retry' => $attempt + 1,
  1414. 'max_retries' => $maxRetries,
  1415. 'error' => $e->getMessage()
  1416. ]);
  1417. sleep($interval);
  1418. $attempt++;
  1419. }
  1420. }
  1421. }
  1422. // 与推理模型对话
  1423. public function chatWithReasoner($data) {
  1424. $content = getProp($data, 'content');
  1425. $model = getProp($data, 'model', 'r1');
  1426. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1427. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1428. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1429. if ($model == 'r1') {
  1430. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1431. $thinkingMode = 'disabled';
  1432. } else {
  1433. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1434. $thinkingMode = 'disabled';
  1435. }
  1436. // 获取可选情感(根据音色可支持情感选)
  1437. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1438. $emotion_list = [];
  1439. foreach ($timbre_emotion as $emotion) {
  1440. $tmp = explode(',', $emotion);
  1441. $emotion_list = array_merge($emotion_list, $tmp);
  1442. }
  1443. $emotion_list = array_unique($emotion_list);
  1444. $emotion_str = implode('、', $emotion_list);
  1445. // // 获取可选情感
  1446. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1447. // $emotion_str = implode('、', $emotion_list);
  1448. // 是否启用情感
  1449. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1450. if ($enable_emotion) {
  1451. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1452. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1453. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1454. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1455. }else {
  1456. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1457. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1458. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1459. }
  1460. $messages = [
  1461. [
  1462. 'role' => 'system',
  1463. 'content' => $sys_content
  1464. ],
  1465. [
  1466. 'role' => 'user',
  1467. 'content' => $content
  1468. ]
  1469. ];
  1470. $post_data = [
  1471. 'model' => $model,
  1472. 'messages' => $messages,
  1473. // 'max_tokens' => 8192,
  1474. 'temperature' => 1,
  1475. 'frequency_penalty' => 0,
  1476. 'presence_penalty' => 0,
  1477. 'thinking' => ['type' => $thinkingMode],
  1478. 'response_format' => [
  1479. 'type' => 'text'
  1480. ],
  1481. 'stream' => false
  1482. ];
  1483. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1484. // 根据模型类型选择调用方法
  1485. $fullContent = '';
  1486. $usage = [];
  1487. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1488. // DeepSeek 官方模型使用 DeepSeek API
  1489. $chatResult = $this->chatOnly($post_data);
  1490. } else if (in_array($model, $this->gpt_text_models)) {
  1491. // GPT-5.4 模型使用 TokenRouter API
  1492. $chatResult = $this->gpt54ChatOnly($post_data);
  1493. } else {
  1494. // 其他模型使用火山引擎API
  1495. $chatResult = $this->volcEngineChatCompletion($post_data);
  1496. }
  1497. if (is_array($chatResult)) {
  1498. $fullContent = $chatResult['fullContent'];
  1499. $usage = $chatResult['usage'];
  1500. }
  1501. // 处理获取到的剧本数据
  1502. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1503. $result = [
  1504. 'origin_content' => $fullContent,
  1505. 'roles' => getProp($script_content, 'roles'),
  1506. 'words' => getProp($script_content, 'words'),
  1507. ];
  1508. return $result;
  1509. }
  1510. public function resetParagraphAudio($data) {
  1511. $bid = getProp($data, 'bid');
  1512. $cid = getProp($data, 'cid');
  1513. $version_id = getProp($data, 'version_id');
  1514. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1515. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1516. 'generate_status' => '待制作',
  1517. 'updated_at' => date('Y-m-d H:i:s')
  1518. ]);
  1519. }
  1520. public function saveParagraphAudio($data) {
  1521. $bid = getProp($data, 'bid');
  1522. $cid = getProp($data, 'cid');
  1523. $version_id = getProp($data, 'version_id');
  1524. $sequence = getProp($data, 'sequence');
  1525. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1526. // 获取所有情感
  1527. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1528. $emotion_list = array_flip($emotion_list);
  1529. // 获取音色支持情感
  1530. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1531. $timbre_emotion = explode(',', $timbre_emotion);
  1532. $emotion = getProp($data, 'emotion');
  1533. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1534. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1535. $list = [
  1536. 'bid' => $bid,
  1537. 'cid' => $cid,
  1538. 'version_id' => $version_id,
  1539. 'sequence' => $sequence,
  1540. 'role' => getProp($data, 'role'),
  1541. 'gender' => getProp($data, 'gender'),
  1542. 'text' => trim(getProp($data, 'text')),
  1543. 'emotion' => $emotion,
  1544. 'emotion_type' => $emotion_type,
  1545. 'voice_type' => getProp($data, 'voice_type'),
  1546. 'voice_name' => getProp($data, 'voice_name'),
  1547. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1548. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1549. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1550. 'pitch' => getProp($data, 'pitch', 0),
  1551. // 'paragraph_audio_url' => '',
  1552. 'generate_status' => '制作中',
  1553. 'error_msg' => '',
  1554. 'updated_at' => date('Y-m-d H:i:s')
  1555. ];
  1556. $continue = false;
  1557. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1558. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1559. $list['generate_status'] = '制作成功';
  1560. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1561. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1562. $continue = true;
  1563. }
  1564. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1565. if ($id) {
  1566. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1567. }else {
  1568. $list['created_at'] = date('Y-m-d H:i:s');
  1569. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1570. $boolen = $id ? true : false;
  1571. }
  1572. // 如果更新成功则加入查询队列
  1573. if ($boolen) {
  1574. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1575. Redis::sadd($redis_key, $id);
  1576. }
  1577. if ($boolen && !$continue) {
  1578. $boolen = false;
  1579. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1580. // 根据ID通过API通知合成音频
  1581. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1582. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1583. $response = $result->getBody()->getContents();
  1584. $response_arr = json_decode($response, true);
  1585. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1586. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1587. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1588. Utils::throwError('20003:通知火山生成段落音频失败');
  1589. }
  1590. $boolen = true;
  1591. }
  1592. return $boolen;
  1593. }
  1594. public function insertAudioEffect($data) {
  1595. $audio_id = getProp($data, 'audio_id');
  1596. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1597. $bid = getProp($chapter_audio, 'bid');
  1598. $version_id = getProp($chapter_audio, 'version_id');
  1599. $cid = getProp($chapter_audio, 'cid');
  1600. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1601. $audio_effect_json = getProp($data, 'audio_effect_json');
  1602. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1603. try {
  1604. DB::beginTransaction();
  1605. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1606. if (!$count) {
  1607. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1608. }else {
  1609. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1610. }
  1611. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1612. 'audio_effect_status' => '添加中',
  1613. 'audio_effect_json' => $audio_effect_json,
  1614. 'updated_at' => date('Y-m-d H:i:s')
  1615. ]);
  1616. if (!$boolen1) {
  1617. DB::rollBack();
  1618. Utils::throwError('20003:更新生成数据失败');
  1619. }
  1620. $id = DB::table('mp_audio_tasks')->insertGetId([
  1621. 'audio_id' => $audio_id,
  1622. 'generate_status' => '执行中',
  1623. 'generate_json' => json_encode([], 256),
  1624. 'bid' => $bid,
  1625. 'book_name' => getProp($chapter_audio, 'book_name'),
  1626. 'version_id' => $version_id,
  1627. 'version_name' => getProp($chapter_audio, 'version_name'),
  1628. 'cid' => $cid,
  1629. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1630. 'task_name' => $task_name,
  1631. 'created_at' => date('Y-m-d H:i:s'),
  1632. 'updated_at' => date('Y-m-d H:i:s')
  1633. ]);
  1634. if (!$id) {
  1635. DB::rollBack();
  1636. Utils::throwError('20003:创建任务失败');
  1637. }
  1638. }catch (\Exception $e) {
  1639. DB::rollBack();
  1640. Utils::throwError('20003:'.$e->getMessage());
  1641. }
  1642. DB::commit();
  1643. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1644. // 根据ID通过API通知合成音频
  1645. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1646. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1647. $response = $result->getBody()->getContents();
  1648. $response_arr = json_decode($response, true);
  1649. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1650. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1651. Log::info('通知火山插入音效失败: '.$error_msg);
  1652. Utils::throwError('20003:通知火山插入音效失败');
  1653. }
  1654. return true;
  1655. }
  1656. public function insertBgm($data) {
  1657. $audio_id = getProp($data, 'audio_id');
  1658. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1659. $bid = getProp($chapter_audio, 'bid');
  1660. $version_id = getProp($chapter_audio, 'version_id');
  1661. $cid = getProp($chapter_audio, 'cid');
  1662. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1663. $bgm_json = getProp($data, 'bgm_json');
  1664. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1665. if (!$bgm_json) {
  1666. $bgm_json = getProp($data, 'audio_effect_json');
  1667. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1668. }
  1669. try {
  1670. DB::beginTransaction();
  1671. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1672. if (!$count) {
  1673. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1674. }else {
  1675. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1676. }
  1677. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1678. 'bgm_status' => '添加中',
  1679. 'bgm_json' => $bgm_json,
  1680. 'updated_at' => date('Y-m-d H:i:s')
  1681. ]);
  1682. if (!$boolen1) {
  1683. DB::rollBack();
  1684. Utils::throwError('20003:更新生成数据失败');
  1685. }
  1686. $id = DB::table('mp_audio_tasks')->insertGetId([
  1687. 'audio_id' => $audio_id,
  1688. 'generate_status' => '执行中',
  1689. 'generate_json' => json_encode([], 256),
  1690. 'bid' => $bid,
  1691. 'book_name' => getProp($chapter_audio, 'book_name'),
  1692. 'version_id' => $version_id,
  1693. 'version_name' => getProp($chapter_audio, 'version_name'),
  1694. 'cid' => $cid,
  1695. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1696. 'task_name' => $task_name,
  1697. 'created_at' => date('Y-m-d H:i:s'),
  1698. 'updated_at' => date('Y-m-d H:i:s')
  1699. ]);
  1700. if (!$id) {
  1701. DB::rollBack();
  1702. Utils::throwError('20003:创建任务失败');
  1703. }
  1704. }catch (\Exception $e) {
  1705. DB::rollBack();
  1706. Utils::throwError('20003:'.$e->getMessage());
  1707. }
  1708. DB::commit();
  1709. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1710. // 根据ID通过API通知合成音频
  1711. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1712. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1713. $response = $result->getBody()->getContents();
  1714. $response_arr = json_decode($response, true);
  1715. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1716. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1717. Log::info('通知火山插入bgm失败: '.$error_msg);
  1718. Utils::throwError('20003:通知火山插入bgm失败');
  1719. }
  1720. return true;
  1721. }
  1722. public function getParagraphAudios($data) {
  1723. $bid = getProp($data, 'bid');
  1724. $cid = getProp($data, 'cid');
  1725. $version_id = getProp($data, 'version_id');
  1726. $sequence = getProp($data, 'sequence');
  1727. // 获取已生成的音频
  1728. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1729. if ($sequence) $query->where('sequence', $sequence);
  1730. $paragraph_audios = $query->orderBy('sequence')->get();
  1731. $result = [];
  1732. foreach($paragraph_audios as $item) {
  1733. $result[] = [
  1734. 'sequence' => getProp($item, 'sequence'),
  1735. 'role' => getProp($item, 'role'),
  1736. 'gender' => getProp($item, 'gender'),
  1737. 'text' => trim(getProp($item, 'text')),
  1738. 'emotion' => getProp($item, 'emotion'),
  1739. 'emotion_type' => getProp($item, 'emotion_type'),
  1740. 'voice_type' => getProp($item, 'voice_type'),
  1741. 'voice_name' => getProp($item, 'voice_name'),
  1742. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1743. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1744. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1745. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1746. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1747. ];
  1748. }
  1749. return $result;
  1750. }
  1751. // 新增合成任务
  1752. public function addGenerateTask($data) {
  1753. $bid = getProp($data, 'bid');
  1754. $cid = getProp($data, 'cid');
  1755. $version_id = getProp($data, 'version_id');
  1756. $generate_json = getProp($data, 'generate_json');
  1757. // 获取已生成的音频
  1758. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1759. $paragraph_list = [];
  1760. foreach($paragraph_audios as $item) {
  1761. $paragraph_list[getProp($item, 'sequence')] = [
  1762. 'role' => getProp($item, 'role'),
  1763. 'gender' => getProp($item, 'gender'),
  1764. 'text' => trim(getProp($item, 'text')),
  1765. 'emotion' => getProp($item, 'emotion'),
  1766. 'emotion_type' => getProp($item, 'emotion_type'),
  1767. 'voice_type' => getProp($item, 'voice_type'),
  1768. 'voice_name' => getProp($item, 'voice_name'),
  1769. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1770. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1771. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1772. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1773. ];
  1774. }
  1775. // 更新角色-音色信息
  1776. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1777. $existed_role_info = json_decode($existed_role_info, true);
  1778. if (!$existed_role_info) $existed_role_info = [];
  1779. // 获取情感信息
  1780. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1781. $emotion_list = array_flip($emotion_list);
  1782. // 获取音色对应情感组
  1783. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1784. $timbre_emotion_list = [];
  1785. foreach($timbre_emotions as $item) {
  1786. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1787. }
  1788. // 构造生成音频的json
  1789. $words = json_decode($generate_json, true);
  1790. // 最终合成前的参数组
  1791. $mp_chapter_paragraph_audios = [];
  1792. $sequence = 1;
  1793. $complete_paragraph_sequences = [];
  1794. foreach($words as &$word) {
  1795. 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:参数格式有误');
  1796. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1797. $role = getProp($word, 'role');
  1798. $word['gender'] = (int)$word['gender'];
  1799. // 判断音色对应情感是否支持,不支持则调整为中性
  1800. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1801. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1802. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1803. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1804. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1805. }else {
  1806. $word['emotion'] = '中性';
  1807. $word['emotion_type'] = 'neutral';
  1808. }
  1809. $existed_role_info[$role] = [
  1810. 'timbre_type' => $word['voice_type'],
  1811. 'timbre_name' => $word['voice_name'],
  1812. 'emotion' => $word['emotion'],
  1813. 'emotion_type' => $word['emotion_type'],
  1814. 'speed_ratio' => $word['speed_ratio'],
  1815. 'loudness_ratio'=> $word['loudness_ratio'],
  1816. 'emotion_scale' => $word['emotion_scale'],
  1817. 'pitch' => $word['pitch']
  1818. ];
  1819. $word['paragraph_audio_url'] = '';
  1820. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1821. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1822. // 如果音频存在并且参数都未改变则使用已生成的音频
  1823. if (getProp($paragraph, 'paragraph_audio_url')) {
  1824. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1825. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1826. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1827. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1828. // {
  1829. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1830. // }
  1831. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1832. }
  1833. $tmp = $word;
  1834. // 组装章节分句音频数据
  1835. // $tmp['sequence'] = getProp($word, 'sequence');
  1836. // $tmp['text'] = getProp($word, 'text');
  1837. // $tmp['emotion'] = getProp($word, 'emotion');
  1838. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1839. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1840. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1841. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1842. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1843. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1844. $tmp['bid'] = $bid;
  1845. $tmp['version_id'] = $version_id;
  1846. $tmp['cid'] = $cid;
  1847. $tmp['sequence'] = $sequence;
  1848. $tmp['created_at'] = date('Y-m-d H:i:s');
  1849. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1850. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1851. $mp_chapter_paragraph_audios[] = $tmp;
  1852. $complete_paragraph_sequences[] = $sequence;
  1853. $sequence++;
  1854. }
  1855. $generate_json = json_encode($words, 256);
  1856. // 判断是否有未生成字幕的段落
  1857. $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();
  1858. if ($no_subtitle_sequences) {
  1859. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1860. }
  1861. try {
  1862. DB::beginTransaction();
  1863. $role_info = json_encode($existed_role_info, 256);
  1864. $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')]);
  1865. if (!$boolen) {
  1866. DB::rollBack();
  1867. Utils::throwError('20003:更新角色信息失败');
  1868. }
  1869. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1870. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1871. if (!$count) {
  1872. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1873. }else {
  1874. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1875. }
  1876. $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')]);
  1877. if (!$boolen1) {
  1878. DB::rollBack();
  1879. Utils::throwError('20003:更新生成数据失败');
  1880. }
  1881. $id = DB::table('mp_audio_tasks')->insertGetId([
  1882. 'audio_id' => getProp($chapter_audio, 'id'),
  1883. 'generate_status' => '执行中',
  1884. 'generate_json' => $generate_json,
  1885. 'bid' => $bid,
  1886. 'book_name' => getProp($chapter_audio, 'book_name'),
  1887. 'version_id' => $version_id,
  1888. 'version_name' => getProp($chapter_audio, 'version_name'),
  1889. 'cid' => $cid,
  1890. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1891. 'task_name' => $task_name,
  1892. 'created_at' => date('Y-m-d H:i:s'),
  1893. 'updated_at' => date('Y-m-d H:i:s')
  1894. ]);
  1895. if (!$id) {
  1896. DB::rollBack();
  1897. Utils::throwError('20003:创建任务失败');
  1898. }
  1899. // 删除不在段落序号范围内的其他数据
  1900. if ($complete_paragraph_sequences) {
  1901. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1902. }
  1903. // // 删除章节分句音频数据并重新插入
  1904. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1905. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1906. // if (!$boolen3) {
  1907. // DB::rollBack();
  1908. // Utils::throwError('20003:更新章节分句音频失败');
  1909. // }
  1910. } catch (\Exception $e) {
  1911. DB::rollBack();
  1912. Utils::throwError('20003:'.$e->getMessage());
  1913. }
  1914. DB::commit();
  1915. // 通知火山生成音频
  1916. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1917. // 根据ID通过API通知合成音频
  1918. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1919. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1920. $response = $result->getBody()->getContents();
  1921. $response_arr = json_decode($response, true);
  1922. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1923. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1924. Log::info('通知火山生成音频失败: '.$error_msg);
  1925. Utils::throwError('20003:通知火山生成音频失败');
  1926. }
  1927. return true;
  1928. }
  1929. public function timbreList($data) {
  1930. $gender = getProp($data, 'gender');
  1931. $timbre_name = getProp($data, 'voice_name');
  1932. $category_id = getProp($data, 'category_id');
  1933. $age_stage = getProp($data, 'age_stage');
  1934. $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');
  1935. if ($gender) {
  1936. $query->where('gender', $gender);
  1937. }
  1938. if ($timbre_name) {
  1939. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1940. }
  1941. if ($category_id) {
  1942. $query->where(function ($query) use ($category_id) {
  1943. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1944. });
  1945. }
  1946. if ($age_stage) {
  1947. $query->where('age_stage', $age_stage);
  1948. }
  1949. $list = $query->get()->map(function ($value) {
  1950. $value = (array)$value;
  1951. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1952. return $value;
  1953. })->toArray();
  1954. return $list;
  1955. }
  1956. // 生成火山临时token
  1957. public function setStsToken() {
  1958. // ************* 配置参数 *************
  1959. $method = 'GET';
  1960. $service = 'sts';
  1961. $host = 'open.volcengineapi.com';
  1962. $region = env('VOLC_REGION');
  1963. $endpoint = 'https://open.volcengineapi.com';
  1964. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1965. $access_key = env('VOLC_AK');
  1966. $secret_key = env('VOLC_SK');
  1967. // 获取缓存中的token,如果没有则请求接口
  1968. $token = Redis::get('volc_sts_token');
  1969. if (!$token) {
  1970. // 查询参数
  1971. $query_parameters = [
  1972. 'Action' => 'AssumeRole',
  1973. 'RoleSessionName' => 'user@zw',
  1974. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1975. 'Version' => '2018-01-01'
  1976. ];
  1977. // 生成URL编码的查询字符串
  1978. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1979. // 获取签名头信息
  1980. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1981. // 构建完整URL
  1982. $request_url = $endpoint . '?' . $request_parameters;
  1983. $client = new Client(['verify' => false]);
  1984. $response = $client->get($request_url, ['headers' => $headers]);
  1985. $response_arr = json_decode($response->getBody()->getContents(), true);
  1986. $result = [
  1987. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1988. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1989. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1990. 'Region' => env('VOLC_REGION'),
  1991. 'Endpoint' => env('VOLC_END_POINT'),
  1992. 'Bucket' => env('VOLC_BUCKET'),
  1993. ];
  1994. // 缓存token
  1995. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1996. return $result;
  1997. } else {
  1998. return json_decode($token, true);
  1999. }
  2000. // $response = $response['Response'];
  2001. // $access_key = $response['Credentials']['AccessKeyId'];
  2002. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2003. // $security_token = $response['Credentials']['SecurityToken'];
  2004. // $expiration = $response['Credentials']['Expiration'];
  2005. // dd($response_arr);
  2006. }
  2007. public function emotionGroups($data) {
  2008. $id = getProp($data, 'group_id');
  2009. $group_name = getProp($data, 'group_name');
  2010. $voice_type = getProp($data, 'voice_type');
  2011. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2012. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2013. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2014. if ($group_name) {
  2015. $query->where('group_name', 'like', "%{$group_name}%");
  2016. }
  2017. if ($id) {
  2018. $query->where('id', $id);
  2019. }
  2020. if ($voice_type) {
  2021. $query->where('voice_type', $voice_type);
  2022. }
  2023. return $query->orderBy('id')->get()->map(function ($value) {
  2024. return (array)$value;
  2025. })->toArray();
  2026. }
  2027. private function sign($key, $msg) {
  2028. return hash_hmac('sha256', $msg, $key, true);
  2029. }
  2030. // 生成签名密钥
  2031. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2032. $kDate = $this->sign($key, $dateStamp);
  2033. $kRegion = $this->sign($kDate, $regionName);
  2034. $kService = $this->sign($kRegion, $serviceName);
  2035. $kSigning = $this->sign($kService, 'request');
  2036. return $kSigning;
  2037. }
  2038. // 获取签名头信息
  2039. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2040. $contenttype = 'application/x-www-form-urlencoded';
  2041. $accept = 'application/json';
  2042. // 获取当前UTC时间
  2043. $t = new DateTime('now', new DateTimeZone('UTC'));
  2044. $xdate = $t->format('Ymd\THis\Z');
  2045. $datestamp = $t->format('Ymd');
  2046. // 1. 拼接规范请求串
  2047. $canonical_uri = '/';
  2048. $canonical_querystring = $request_parameters;
  2049. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2050. $signed_headers = 'content-type;host;x-date';
  2051. // 空请求体的SHA256哈希
  2052. $payload_hash = hash('sha256', '');
  2053. $canonical_request = implode("\n", [
  2054. $method,
  2055. $canonical_uri,
  2056. $canonical_querystring,
  2057. $canonical_headers,
  2058. $signed_headers,
  2059. $payload_hash
  2060. ]);
  2061. // 2. 拼接待签名字符串
  2062. $algorithm = 'HMAC-SHA256';
  2063. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2064. $hashed_canonical_request = hash('sha256', $canonical_request);
  2065. $string_to_sign = implode("\n", [
  2066. $algorithm,
  2067. $xdate,
  2068. $credential_scope,
  2069. $hashed_canonical_request
  2070. ]);
  2071. // 3. 计算签名
  2072. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2073. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2074. // 4. 添加签名到请求头
  2075. $authorization_header = sprintf(
  2076. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2077. $algorithm,
  2078. $access_key,
  2079. $credential_scope,
  2080. $signed_headers,
  2081. $signature
  2082. );
  2083. return [
  2084. 'Accept' => $accept,
  2085. 'Content-Type' => $contenttype,
  2086. 'X-Date' => $xdate,
  2087. 'Authorization' => $authorization_header
  2088. ];
  2089. }
  2090. // 文字合成语音(火山引擎)
  2091. public function tts($data) {
  2092. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2093. $headers = [
  2094. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2095. 'Content-Type' => 'application/json; charset=UTF-8'
  2096. ];
  2097. $post_data = [
  2098. 'app' => [
  2099. 'appid' => env('VOLC_APPID'),
  2100. 'token' => env('VOLC_TOKEN'),
  2101. 'cluster' => 'volcano_tts'
  2102. ],
  2103. 'user' => [
  2104. 'uid' => 'mp_audio'
  2105. ],
  2106. // 'audio' => [
  2107. // 'voice_type' =>
  2108. // ],
  2109. ];
  2110. }
  2111. public function scriptList($data) {
  2112. $uid = Site::getUid();
  2113. $script_id = getProp($data, 'script_id');
  2114. $script_name = getProp($data, 'script_name');
  2115. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2116. if ($script_id) {
  2117. $query->where('id', $script_id);
  2118. }
  2119. if ($script_name) {
  2120. $query->where('script_name', 'like', "%{$script_name}%");
  2121. }
  2122. return $query->orderBy('created_at', 'desc')->paginate(12);
  2123. }
  2124. public function scripts($data) {
  2125. $uid = Site::getUid();
  2126. $script_id = getProp($data, 'script_id');
  2127. $script_name = getProp($data, 'script_name');
  2128. $is_products = getProp($data, 'is_products');
  2129. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2130. if ($script_id) {
  2131. $query->where('id', $script_id);
  2132. }
  2133. if ($is_products !== '') {
  2134. $query->where('is_products', $is_products);
  2135. }
  2136. if ($script_name) {
  2137. $query->where('script_name', 'like', "%{$script_name}%");
  2138. }
  2139. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2140. return (array)$value;
  2141. })->toArray();
  2142. }
  2143. public function scriptInfo($data) {
  2144. $uid = Site::getUid();
  2145. $script_id = getProp($data, 'script_id');
  2146. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2147. // ->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();
  2148. ->selectRaw('id as script_id, script_name')->first();
  2149. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2150. $script = (array)$script;
  2151. // 获取分集组信息
  2152. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2153. ->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')
  2154. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2155. $value = (array)$value;
  2156. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2157. return (array)$value;
  2158. })->toArray();
  2159. $script['group'] = $groups;
  2160. return $script;
  2161. }
  2162. public function createScript($data) {
  2163. $script_name = getProp($data, 'script_name');
  2164. $uid = Site::getUid(); // 获取当前用户ID
  2165. $cpid = Site::getCpid(); // 获取当前公司组ID
  2166. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2167. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2168. $script_name .= '_'.date('YmdHis');
  2169. }
  2170. return DB::table('mp_scripts')->insertGetId([
  2171. 'script_name' => $script_name,
  2172. 'user_id' => $uid,
  2173. 'cpid' => $cpid,
  2174. 'created_at' => date('Y-m-d H:i:s'),
  2175. 'updated_at' => date('Y-m-d H:i:s')
  2176. ]);
  2177. }
  2178. public function editScript($data) {
  2179. $script_id = getProp($data, 'script_id');
  2180. $script_name = getProp($data, 'script_name');
  2181. $uid = Site::getUid(); // 获取当前用户ID
  2182. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2183. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2184. if ($id && (int)$id !== (int)$script_id) {
  2185. $script_name .= '_'.date('YmdHis');
  2186. }
  2187. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2188. 'script_name' => $script_name,
  2189. 'updated_at' => date('Y-m-d H:i:s')
  2190. ]);
  2191. }
  2192. public function delScript($data) {
  2193. $script_id = getProp($data, 'script_id');
  2194. $uid = Site::getUid(); // 获取当前用户ID
  2195. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2196. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2197. 'is_deleted' => 1,
  2198. 'updated_at' => date('Y-m-d H:i:s')
  2199. ]);
  2200. }
  2201. public function createEpisode($data) {
  2202. $script_id = getProp($data, 'script_id');
  2203. $group_name = getProp($data, 'group_name');
  2204. $remark = getProp($data, 'remark');
  2205. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2206. $uid = Site::getUid(); // 获取当前用户ID
  2207. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2208. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2209. $group_name .= '_'.date('YmdHis');
  2210. }
  2211. return DB::table('mp_script_episode_group')->insertGetId([
  2212. 'script_id' => $script_id,
  2213. 'group_name' => $group_name,
  2214. 'user_id' => $uid,
  2215. 'remark' => $remark,
  2216. 'created_at' => date('Y-m-d H:i:s'),
  2217. 'updated_at' => date('Y-m-d H:i:s')
  2218. ]);
  2219. }
  2220. public function editEpisode($data) {
  2221. $group_id = getProp($data, 'group_id');
  2222. $start_episode_number = getProp($data, 'start_episode_number');
  2223. $end_episode_number = getProp($data, 'end_episode_number');
  2224. $group_name = getProp($data, 'group_name');
  2225. $uid = Site::getUid(); // 获取当前用户ID
  2226. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2227. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2228. if ($id && (int)$id !== (int)$group_id) {
  2229. $group_name .= '_'.date('YmdHis');
  2230. }
  2231. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2232. 'group_name' => $group_name,
  2233. 'start_episode_number' => $start_episode_number,
  2234. 'end_episode_number' => $end_episode_number,
  2235. 'updated_at' => date('Y-m-d H:i:s')
  2236. ]);
  2237. }
  2238. public function delEpisode($data) {
  2239. $group_id = getProp($data, 'group_id');
  2240. $uid = Site::getUid(); // 获取当前用户ID
  2241. if (!$group_id) Utils::throwError('20003:请选择分集');
  2242. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2243. 'is_deleted' => 1,
  2244. 'updated_at' => date('Y-m-d H:i:s')
  2245. ]);
  2246. }
  2247. /**
  2248. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2249. *
  2250. * @param array $data 包含以下参数:
  2251. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2252. * - question: 用户问题(可选)
  2253. * - model: 使用的模型(r1 或 v3,默认 v3)
  2254. * @return \Generator 返回生成器,用于流式输出
  2255. */
  2256. public function generateEpisodes($data) {
  2257. $script_id = getProp($data, 'script_id');
  2258. $group_id = getProp($data, 'group_id');
  2259. // $file = getProp($data, 'file');
  2260. $file = '';
  2261. $content = getProp($data, 'content', '');
  2262. // $bid = getProp($data, 'bid', 0);
  2263. $bid = 0;
  2264. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2265. if (!$group) {
  2266. Utils::throwError('20003:剧本分集不存在');
  2267. }
  2268. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2269. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2270. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2271. $prompt = getProp($data, 'prompt');
  2272. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2273. $model = getProp($data, 'model');
  2274. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2275. Utils::throwError('20003:该模型不存在!');
  2276. }
  2277. // 检查是否存在重叠的剧集序号范围
  2278. $exists_groups = DB::table('mp_script_episode_group')
  2279. ->where('script_id', $script_id)
  2280. ->where('id', '<>', $group_id) // 排除当前组
  2281. ->where('is_deleted', 0)
  2282. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2283. // 检查新范围是否与现有范围重叠
  2284. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2285. // 新范围的开始在现有范围内
  2286. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2287. ->where('end_episode_number', '>=', $start_episode_sequence);
  2288. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2289. // 新范围的结束在现有范围内
  2290. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2291. ->where('end_episode_number', '>=', $end_episode_sequence);
  2292. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2293. // 新范围完全包含现有范围
  2294. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2295. ->where('end_episode_number', '<=', $end_episode_sequence);
  2296. });
  2297. })
  2298. ->select('start_episode_number', 'end_episode_number')
  2299. ->get();
  2300. if ($exists_groups->isNotEmpty()) {
  2301. $conflict_ranges = [];
  2302. foreach ($exists_groups as $group) {
  2303. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2304. }
  2305. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2306. }
  2307. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2308. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2309. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2310. if ($model === 'deepseek-chat') {
  2311. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2312. $model = 'deepseek-v4-flash';
  2313. $thinkingMode = 'disabled';
  2314. } elseif ($model === 'deepseek-reasoner') {
  2315. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2316. $model = 'deepseek-v4-flash';
  2317. $thinkingMode = 'enabled';
  2318. }
  2319. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2320. if (!$script) {
  2321. Utils::throwError('20003:剧本不存在');
  2322. }
  2323. $content = getProp($group, 'content');
  2324. if (!$file && !$content && !$bid) {
  2325. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2326. }
  2327. // 提取文件内容
  2328. if ($file) {
  2329. $content = $this->extractFileContent($file);
  2330. if (!$content) {
  2331. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2332. }
  2333. } elseif ($bid) {
  2334. $content = $this->getContentByBid($bid);
  2335. if (!$content) {
  2336. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2337. }
  2338. } elseif ($content) {
  2339. $content = filterContent($content);
  2340. } elseif ($prompt) {
  2341. $content = filterContent($prompt);
  2342. } else {
  2343. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2344. }
  2345. // 构建消息
  2346. $messages = [
  2347. $this->sys_message,
  2348. [
  2349. 'role' => 'user',
  2350. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2351. ]
  2352. ];
  2353. $post_data = [
  2354. 'model' => $model,
  2355. 'messages' => $messages,
  2356. // 'max_tokens' => 8192,
  2357. 'temperature' => 0.7,
  2358. 'frequency_penalty' => 0,
  2359. 'presence_penalty' => 0,
  2360. 'thinking' => ['type' => $thinkingMode],
  2361. 'response_format' => ['type' => 'text'],
  2362. 'stream' => true
  2363. ];
  2364. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2365. // 根据模型类型选择调用方法
  2366. $fullContent = '';
  2367. $fullReasoningContent = '';
  2368. $usage = [];
  2369. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2370. // DeepSeek 官方模型使用 DeepSeek API
  2371. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2372. } else if (in_array($model, $this->gpt_text_models)) {
  2373. // GPT-5.4 模型使用 TokenRouter API
  2374. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2375. } else {
  2376. // 其他模型使用火山引擎API
  2377. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2378. }
  2379. // 处理流式输出
  2380. foreach ($streamGenerator as $chunk) {
  2381. if (isset($chunk['type'])) {
  2382. if ($chunk['type'] === 'done') {
  2383. // 最终结果
  2384. $fullContent = $chunk['full_content'];
  2385. $fullReasoningContent = $chunk['full_reasoning'];
  2386. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2387. } else {
  2388. // 逐块yield数据
  2389. yield $chunk;
  2390. }
  2391. }
  2392. }
  2393. dLog('deepseek')->info('完整内容: '.$fullContent);
  2394. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2395. // 处理完整内容并返回最终结果
  2396. $script_arr = [];
  2397. if ($fullContent) {
  2398. $script_arr = extractScriptContent($fullContent);
  2399. }
  2400. logDB('deepseek', 'info', '解析内容', $script_arr);
  2401. if (!$script_arr['episodes']) {
  2402. Utils::throwError('20003:未生成剧本相关信息');
  2403. // yield [
  2404. // 'type' => 'done',
  2405. // 'script' => $script_arr,
  2406. // 'msg' => '未生成剧本相关信息',
  2407. // 'answer' => $fullContent,
  2408. // 'reasoning' => $fullReasoningContent,
  2409. // 'usage' => $usage
  2410. // ];
  2411. // return ;
  2412. }
  2413. try {
  2414. DB::beginTransaction();
  2415. // // 返回前保存剧本内容
  2416. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2417. // 'content' => $content,
  2418. // 'updated_at' => date('Y-m-d H:i:s')
  2419. // ]);
  2420. // if (!$boolen) {
  2421. // Utils::throwError('20003:保存剧本内容失败');
  2422. // }
  2423. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2424. // 'start_episode_number' => $start_episode_sequence,
  2425. // 'end_episode_number' => $end_episode_sequence,
  2426. // 'updated_at' => date('Y-m-d H:i:s')
  2427. // ]);
  2428. // if (!$boolen1) {
  2429. // Utils::throwError('20003:保存分集失败');
  2430. // }
  2431. $episode_content = '';
  2432. $episodes = [];
  2433. foreach ($script_arr['episodes'] as $item) {
  2434. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2435. // $episodes[] = [
  2436. // 'script_id' => $script_id,
  2437. // 'episode_number' => $item['episode_number'],
  2438. // 'episode_name' => $item['episode_name'],
  2439. // 'episode_content' => $item['episode_content'],
  2440. // 'created_at' => date('Y-m-d H:i:s'),
  2441. // 'updated_at' => date('Y-m-d H:i:s'),
  2442. // ];
  2443. }
  2444. if ($episode_content) {
  2445. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2446. 'episode_content' => $episode_content,
  2447. 'updated_at' => date('Y-m-d H:i:s')
  2448. ]);
  2449. if (!$boolen2) {
  2450. Utils::throwError('20003:保存分集内容失败');
  2451. }
  2452. }else {
  2453. Utils::throwError('20003:分集剧本解析失败');
  2454. }
  2455. }catch (\Exception $e) {
  2456. DB::rollBack();
  2457. Utils::throwError('20003:'.$e->getMessage());
  2458. }
  2459. DB::commit();
  2460. yield [
  2461. 'type' => 'done',
  2462. 'script' => $script_arr,
  2463. 'episode_content' => $episode_content,
  2464. 'answer' => $fullContent,
  2465. 'reasoning' => $fullReasoningContent,
  2466. 'usage' => $usage
  2467. ];
  2468. }
  2469. public function chatWithFileStream($data) {
  2470. $script_id = getProp($data, 'script_id');
  2471. $group_id = getProp($data, 'group_id');
  2472. $file = getProp($data, 'file');
  2473. $content = getProp($data, 'content', '');
  2474. $bid = getProp($data, 'bid', 0);
  2475. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2476. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2477. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2478. $prompt = getProp($data, 'prompt');
  2479. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2480. if (!empty($prompt)) {
  2481. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2482. }
  2483. $question = getProp($data, 'question', $baseQuestion);
  2484. $model = getProp($data, 'model');
  2485. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2486. Utils::throwError('20003:该模型不存在!');
  2487. }
  2488. // 检查是否存在重叠的剧集序号范围
  2489. $exists_groups = DB::table('mp_script_episode_group')
  2490. ->where('script_id', $script_id)
  2491. ->where('id', '<>', $group_id)
  2492. ->where('is_deleted', 0)
  2493. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2494. // 检查新范围是否与现有范围重叠
  2495. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2496. // 新范围的开始在现有范围内
  2497. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2498. ->where('end_episode_number', '>=', $start_episode_sequence);
  2499. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2500. // 新范围的结束在现有范围内
  2501. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2502. ->where('end_episode_number', '>=', $end_episode_sequence);
  2503. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2504. // 新范围完全包含现有范围
  2505. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2506. ->where('end_episode_number', '<=', $end_episode_sequence);
  2507. });
  2508. })
  2509. ->select('start_episode_number', 'end_episode_number')
  2510. ->get();
  2511. if ($exists_groups->isNotEmpty()) {
  2512. $conflict_ranges = [];
  2513. foreach ($exists_groups as $group) {
  2514. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2515. }
  2516. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2517. }
  2518. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2519. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2520. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2521. if ($model === 'deepseek-chat') {
  2522. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2523. $model = 'deepseek-v4-flash';
  2524. $thinkingMode = 'disabled';
  2525. } elseif ($model === 'deepseek-reasoner') {
  2526. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2527. $model = 'deepseek-v4-flash';
  2528. $thinkingMode = 'enabled';
  2529. }
  2530. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2531. if (!$script) {
  2532. Utils::throwError('20003:剧本不存在');
  2533. }
  2534. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2535. if (!$group) {
  2536. Utils::throwError('20003:剧本分集不存在');
  2537. }
  2538. if (!$file && !$content && !$bid) {
  2539. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2540. }
  2541. // 提取文件内容
  2542. if ($file) {
  2543. $content = $this->extractFileContent($file);
  2544. if (!$content) {
  2545. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2546. }
  2547. } elseif ($bid) {
  2548. $content = $this->getContentByBid($bid);
  2549. if (!$content) {
  2550. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2551. }
  2552. } elseif ($content) {
  2553. $content = filterContent($content);
  2554. } elseif ($prompt) {
  2555. $content = filterContent($prompt);
  2556. } else {
  2557. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2558. }
  2559. // 构建消息
  2560. $messages = [
  2561. [
  2562. 'role' => 'system',
  2563. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2564. 强制要求:\n
  2565. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2566. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2567. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2568. 普通要求:\n
  2569. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2570. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2571. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2572. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2573. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2574. 示例如下:\n
  2575. ###剧本名:西昆仑
  2576. ###故事梗概
  2577. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2578. ###剧本亮点
  2579. 亮点1:绝境奇药,生死一线
  2580. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2581. 亮点2:结拜兄妹,化解尴尬
  2582. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2583. 亮点3:纤发夺命,情愫暗涌
  2584. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2585. ###人物关系
  2586. 阿雪与梁萧之间存在兄妹之情。
  2587. ###核心矛盾
  2588. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2589. ###主体列表
  2590. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2591. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2592. 阴阳球:天地异宝,能化生精气,救人于危难。
  2593. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2594. ###美术风格
  2595. 基础画风风格词:厚涂古风
  2596. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2597. ###场景列表
  2598. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2599. [
  2600. 'role' => 'user',
  2601. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2602. ]
  2603. ];
  2604. $post_data = [
  2605. 'model' => $model,
  2606. 'messages' => $messages,
  2607. // 'max_tokens' => 8192,
  2608. 'temperature' => 0.7,
  2609. 'frequency_penalty' => 0,
  2610. 'presence_penalty' => 0,
  2611. 'thinking' => ['type' => $thinkingMode],
  2612. 'response_format' => ['type' => 'text'],
  2613. 'stream' => true
  2614. ];
  2615. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2616. // 根据模型类型选择调用方法
  2617. $fullContent = '';
  2618. $fullReasoningContent = '';
  2619. $usage = [];
  2620. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2621. // DeepSeek 官方模型使用 DeepSeek API
  2622. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2623. } else if (in_array($model, $this->gpt_text_models)) {
  2624. // GPT-5.4 模型使用 TokenRouter API
  2625. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2626. } else {
  2627. // 其他模型使用火山引擎API
  2628. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2629. }
  2630. // 处理流式输出
  2631. foreach ($streamGenerator as $chunk) {
  2632. if (isset($chunk['type'])) {
  2633. if ($chunk['type'] === 'done') {
  2634. // 最终结果
  2635. $fullContent = $chunk['full_content'];
  2636. $fullReasoningContent = $chunk['full_reasoning'];
  2637. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2638. } else {
  2639. // 逐块yield数据
  2640. yield $chunk;
  2641. }
  2642. }
  2643. }
  2644. dLog('deepseek')->info('完整内容: '.$fullContent);
  2645. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2646. // 处理完整内容并返回最终结果
  2647. $script_arr = [];
  2648. if ($fullContent) {
  2649. $script_arr = extractScriptContent($fullContent);
  2650. }
  2651. logDB('deepseek', 'info', '解析内容', $script_arr);
  2652. if (!$script_arr['roles']) {
  2653. Utils::throwError('20003:未生成剧本相关信息');
  2654. // yield [
  2655. // 'type' => 'done',
  2656. // 'script' => $script_arr,
  2657. // 'msg' => '未生成剧本相关信息',
  2658. // 'answer' => $fullContent,
  2659. // 'reasoning' => $fullReasoningContent,
  2660. // 'usage' => $usage
  2661. // ];
  2662. }
  2663. try {
  2664. DB::beginTransaction();
  2665. // // 返回前保存剧本内容
  2666. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2667. // 'content' => $content,
  2668. // 'status' => '解析完成',
  2669. // 'updated_at' => date('Y-m-d H:i:s')
  2670. // ]);
  2671. // if (!$boolen) {
  2672. // Utils::throwError('20003:保存剧本内容失败');
  2673. // }
  2674. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2675. 'start_episode_number' => $start_episode_sequence,
  2676. 'end_episode_number' => $end_episode_sequence,
  2677. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2678. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2679. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2680. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2681. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2682. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2683. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2684. 'status' => '解析完成',
  2685. 'content' => $content,
  2686. 'updated_at' => date('Y-m-d H:i:s')
  2687. ]);
  2688. if (!$boolen1) {
  2689. Utils::throwError('20003:保存分集失败');
  2690. }
  2691. // $episodes = [];
  2692. // foreach ($script_arr['episodes'] as $item) {
  2693. // $episodes[] = [
  2694. // 'script_id' => $script_id,
  2695. // 'episode_number' => $item['episode_number'],
  2696. // 'episode_name' => $item['episode_name'],
  2697. // 'episode_content' => $item['episode_content'],
  2698. // 'created_at' => date('Y-m-d H:i:s'),
  2699. // 'updated_at' => date('Y-m-d H:i:s'),
  2700. // ];
  2701. // }
  2702. // if ($episodes) {
  2703. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2704. // if (!$boolen2) {
  2705. // Utils::throwError('20003:保存分集内容失败');
  2706. // }
  2707. // }else {
  2708. // Utils::throwError('20003:分集剧本解析失败');
  2709. // }
  2710. }catch (\Exception $e) {
  2711. DB::rollBack();
  2712. Utils::throwError('20003:'.$e->getMessage());
  2713. }
  2714. DB::commit();
  2715. yield [
  2716. 'type' => 'done',
  2717. 'script' => $script_arr,
  2718. 'answer' => $fullContent,
  2719. 'reasoning' => $fullReasoningContent,
  2720. 'usage' => $usage
  2721. ];
  2722. }
  2723. /**
  2724. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2725. *
  2726. * @param array $data 包含以下参数:
  2727. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2728. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2729. * - model: 使用的模型(r1 或 v3,默认 v3)
  2730. * @return array
  2731. */
  2732. public function chatWithFile($data) {
  2733. $script_id = getProp($data, 'script_id');
  2734. $file = getProp($data, 'file');
  2735. $content = getProp($data, 'content', '');
  2736. $bid = getProp($data, 'bid', 0);
  2737. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2738. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2739. $prompt = getProp($data, 'prompt');
  2740. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2741. if (!empty($prompt)) {
  2742. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2743. }
  2744. $question = getProp($data, 'question', $baseQuestion);
  2745. // 处理文本模型
  2746. $model = getProp($data, 'model');
  2747. if (!$model) {
  2748. // 用户没有输入,使用默认值
  2749. $model = 'doubao-seed-2-0-mini-260215';
  2750. }
  2751. // 验证模型是否在可用模型表中
  2752. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2753. $model = 'doubao-seed-2-0-mini-260215';
  2754. }
  2755. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2756. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2757. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2758. if ($model === 'deepseek-chat') {
  2759. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2760. $model = 'deepseek-v4-flash';
  2761. $thinkingMode = 'disabled';
  2762. } elseif ($model === 'deepseek-reasoner') {
  2763. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2764. $model = 'deepseek-v4-flash';
  2765. $thinkingMode = 'enabled';
  2766. }
  2767. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2768. if (!$script) {
  2769. Utils::throwError('20003:剧本不存在');
  2770. }
  2771. if (!$file && !$content && !$bid) {
  2772. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2773. }
  2774. // 提取文件内容
  2775. if ($file) {
  2776. $content = $this->extractFileContent($file);
  2777. if (!$content) {
  2778. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2779. }
  2780. } elseif ($bid) {
  2781. $content = $this->getContentByBid($bid);
  2782. if (!$content) {
  2783. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2784. }
  2785. } elseif ($content) {
  2786. $content = filterContent($content);
  2787. } elseif ($prompt) {
  2788. $content = filterContent($prompt);
  2789. } else {
  2790. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2791. }
  2792. // 构建消息
  2793. $messages = [
  2794. $this->sys_message,
  2795. [
  2796. 'role' => 'user',
  2797. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2798. ]
  2799. ];
  2800. $post_data = [
  2801. 'model' => $model,
  2802. 'messages' => $messages,
  2803. // 'max_tokens' => 8192,
  2804. 'temperature' => 0.7,
  2805. 'frequency_penalty' => 0,
  2806. 'presence_penalty' => 0,
  2807. 'thinking' => ['type' => $thinkingMode],
  2808. 'response_format' => ['type' => 'text'],
  2809. 'stream' => false
  2810. ];
  2811. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2812. // 根据模型类型选择调用方法
  2813. $fullContent = '';
  2814. $usage = [];
  2815. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2816. // DeepSeek 官方模型使用 DeepSeek API
  2817. $chatResult = $this->chatOnly($post_data);
  2818. } else if (in_array($model, $this->gpt_text_models)) {
  2819. // GPT-5.4 模型使用 TokenRouter API
  2820. $chatResult = $this->gpt54ChatOnly($post_data);
  2821. } else {
  2822. // 其他模型使用火山引擎API
  2823. $chatResult = $this->volcEngineChatCompletion($post_data);
  2824. }
  2825. if (is_array($chatResult)) {
  2826. $fullContent = $chatResult['fullContent'];
  2827. $usage = $chatResult['usage'];
  2828. }
  2829. $script_arr = [];
  2830. // 处理结果
  2831. if ($fullContent) {
  2832. $script_arr = extractScriptContent($fullContent);
  2833. }
  2834. // 返回前保存剧本内容
  2835. DB::table('mp_scripts')->where('id', $script_id)->update([
  2836. 'content' => $content,
  2837. 'updated_at' => date('Y-m-d H:i:s')
  2838. ]);
  2839. return [
  2840. 'script' => $script_arr,
  2841. 'answer' => $fullContent,
  2842. 'usage' => $usage
  2843. ];
  2844. }
  2845. public function getEpisodeContent($data) {
  2846. $group_id = getProp($data, 'group_id');
  2847. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2848. }
  2849. public function saveEpisodeContent($data) {
  2850. $script_id = getProp($data, 'script_id');
  2851. $group_id = getProp($data, 'group_id');
  2852. $start_episode_sequence = getProp($data, 'start_episode_number');
  2853. $end_episode_sequence = getProp($data, 'end_episode_number');
  2854. // 检查是否存在重叠的剧集序号范围
  2855. $exists_groups = DB::table('mp_script_episode_group')
  2856. ->where('script_id', $script_id)
  2857. ->where('id', '<>', $group_id) // 排除当前组
  2858. ->where('is_deleted', 0)
  2859. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2860. // 检查新范围是否与现有范围重叠
  2861. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2862. // 新范围的开始在现有范围内
  2863. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2864. ->where('end_episode_number', '>=', $start_episode_sequence);
  2865. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2866. // 新范围的结束在现有范围内
  2867. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2868. ->where('end_episode_number', '>=', $end_episode_sequence);
  2869. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2870. // 新范围完全包含现有范围
  2871. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2872. ->where('end_episode_number', '<=', $end_episode_sequence);
  2873. });
  2874. })
  2875. ->select('start_episode_number', 'end_episode_number')
  2876. ->get();
  2877. if ($exists_groups->isNotEmpty()) {
  2878. $conflict_ranges = [];
  2879. foreach ($exists_groups as $group) {
  2880. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2881. }
  2882. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2883. }
  2884. $episode_content = getProp($data, 'episode_content');
  2885. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2886. 'content' => $episode_content,
  2887. 'start_episode_number' => $start_episode_sequence,
  2888. 'end_episode_number' => $end_episode_sequence,
  2889. 'updated_at' => date('Y-m-d H:i:s')
  2890. ]);
  2891. $script_arr =getProp($data, 'script', []);
  2892. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2893. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2894. $script_id = getProp($data, 'script_id');
  2895. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2896. try {
  2897. DB::beginTransaction();
  2898. $update_data = [
  2899. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2900. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2901. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2902. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2903. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2904. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2905. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2906. 'status' => 3,
  2907. 'start_episode_sequence' => $start_episode_sequence,
  2908. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2909. 'episode_num' => count($script_arr['episodes']),
  2910. 'updated_at' => date('Y-m-d H:i:s')
  2911. ];
  2912. // 保存剧本内容
  2913. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2914. if (!$boolen) {
  2915. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2916. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2917. Utils::throwError('20003:剧本内容保存失败');
  2918. }
  2919. // 保存分集内容
  2920. // 删除历史分集内容
  2921. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2922. $episodes = [];
  2923. $sequence = 1;
  2924. foreach ($script_arr['episodes'] as $episode) {
  2925. $segment_number = 1;
  2926. foreach($episode['segments'] as $segment) {
  2927. $episodes[] = [
  2928. 'script_id' => $script_id,
  2929. 'episode_number' => $episode['episode_number'],
  2930. 'title' => $episode['title'],
  2931. // 'content' => $episode['content'],
  2932. 'content' => '',
  2933. 'segment_number' => $segment_number,
  2934. 'segment_content' => $segment['segment_content'],
  2935. 'sequence' => $sequence,
  2936. 'created_at' => date('Y-m-d H:i:s'),
  2937. 'updated_at' => date('Y-m-d H:i:s')
  2938. ];
  2939. $sequence++;
  2940. $segment_number++;
  2941. }
  2942. }
  2943. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2944. if (!$boolen2) {
  2945. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2946. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2947. Utils::throwError('20003:分集内容保存失败');
  2948. }
  2949. } catch (\Exception $e) {
  2950. DB::rollBack();
  2951. Utils::throwError('20003:'.$e->getMessage());
  2952. }
  2953. DB::commit();
  2954. return true;
  2955. }
  2956. public function getBookContent($data) {
  2957. $bid = getProp($data, 'bid');
  2958. $start_sequence = getProp($data, 'start_sequence');
  2959. $end_sequence = getProp($data, 'end_sequence');
  2960. $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])
  2961. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2962. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2963. return $return_content;
  2964. }
  2965. public function exportScript($data) {
  2966. $filename = getProp($data, 'filename');
  2967. $script_id = getProp($data, 'script_id');
  2968. $group_id = getProp($data, 'group_id');
  2969. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2970. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2971. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2972. $script = (array)$script;
  2973. // 获取分集组信息
  2974. if ($group_id) {
  2975. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2976. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2977. ->get()->map(function($value) {
  2978. return (array)$value;
  2979. })->toArray();
  2980. }else {
  2981. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_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. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2984. return (array)$value;
  2985. })->toArray();
  2986. }
  2987. if (!$groups) Utils::throwError('20003:分集不存在');
  2988. $script['group'] = $groups;
  2989. $export_type = getProp($data, 'export_type', 'txt');
  2990. // 生成文件名
  2991. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2992. // 根据导出类型生成不同格式的文件
  2993. switch ($export_type) {
  2994. case 'txt':
  2995. return $this->exportScriptAsTxt($script, $filename);
  2996. case 'pdf':
  2997. return $this->exportScriptAsPdf($script, $filename);
  2998. default:
  2999. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3000. }
  3001. }
  3002. /**
  3003. * 导出剧本为TXT格式
  3004. */
  3005. private function exportScriptAsTxt($script, $filename) {
  3006. // 构建TXT内容
  3007. $content = $this->buildScriptContent($script);
  3008. // 设置响应头,直接下载
  3009. header('Content-Type: text/plain; charset=utf-8');
  3010. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3011. header('Content-Length: ' . strlen($content));
  3012. // 输出内容并结束
  3013. echo $content;
  3014. exit();
  3015. }
  3016. /**
  3017. * 导出剧本为PDF格式
  3018. */
  3019. private function exportScriptAsPdf($script, $filename) {
  3020. // 使用HTML转PDF的方式来更好地支持中文
  3021. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3022. // 创建PDF实例
  3023. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3024. // 设置文档信息
  3025. $pdf->SetCreator('剧本导出系统');
  3026. $pdf->SetAuthor('系统');
  3027. $pdf->SetTitle($script['script_name']);
  3028. $pdf->SetSubject('剧本导出');
  3029. // 设置边距
  3030. $pdf->SetMargins(15, 15, 15);
  3031. $pdf->SetAutoPageBreak(TRUE, 15);
  3032. // 添加页面
  3033. $pdf->AddPage();
  3034. // 注册并使用 simsun.ttf 字体
  3035. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3036. // 使用HTML内容生成PDF
  3037. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3038. // 直接输出PDF文件供下载
  3039. header('Content-Type: application/pdf');
  3040. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3041. // 直接输出PDF内容
  3042. $pdf->Output($filename . '.pdf', 'D');
  3043. exit();
  3044. }
  3045. /**
  3046. * 构建用于PDF的HTML内容
  3047. */
  3048. private function buildScriptHtmlForPdf($script) {
  3049. $html = '<style>
  3050. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3051. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3052. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3053. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3054. .info { margin-bottom: 8px; }
  3055. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3056. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3057. .segment { margin-bottom: 10px; margin-left: 20px; }
  3058. .episode-content { white-space: pre-wrap; }
  3059. </style>';
  3060. // 标题
  3061. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3062. // 处理分组数据
  3063. if (!empty($script['group']) && is_array($script['group'])) {
  3064. $groups = (array)$script['group'];
  3065. foreach ($groups as $group) {
  3066. $html .= '<div class="group">';
  3067. // 分组标题
  3068. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3069. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3070. // 故事梗概
  3071. if (!empty($group['intro'])) {
  3072. $html .= '<h3>故事梗概</h3>';
  3073. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3074. }
  3075. // 剧本亮点
  3076. if (!empty($group['highlights'])) {
  3077. $html .= '<h3>剧本亮点</h3>';
  3078. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3079. }
  3080. // 人物关系
  3081. if (!empty($group['role_relationship'])) {
  3082. $html .= '<h3>人物关系</h3>';
  3083. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3084. }
  3085. // 核心矛盾
  3086. if (!empty($group['core_contradiction'])) {
  3087. $html .= '<h3>核心矛盾</h3>';
  3088. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3089. }
  3090. // 主体列表
  3091. if (!empty($group['roles']) && is_array($group['roles'])) {
  3092. $html .= '<h3>主体列表</h3>';
  3093. $html .= '<ul>';
  3094. foreach ($group['roles'] as $role) {
  3095. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3096. }
  3097. $html .= '</ul>';
  3098. }
  3099. // 美术风格
  3100. if (!empty($group['art_style'])) {
  3101. $html .= '<h3>美术风格</h3>';
  3102. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3103. }
  3104. // 场景列表
  3105. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3106. $html .= '<h3>场景列表</h3>';
  3107. $html .= '<ul>';
  3108. foreach ($group['scenes'] as $scene) {
  3109. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3110. }
  3111. $html .= '</ul>';
  3112. }
  3113. // 分集剧本
  3114. if (!empty($group['episode_content'])) {
  3115. $html .= '<h3>分集剧本</h3>';
  3116. // 去除零宽字符和其他不可见字符
  3117. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3118. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3119. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3120. }
  3121. $html .= '</div>';
  3122. }
  3123. }
  3124. return $html;
  3125. }
  3126. /**
  3127. * 构建PDF内容
  3128. */
  3129. private function buildPdfContent($pdf, $script) {
  3130. // 标题
  3131. $pdf->SetFont('dejavusans', 'B', 18);
  3132. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3133. $pdf->Ln(5);
  3134. // 基本信息
  3135. $pdf->SetFont('dejavusans', '', 12);
  3136. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3137. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3138. $pdf->Ln(5);
  3139. // 剧本简介
  3140. if (!empty($script['intro'])) {
  3141. $pdf->SetFont('dejavusans', 'B', 14);
  3142. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3143. $pdf->SetFont('dejavusans', '', 12);
  3144. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3145. $pdf->Ln(3);
  3146. }
  3147. // 亮点
  3148. if (!empty($script['highlights'])) {
  3149. $pdf->SetFont('dejavusans', 'B', 14);
  3150. $pdf->Cell(0, 10, '亮点', 0, 1);
  3151. $pdf->SetFont('dejavusans', '', 12);
  3152. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3153. $pdf->Ln(3);
  3154. }
  3155. // 核心矛盾
  3156. if (!empty($script['core_contradiction'])) {
  3157. $pdf->SetFont('dejavusans', 'B', 14);
  3158. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3159. $pdf->SetFont('dejavusans', '', 12);
  3160. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3161. $pdf->Ln(3);
  3162. }
  3163. // 艺术风格
  3164. if (!empty($script['art_style'])) {
  3165. $pdf->SetFont('dejavusans', 'B', 14);
  3166. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3167. $pdf->SetFont('dejavusans', '', 12);
  3168. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3169. $pdf->Ln(3);
  3170. }
  3171. // 备注
  3172. if (!empty($script['remark'])) {
  3173. $pdf->SetFont('dejavusans', 'B', 14);
  3174. $pdf->Cell(0, 10, '备注', 0, 1);
  3175. $pdf->SetFont('dejavusans', '', 12);
  3176. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3177. $pdf->Ln(3);
  3178. }
  3179. // 角色列表
  3180. if (!empty($script['roles']) && is_array($script['roles'])) {
  3181. $pdf->SetFont('dejavusans', 'B', 14);
  3182. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3183. $pdf->SetFont('dejavusans', '', 12);
  3184. foreach ($script['roles'] as $index => $role) {
  3185. if (is_array($role) || is_object($role)) {
  3186. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3187. } else {
  3188. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3189. }
  3190. }
  3191. $pdf->Ln(3);
  3192. }
  3193. // 角色关系
  3194. if (!empty($script['role_relationship'])) {
  3195. $pdf->SetFont('dejavusans', 'B', 14);
  3196. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3197. $pdf->SetFont('dejavusans', '', 12);
  3198. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3199. $pdf->Ln(3);
  3200. }
  3201. // 场景列表
  3202. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3203. $pdf->SetFont('dejavusans', 'B', 14);
  3204. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3205. $pdf->SetFont('dejavusans', '', 12);
  3206. foreach ($script['scenes'] as $index => $scene) {
  3207. if (is_array($scene) || is_object($scene)) {
  3208. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3209. } else {
  3210. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3211. }
  3212. }
  3213. $pdf->Ln(5);
  3214. }
  3215. // 分集内容
  3216. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3217. $pdf->SetFont('dejavusans', 'B', 16);
  3218. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3219. $pdf->Ln(3);
  3220. foreach ($script['episodes'] as $episode) {
  3221. // 检查是否需要新页面
  3222. if ($pdf->GetY() > 250) {
  3223. $pdf->AddPage();
  3224. }
  3225. $pdf->SetFont('dejavusans', 'B', 14);
  3226. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3227. if (!empty($episode['title'])) {
  3228. $episodeTitle .= ':' . $episode['title'];
  3229. }
  3230. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3231. // 处理分段内容
  3232. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3233. $pdf->SetFont('dejavusans', '', 12);
  3234. foreach ($episode['segments'] as $segment) {
  3235. if (!empty($segment['segment_content'])) {
  3236. // 如果有分段编号,显示分段标题
  3237. if (!empty($segment['segment_number'])) {
  3238. $pdf->SetFont('dejavusans', 'B', 12);
  3239. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3240. $pdf->SetFont('dejavusans', '', 12);
  3241. }
  3242. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3243. $pdf->Ln(2);
  3244. }
  3245. }
  3246. }
  3247. $pdf->Ln(5);
  3248. }
  3249. }
  3250. }
  3251. /**
  3252. * 构建剧本文本内容
  3253. */
  3254. private function buildScriptContent($script) {
  3255. $content = '';
  3256. $groups = $script['group'];
  3257. $groups = (array)$groups;
  3258. foreach ($groups as $group) {
  3259. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3260. // 剧本基本信息
  3261. if (!empty($group['intro'])) {
  3262. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3263. }
  3264. if (!empty($group['highlights'])) {
  3265. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3266. }
  3267. if (!empty($group['role_relationship'])) {
  3268. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3269. }
  3270. if (!empty($group['core_contradiction'])) {
  3271. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3272. }
  3273. if (!empty($group['roles']) && is_array($group['roles'])) {
  3274. $content .= "###主体列表\n";
  3275. foreach ($group['roles'] as $role) {
  3276. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3277. }
  3278. $content .= "\n\n";
  3279. }
  3280. if (!empty($group['art_style'])) {
  3281. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3282. }
  3283. // 场景信息
  3284. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3285. $content .= "###场景列表\n";
  3286. foreach ($group['scenes'] as $scene) {
  3287. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3288. }
  3289. $content .= "\n\n";
  3290. }
  3291. // 分集内容
  3292. if (!empty($group['episode_content'])) {
  3293. $content .= "###分集剧本\n";
  3294. $content .= $group['episode_content'];
  3295. // foreach ($script['episodes'] as $episode) {
  3296. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3297. // // if (!empty($episode['episode_name'])) {
  3298. // // $content .= ":" . $episode['episode_name'];
  3299. // // }
  3300. // // $content .= "\n";
  3301. // $content .= $episode['episode_content'] . "\n\n";
  3302. // }
  3303. }
  3304. }
  3305. return $content;
  3306. }
  3307. /**
  3308. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3309. *
  3310. * @param array $data 包含以下参数:
  3311. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3312. * - question: 用户问题(可选)
  3313. * - model: 使用的模型(r1 或 v3,默认 v3)
  3314. * @return \Generator 返回生成器,用于流式输出
  3315. */
  3316. public function addChat($data) {
  3317. $uid = Site::getUid();
  3318. $anime_id = getProp($data, 'anime_id');
  3319. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3320. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3321. if (!$anime) Utils::throwError('20003:对话不存在');
  3322. $file = getProp($data, 'file');
  3323. $content = getProp($data, 'content', '');
  3324. $bid = getProp($data, 'bid', 0);
  3325. $script_id = getProp($data, 'script_id', 0);
  3326. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3327. $prompt = getProp($data, 'prompt');
  3328. $user_anime_name = getProp($anime, 'anime_name');
  3329. // 处理文本模型
  3330. $model = getProp($data, 'model');
  3331. if (!$model) {
  3332. // 用户没有输入,从anime表获取
  3333. $model = getProp($anime, 'model');
  3334. if (!$model) {
  3335. // anime表也没有,使用默认值
  3336. $model = 'doubao-seed-2-0-mini-260215';
  3337. }
  3338. }
  3339. // 验证模型是否在可用模型表中
  3340. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3341. $model = 'doubao-seed-2-0-mini-260215';
  3342. }
  3343. $is_multi = getProp($anime, 'is_multi');
  3344. $is_single = (int)$is_multi !== 1;
  3345. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3346. if ($prompt) {
  3347. $question .= "本次修改要求如下:\n{$prompt}";
  3348. }
  3349. // if (!$file && !$content && !$bid) {
  3350. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3351. // }
  3352. // 提取文件内容
  3353. if ($file) {
  3354. $content = $this->extractFileContent($file);
  3355. if (!$content) {
  3356. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3357. }
  3358. } elseif ($script_id) {
  3359. $content = $this->getContentByScriptId($script_id);
  3360. if (!$content) {
  3361. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3362. }
  3363. } elseif ($bid) {
  3364. $content = $this->getContentByBid($bid);
  3365. if (!$content) {
  3366. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3367. }
  3368. } elseif ($content) {
  3369. $content = filterContent($content);
  3370. } else {
  3371. $content = getProp($anime, 'content');
  3372. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3373. $need_generate_content = true;
  3374. }
  3375. }
  3376. // 美术风格
  3377. $input_art_style = getProp($data, 'art_style');
  3378. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3379. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3380. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3381. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3382. 中年女:邻居阿姨
  3383. 老年男:幽默大爷
  3384. 老年女:婆婆
  3385. 萌娃:奶气萌娃";
  3386. // 判断是否需要生成原文内容
  3387. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3388. // 如果需要生成原文内容,添加额外的要求
  3389. $content_generation_requirement = $need_generate_content
  3390. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3391. : "";
  3392. // 美术风格
  3393. if (!$mappedArtStyle) {
  3394. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3395. }else {
  3396. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3397. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3398. }else {
  3399. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3400. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3401. }
  3402. }
  3403. $systemPrompt = $is_single
  3404. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3405. 强制要求:
  3406. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3407. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3408. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3409. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3410. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3411. 普通要求:
  3412. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3413. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3414. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3415. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3416. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3417. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3418. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3419. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3420. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3421. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3422. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3423. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3424. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3425. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3426. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3427. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3428. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3429. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3430. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3431. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3432. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3433. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3434. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3435. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3436. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3437. 5.{$mappedArtStyle_prompt}\n\n
  3438. 示例如下:\n
  3439. ###剧本名:西昆仑
  3440. ###故事梗概
  3441. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3442. ###剧本亮点
  3443. 亮点1:绝境奇药,生死一线
  3444. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3445. 亮点2:结拜兄妹,化解尴尬
  3446. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3447. 亮点3:纤发夺命,情愫暗涌
  3448. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3449. ###人物关系
  3450. 阿雪与梁萧之间存在兄妹之情。
  3451. ###核心矛盾
  3452. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3453. ###主体列表
  3454. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3455. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3456. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3457. 姿态:站立。}{{甜心小美}}
  3458. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3459. 全景,正面拍摄,青年女性,亚洲人。
  3460. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3461. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3462. 姿态:站立。}{{阳光青年}}
  3463. ###美术风格
  3464. 基础画风风格词:厚涂古风
  3465. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3466. ###场景列表
  3467. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3468. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3469. 无人物。}
  3470. ###分镜剧本
  3471. ##第1幕:徐家老旧厨房 白天 室内
  3472. 分镜1
  3473. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3474. 场景:徐家老旧厨房
  3475. 构图设计:全景,低角度仰视
  3476. 运镜调度:手持拍摄
  3477. 配音角色:旁白
  3478. 出镜角色:许芸-校服装、徐母
  3479. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3480. 画面类型:普通画面
  3481. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3482. 分镜2
  3483. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3484. 场景:徐家老旧厨房
  3485. 构图设计:近景,徐母面部特写
  3486. 运镜调度:固定镜头
  3487. 配音角色:徐母
  3488. 出镜角色:徐母
  3489. 台词内容:问我夜不归宿死哪儿去了。
  3490. 画面类型:对口型
  3491. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3492. ##第2幕:徐家简陋客厅 黄昏 室内
  3493. 分镜3
  3494. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3495. 场景:徐家简陋客厅
  3496. 构图设计:全景,景深虚化
  3497. 运镜调度:固定镜头
  3498. 配音角色:旁白
  3499. 出镜角色:无
  3500. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3501. 画面类型:普通画面
  3502. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3503. 分镜4
  3504. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3505. 场景:徐家简陋客厅
  3506. 构图设计:特写,火车票
  3507. 运镜调度:固定镜头
  3508. 配音角色:旁白
  3509. 出镜角色:无
  3510. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3511. 画面类型:普通画面
  3512. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3513. "
  3514. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3515. 强制要求:\n
  3516. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3517. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3518. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3519. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3520. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3521. 普通要求:\n
  3522. 1.剧本名(必须生成)必须与文档内容高度相关
  3523. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3524. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3525. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3526. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3527. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3528. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3529. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3530. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3531. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3532. 4.{$mappedArtStyle_prompt}\n\n
  3533. 示例如下:\n
  3534. ###剧本名:西昆仑
  3535. ###故事梗概
  3536. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3537. ###剧本亮点
  3538. 亮点1:绝境奇药,生死一线
  3539. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3540. 亮点2:结拜兄妹,化解尴尬
  3541. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3542. 亮点3:纤发夺命,情愫暗涌
  3543. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3544. ###人物关系
  3545. 阿雪与梁萧之间存在兄妹之情。
  3546. ###核心矛盾
  3547. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3548. ###主体列表
  3549. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3550. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3551. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3552. 姿态:站立。}{{甜心小美}}
  3553. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3554. 全景,正面拍摄,青年女性,亚洲人。
  3555. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3556. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3557. 姿态:站立。}{{阳光青年}}
  3558. ###美术风格
  3559. 基础画风风格词:厚涂古风
  3560. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3561. ###场景列表
  3562. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3563. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3564. 无人物。}";
  3565. // 构建消息
  3566. $messages = [
  3567. [
  3568. 'role' => 'system',
  3569. 'content' => $systemPrompt
  3570. ],
  3571. [
  3572. 'role' => 'user',
  3573. 'content' => "以下是文档内容:
  3574. {$content}
  3575. 用户问题:
  3576. {$question}"
  3577. ]
  3578. ];
  3579. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3580. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3581. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3582. if ($model === 'deepseek-chat') {
  3583. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3584. $model = 'deepseek-v4-flash';
  3585. $thinkingMode = 'disabled';
  3586. } elseif ($model === 'deepseek-reasoner') {
  3587. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3588. $model = 'deepseek-v4-flash';
  3589. $thinkingMode = 'enabled';
  3590. }
  3591. $post_data = [
  3592. 'model' => $model,
  3593. 'messages' => $messages,
  3594. // 'max_tokens' => 8192,
  3595. 'temperature' => 0.7,
  3596. 'frequency_penalty' => 0,
  3597. 'presence_penalty' => 0,
  3598. 'response_format' => ['type' => 'text'],
  3599. 'thinking' => ['type'=>$thinkingMode],
  3600. 'stream' => true // 启用流式输出
  3601. ];
  3602. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3603. // 根据模型类型选择调用方法
  3604. $fullContent = '';
  3605. $fullReasoningContent = '';
  3606. $usage = [];
  3607. try {
  3608. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3609. // DeepSeek 官方模型使用 DeepSeek API
  3610. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3611. } else if (in_array($model, $this->gpt_text_models)) {
  3612. // GPT-5.4 模型使用 TokenRouter API
  3613. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3614. } else {
  3615. // 其他模型使用火山引擎API
  3616. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3617. }
  3618. // 验证返回值类型
  3619. if (!is_iterable($streamGenerator)) {
  3620. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3621. dLog('deepseek')->error('addChat流式生成器无效', [
  3622. 'generator_type' => $errorType,
  3623. 'model' => $model,
  3624. 'anime_id' => $anime_id
  3625. ]);
  3626. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3627. 'type' => $errorType,
  3628. 'model' => $model
  3629. ]);
  3630. yield [
  3631. 'type' => 'error',
  3632. 'script' => [],
  3633. 'episode' => [],
  3634. 'answer' => '',
  3635. 'reasoning' => '',
  3636. 'usage' => [],
  3637. 'error' => '接口返回数据异常,请重新请求'
  3638. ];
  3639. return;
  3640. }
  3641. // 处理流式输出
  3642. foreach ($streamGenerator as $chunk) {
  3643. if (isset($chunk['type'])) {
  3644. if ($chunk['type'] === 'done') {
  3645. // 最终结果
  3646. $fullContent = $chunk['full_content'];
  3647. $fullReasoningContent = $chunk['full_reasoning'];
  3648. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3649. } else {
  3650. // 逐块yield数据
  3651. yield $chunk;
  3652. }
  3653. }
  3654. }
  3655. } catch (\Exception $e) {
  3656. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3657. 'model' => $model,
  3658. 'anime_id' => $anime_id,
  3659. 'trace' => $e->getTraceAsString()
  3660. ]);
  3661. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3662. 'error' => $e->getMessage(),
  3663. 'model' => $model
  3664. ]);
  3665. yield [
  3666. 'type' => 'error',
  3667. 'script' => [],
  3668. 'episode' => [],
  3669. 'answer' => '',
  3670. 'reasoning' => '',
  3671. 'usage' => [],
  3672. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3673. ];
  3674. return;
  3675. }
  3676. dLog('deepseek')->info('完整内容: '.$fullContent);
  3677. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3678. // 处理完整内容并返回最终结果
  3679. $script_arr = [];
  3680. if ($fullContent) {
  3681. $script_arr = handleScriptContent($fullContent);
  3682. dLog('deepseek')->info('解析内容', $script_arr);
  3683. logDB('deepseek', 'info', '解析内容', $script_arr);
  3684. }
  3685. if (empty($script_arr['roles'])) {
  3686. // 未生成剧本相关内容,保存对话记录并返回提示
  3687. dLog('deepseek')->info('未生成剧本相关的内容');
  3688. try {
  3689. DB::beginTransaction();
  3690. $now = date('Y-m-d H:i:s');
  3691. // 保存对话记录
  3692. $records = [
  3693. [
  3694. 'uid' => $uid,
  3695. 'anime_id' => $anime_id,
  3696. 'sequence' => 0,
  3697. 'role' => 'user',
  3698. 'content' => $prompt,
  3699. 'created_at' => $now,
  3700. 'updated_at' => $now
  3701. ],
  3702. [
  3703. 'uid' => $uid,
  3704. 'anime_id' => $anime_id,
  3705. 'sequence' => 0,
  3706. 'role' => 'assistant',
  3707. // 'content' => $fullContent,
  3708. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3709. 'created_at' => $now,
  3710. 'updated_at' => $now
  3711. ]
  3712. ];
  3713. DB::table('mp_anime_records')->insert($records);
  3714. DB::commit();
  3715. } catch (\Exception $e) {
  3716. DB::rollBack();
  3717. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3718. }
  3719. yield [
  3720. 'type' => 'done',
  3721. 'script' => [],
  3722. 'episode' => [],
  3723. 'answer' => $fullContent,
  3724. 'reasoning' => $fullReasoningContent,
  3725. 'usage' => $usage,
  3726. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3727. ];
  3728. return;
  3729. }
  3730. // 如果需要生成原文内容,从script_arr中提取
  3731. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3732. $content = $script_arr['content'];
  3733. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3734. if (!$content) {
  3735. yield [
  3736. 'type' => 'done',
  3737. 'script' => [],
  3738. 'episode' => [],
  3739. 'answer' => $fullContent,
  3740. 'reasoning' => $fullReasoningContent,
  3741. 'usage' => $usage,
  3742. 'error' => '未生成剧本内容,请调整提示词再试'
  3743. ];
  3744. return;
  3745. }
  3746. }
  3747. // 替换美术风格
  3748. if ($mappedArtStyle !== '') {
  3749. $script_arr['art_style'] = $mappedArtStyle;
  3750. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3751. }
  3752. // 新建动漫
  3753. if ($user_anime_name == '新剧本策划') {
  3754. $anime_name = getProp($script_arr, 'script_name');
  3755. // if (!$anime_name) {
  3756. // // 未识别到剧本名,保存对话记录并返回提示
  3757. // dLog('deepseek')->info('未能识别到剧本名称');
  3758. // try {
  3759. // DB::beginTransaction();
  3760. // $now = date('Y-m-d H:i:s');
  3761. // // 保存对话记录
  3762. // $records = [
  3763. // [
  3764. // 'uid' => $uid,
  3765. // 'anime_id' => $anime_id,
  3766. // 'sequence' => 0,
  3767. // 'role' => 'user',
  3768. // 'content' => $prompt,
  3769. // 'created_at' => $now,
  3770. // 'updated_at' => $now
  3771. // ],
  3772. // [
  3773. // 'uid' => $uid,
  3774. // 'anime_id' => $anime_id,
  3775. // 'sequence' => 0,
  3776. // 'role' => 'assistant',
  3777. // 'content' => '未能生成剧本名称,请重试',
  3778. // 'created_at' => $now,
  3779. // 'updated_at' => $now
  3780. // ]
  3781. // ];
  3782. // DB::table('mp_anime_records')->insert($records);
  3783. // DB::commit();
  3784. // } catch (\Exception $e) {
  3785. // DB::rollBack();
  3786. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3787. // }
  3788. // yield [
  3789. // 'type' => 'done',
  3790. // 'script' => [],
  3791. // 'episode' => [],
  3792. // 'answer' => $fullContent,
  3793. // 'reasoning' => $fullReasoningContent,
  3794. // 'usage' => $usage,
  3795. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3796. // ];
  3797. // return;
  3798. // }
  3799. // 确认对话名称唯一性
  3800. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3801. $anime_name = $anime_name . '_' . date('YmdHis');
  3802. }
  3803. }else {
  3804. $anime_name = $user_anime_name;
  3805. }
  3806. $table_data = [
  3807. 'user_id' => $uid,
  3808. 'anime_name' => $anime_name,
  3809. 'model' => $model,
  3810. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3811. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3812. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3813. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3814. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3815. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3816. 'art_style_type' => $input_art_style,
  3817. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3818. 'status' => '解析完成',
  3819. 'content' => $content,
  3820. 'is_multi' => $is_multi,
  3821. 'ace_mode' => $ace_mode,
  3822. 'generate_status' => '待执行',
  3823. 'updated_at' => date('Y-m-d H:i:s')
  3824. ];
  3825. if ($table_data['content']) {
  3826. $chapters = splitContent($table_data['content']);
  3827. $chapter_count = count($chapters);
  3828. if ($chapter_count > 0) {
  3829. $table_data['start_episode_sequence'] = 1;
  3830. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3831. }
  3832. }
  3833. // 如果有剧本ID则进行绑定
  3834. if ($script_id) {
  3835. $table_data['script_id'] = $script_id;
  3836. }
  3837. $single_episode = [];
  3838. try {
  3839. DB::beginTransaction();
  3840. $now = date('Y-m-d H:i:s');
  3841. // 更新动漫大纲
  3842. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3843. if (!$boolen) {
  3844. dLog('deepseek')->info('动漫保存失败', $table_data);
  3845. Utils::throwError('20003:动漫保存失败');
  3846. }
  3847. // 保存对话记录
  3848. $records = [
  3849. [
  3850. 'uid' => $uid,
  3851. 'anime_id' => $anime_id,
  3852. 'sequence' => 0,
  3853. 'role' => 'user',
  3854. 'content' => $prompt,
  3855. 'created_at' => date('Y-m-d H:i:s'),
  3856. 'updated_at' => date('Y-m-d H:i:s')
  3857. ],
  3858. [
  3859. 'uid' => $uid,
  3860. 'anime_id' => $anime_id,
  3861. 'sequence' => 0,
  3862. 'role' => 'assistant',
  3863. 'content' => $fullContent,
  3864. 'created_at' => date('Y-m-d H:i:s'),
  3865. 'updated_at' => date('Y-m-d H:i:s')
  3866. ]
  3867. ];
  3868. // 保存对话记录
  3869. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3870. if (!$boolen3) {
  3871. Utils::throwError('20003:对话记录保存失败');
  3872. }
  3873. if ($is_single) {
  3874. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3875. if (empty($episode_arr['acts'])) {
  3876. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3877. }
  3878. $saveResult = $this->saveEpisodeVersionData(
  3879. $anime_id,
  3880. 1,
  3881. $episode_arr,
  3882. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3883. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3884. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3885. null,
  3886. null,
  3887. false,
  3888. $content,
  3889. $now
  3890. );
  3891. $single_episode = $saveResult['episode'];
  3892. $episode_id = $saveResult['episode_id'];
  3893. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3894. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3895. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3896. 'props' => json_encode($saveResult['merged_props'], 256),
  3897. 'updated_at' => $now
  3898. ]);
  3899. if ($boolen5 === false) {
  3900. Utils::throwError('20003:单剧集主表资源同步失败');
  3901. }
  3902. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3903. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3904. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3905. $episode_record_content = '确认分镜大纲';
  3906. if ($content !== '') {
  3907. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3908. }
  3909. $episode_records = [
  3910. [
  3911. 'uid' => $uid,
  3912. 'anime_id' => $anime_id,
  3913. 'role' => 'user',
  3914. 'content' => $episode_record_content,
  3915. 'sequence' => 1,
  3916. 'episode_id' => $episode_id,
  3917. 'created_at' => $now,
  3918. 'updated_at' => $now
  3919. ],
  3920. [
  3921. 'uid' => $uid,
  3922. 'anime_id' => $anime_id,
  3923. 'role' => 'assistant',
  3924. 'content' => $fullContent,
  3925. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3926. 'sequence' => 1,
  3927. 'episode_id' => $episode_id,
  3928. 'created_at' => $now,
  3929. 'updated_at' => $now
  3930. ]
  3931. ];
  3932. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3933. if (!$boolen4) {
  3934. Utils::throwError('20003:单剧集分镜记录保存失败');
  3935. }
  3936. }
  3937. }catch (\Exception $e) {
  3938. DB::rollBack();
  3939. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3940. yield [
  3941. 'type' => 'done',
  3942. 'answer' => $fullContent,
  3943. 'reasoning' => $fullReasoningContent,
  3944. 'usage' => $usage,
  3945. 'error' => $e->getMessage(),
  3946. ];
  3947. return;
  3948. }
  3949. DB::commit();
  3950. dLog('deepseek')->info('保存完毕');
  3951. if ($is_single && !empty($single_episode)) {
  3952. // $this->batchSetGlobalRoleImg([
  3953. // 'anime_id' => $anime_id,
  3954. // ]);
  3955. // $this->batchSetGlobalSceneImg([
  3956. // 'anime_id' => $anime_id,
  3957. // ]);
  3958. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3959. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3960. }
  3961. $table_data['anime_id'] = $anime_id;
  3962. $table_data['roles'] = json_decode($table_data['roles'], true);
  3963. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3964. // $table_data['episodes'] = $script_arr['episodes'];
  3965. unset($table_data['created_at']);
  3966. unset($table_data['updated_at']);
  3967. unset($table_data['status']);
  3968. dLog('deepseek')->info('开始返回');
  3969. yield [
  3970. 'type' => 'done',
  3971. 'script' => $table_data,
  3972. 'episode' => $single_episode,
  3973. 'answer' => $fullContent,
  3974. 'reasoning' => $fullReasoningContent,
  3975. 'usage' => $usage
  3976. ];
  3977. }
  3978. public function reGenerateAnime($data) {
  3979. $uid = Site::getUid();
  3980. $file = getProp($data, 'file');
  3981. $content = getProp($data, 'content', '');
  3982. $bid = getProp($data, 'bid', 0);
  3983. $script_id = getProp($data, 'script_id', 0);
  3984. $anime_id = getProp($data, 'anime_id');
  3985. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3986. if (!$anime) {
  3987. Utils::throwError('20003:该对话不存在');
  3988. }
  3989. $user_anime_name = getProp($anime, 'anime_name');
  3990. $prompt = getProp($data, 'prompt');
  3991. // 处理文本模型
  3992. $model = getProp($data, 'model');
  3993. if (!$model) {
  3994. // 用户没有输入,从anime表获取
  3995. $model = getProp($anime, 'model');
  3996. if (!$model) {
  3997. // anime表也没有,使用默认值
  3998. $model = 'doubao-seed-2-0-mini-260215';
  3999. }
  4000. }
  4001. // 验证模型是否在可用模型表中
  4002. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4003. $model = 'doubao-seed-2-0-mini-260215';
  4004. }
  4005. $is_multi = getProp($anime, 'is_multi', 1);
  4006. $is_single = (int)$is_multi !== 1;
  4007. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4008. if ($is_single) {
  4009. $episode_exists = DB::table('mp_anime_episodes')
  4010. ->where('anime_id', $anime_id)
  4011. ->where('sequence', 1)
  4012. ->exists();
  4013. if ($episode_exists) {
  4014. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4015. }
  4016. }
  4017. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4018. if ($prompt) {
  4019. $question .= "本次修改要求如下:\n{$prompt}";
  4020. }
  4021. // 提取文件内容
  4022. if ($file) {
  4023. $content = $this->extractFileContent($file);
  4024. if (!$content) {
  4025. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4026. }
  4027. } elseif ($script_id) {
  4028. $content = $this->getContentByScriptId($script_id);
  4029. if (!$content) {
  4030. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4031. }
  4032. } elseif ($bid) {
  4033. $content = $this->getContentByBid($bid);
  4034. if (!$content) {
  4035. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4036. }
  4037. } elseif ($content) {
  4038. $content = filterContent($content);
  4039. }else {
  4040. $content = filterContent(getProp($anime, 'content'));
  4041. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4042. $need_generate_content = true;
  4043. }
  4044. }
  4045. // 判断是否需要生成原文内容
  4046. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4047. // 如果需要生成原文内容,添加额外的要求
  4048. $content_generation_requirement = $need_generate_content
  4049. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4050. : "";
  4051. // 美术风格
  4052. $input_art_style = getProp($anime, 'art_style');
  4053. if (!$input_art_style) {
  4054. $input_art_style = getProp($data, 'art_style');
  4055. }
  4056. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4057. // 美术风格
  4058. if (!$mappedArtStyle) {
  4059. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4060. }else {
  4061. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4062. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4063. }else {
  4064. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4065. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4066. }
  4067. }
  4068. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4069. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4070. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4071. 中年女:邻居阿姨
  4072. 老年男:幽默大爷
  4073. 老年女:婆婆
  4074. 萌娃:奶气萌娃";
  4075. $system_message = ['role'=>'system', 'content'=>$is_single
  4076. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4077. 强制要求:
  4078. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4079. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4080. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4081. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4082. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4083. 普通要求:
  4084. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4085. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4086. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4087. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4088. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4089. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4090. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4091. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4092. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4093. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4094. 3.$mappedArtStyle_prompt\n\n
  4095. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4096. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4097. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4098. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4099. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4100. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4101. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4102. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4103. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4104. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4105. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4106. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4107. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4108. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4109. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4110. 示例如下:\n
  4111. ###剧本名:西昆仑
  4112. ###故事梗概
  4113. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4114. ###剧本亮点
  4115. 亮点1:绝境奇药,生死一线
  4116. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4117. 亮点2:结拜兄妹,化解尴尬
  4118. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4119. 亮点3:纤发夺命,情愫暗涌
  4120. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4121. ###人物关系
  4122. 阿雪与梁萧之间存在兄妹之情。
  4123. ###核心矛盾
  4124. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4125. ###主体列表
  4126. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4127. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4128. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4129. 姿态:站立。}{{甜心小美}}
  4130. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4131. 全景,正面拍摄,青年女性,亚洲人。
  4132. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4133. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4134. 姿态:站立。}{{阳光青年}}
  4135. ###美术风格
  4136. 基础画风风格词:厚涂古风
  4137. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4138. ###场景列表
  4139. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4140. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4141. 无人物。}
  4142. ###分镜剧本
  4143. ##第1幕:徐家老旧厨房 白天 室内
  4144. 分镜1
  4145. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4146. 场景:徐家老旧厨房
  4147. 构图设计:全景,低角度仰视
  4148. 运镜调度:手持拍摄
  4149. 配音角色:旁白
  4150. 出镜角色:许芸-校服装、徐母
  4151. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4152. 画面类型:普通画面
  4153. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4154. 分镜2
  4155. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4156. 场景:徐家老旧厨房
  4157. 构图设计:近景,徐母面部特写
  4158. 运镜调度:固定镜头
  4159. 配音角色:徐母
  4160. 出镜角色:徐母
  4161. 台词内容:问我夜不归宿死哪儿去了。
  4162. 画面类型:对口型
  4163. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4164. ##第2幕:徐家简陋客厅 黄昏 室内
  4165. 分镜3
  4166. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4167. 场景:徐家简陋客厅
  4168. 构图设计:全景,景深虚化
  4169. 运镜调度:固定镜头
  4170. 配音角色:旁白
  4171. 出镜角色:无
  4172. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4173. 画面类型:普通画面
  4174. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4175. 分镜4
  4176. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4177. 场景:徐家简陋客厅
  4178. 构图设计:特写,火车票
  4179. 运镜调度:固定镜头
  4180. 配音角色:旁白
  4181. 出镜角色:无
  4182. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4183. 画面类型:普通画面
  4184. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4185. "
  4186. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4187. 强制要求:\n
  4188. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4189. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4190. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4191. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4192. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4193. 普通要求:\n
  4194. 1.剧本名(必须生成)必须与文档内容高度相关
  4195. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4196. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4197. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4198. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4199. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4200. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4201. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4202. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4203. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4204. 4.$mappedArtStyle_prompt\n\n
  4205. 示例如下:\n
  4206. ###剧本名:西昆仑
  4207. ###故事梗概
  4208. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4209. ###剧本亮点
  4210. 亮点1:绝境奇药,生死一线
  4211. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4212. 亮点2:结拜兄妹,化解尴尬
  4213. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4214. 亮点3:纤发夺命,情愫暗涌
  4215. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4216. ###人物关系
  4217. 阿雪与梁萧之间存在兄妹之情。
  4218. ###核心矛盾
  4219. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4220. ###主体列表
  4221. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4222. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4223. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4224. 姿态:站立。}{{甜心小美}}
  4225. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4226. 全景,正面拍摄,青年女性,亚洲人。
  4227. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4228. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4229. 姿态:站立。}{{阳光青年}}
  4230. ###美术风格
  4231. 基础画风风格词:厚涂古风
  4232. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4233. ###场景列表
  4234. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4235. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4236. 无人物。}"];
  4237. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4238. $episode_count = $this->extractEpisodeNumber($prompt);
  4239. if ((int)getProp($anime, 'is_multi') !== 1) {
  4240. yield [
  4241. 'type' => 'done',
  4242. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4243. 'reasoning' => '',
  4244. 'usage' => []
  4245. ];
  4246. return;
  4247. }
  4248. if ($episode_count) {
  4249. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4250. $system_message = [
  4251. 'role' => 'system',
  4252. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4253. 强制要求:\n
  4254. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4255. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4256. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4257. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4258. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4259. 普通要求:\n
  4260. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4261. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4262. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4263. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4264. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4265. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4266. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4267. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4268. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4269. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4270. 示例如下:\n
  4271. ###剧本名:西昆仑
  4272. ###故事梗概
  4273. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4274. ###剧本亮点
  4275. 亮点1:绝境奇药,生死一线
  4276. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4277. 亮点2:结拜兄妹,化解尴尬
  4278. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4279. 亮点3:纤发夺命,情愫暗涌
  4280. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4281. ###人物关系
  4282. 阿雪与梁萧之间存在兄妹之情。
  4283. ###核心矛盾
  4284. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4285. ###主体列表
  4286. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4287. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4288. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4289. 姿态:站立。}{{甜心小美}}
  4290. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4291. 全景,正面拍摄,青年女性,亚洲人。
  4292. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4293. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4294. 姿态:站立。}{{阳光青年}}
  4295. ###美术风格
  4296. 基础画风风格词:厚涂古风
  4297. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4298. ###场景列表
  4299. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4300. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4301. 无人物。}
  4302. ###分集详细内容
  4303. ##第1章 重生
  4304. 我重生了。
  4305. 源于一个男人偏执的暗恋。
  4306. ##第2章 相救
  4307. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4308. 我眼睛扫向站在锅炉后的卞大伟。"
  4309. ];
  4310. // 构建消息
  4311. $messages = [
  4312. $system_message,
  4313. [
  4314. 'role' => 'user',
  4315. 'content' => "以下是文档内容:
  4316. {$content}
  4317. 用户问题:
  4318. {$question}"
  4319. ]
  4320. ];
  4321. }else {
  4322. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4323. // 构建消息
  4324. $messages = [
  4325. $system_message,
  4326. [
  4327. 'role' => 'user',
  4328. 'content' => "以下是文档内容:
  4329. {$content}
  4330. 用户问题:
  4331. {$question}"
  4332. ]
  4333. ];
  4334. }else {
  4335. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4336. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4337. return (array)$value;
  4338. })->toArray();
  4339. array_unshift($messages, $system_message);
  4340. $messages[] = [
  4341. 'role' => 'user',
  4342. 'content' => $prompt
  4343. ];
  4344. }
  4345. }
  4346. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4347. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4348. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4349. if ($model === 'deepseek-chat') {
  4350. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4351. $model = 'deepseek-v4-flash';
  4352. $thinkingMode = 'disabled';
  4353. } elseif ($model === 'deepseek-reasoner') {
  4354. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4355. $model = 'deepseek-v4-flash';
  4356. $thinkingMode = 'enabled';
  4357. }
  4358. $post_data = [
  4359. 'model' => $model,
  4360. 'messages' => $messages,
  4361. // 'max_tokens' => 8192,
  4362. 'temperature' => 0.7,
  4363. 'frequency_penalty' => 0,
  4364. 'presence_penalty' => 0,
  4365. 'response_format' => ['type' => 'text'],
  4366. 'thinking' => ['type' => $thinkingMode],
  4367. 'stream' => true // 启用流式输出
  4368. ];
  4369. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4370. // 根据模型类型选择调用方法
  4371. $fullContent = '';
  4372. $fullReasoningContent = '';
  4373. $usage = [];
  4374. // dd($post_data);
  4375. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4376. try {
  4377. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4378. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4379. } else if (in_array($model, $this->gpt_text_models)) {
  4380. // GPT-5.4 模型使用 TokenRouter API
  4381. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4382. } else {
  4383. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4384. }
  4385. // 验证返回值类型
  4386. if (!is_iterable($streamGenerator)) {
  4387. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4388. dLog('deepseek')->error('方法名流式生成器无效', [
  4389. 'generator_type' => $errorType,
  4390. 'model' => $model,
  4391. // 添加其他上下文信息
  4392. ]);
  4393. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4394. 'type' => $errorType,
  4395. 'model' => $model
  4396. ]);
  4397. yield [
  4398. 'type' => 'error',
  4399. // 根据方法返回相应的空数据结构
  4400. 'answer' => '',
  4401. 'reasoning' => '',
  4402. 'usage' => [],
  4403. 'error' => '接口返回数据异常,请重新请求'
  4404. ];
  4405. return;
  4406. }
  4407. // 处理流式输出
  4408. foreach ($streamGenerator as $chunk) {
  4409. if (isset($chunk['type'])) {
  4410. if ($chunk['type'] === 'done') {
  4411. $fullContent = $chunk['full_content'];
  4412. $fullReasoningContent = $chunk['full_reasoning'];
  4413. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4414. } else {
  4415. yield $chunk;
  4416. }
  4417. }
  4418. }
  4419. } catch (\Exception $e) {
  4420. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4421. 'model' => $model,
  4422. 'trace' => $e->getTraceAsString()
  4423. ]);
  4424. logDB('deepseek', 'error', '方法名流式处理失败', [
  4425. 'error' => $e->getMessage(),
  4426. 'model' => $model
  4427. ]);
  4428. yield [
  4429. 'type' => 'error',
  4430. // 根据方法返回相应的空数据结构
  4431. 'answer' => '',
  4432. 'reasoning' => '',
  4433. 'usage' => [],
  4434. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4435. ];
  4436. return;
  4437. }
  4438. dLog('deepseek')->info('完整内容: '.$fullContent);
  4439. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4440. // 处理完整内容并返回最终结果
  4441. $script_arr = [];
  4442. if ($fullContent) {
  4443. $script_arr = handleScriptContent($fullContent);
  4444. dLog('deepseek')->info('解析内容', $script_arr);
  4445. logDB('deepseek', 'info', '解析内容', $script_arr);
  4446. }
  4447. if (empty($script_arr['roles'])) {
  4448. // 未生成剧本相关内容,保存对话记录并返回提示
  4449. dLog('deepseek')->info('未生成剧本相关的内容');
  4450. try {
  4451. $now = date('Y-m-d H:i:s');
  4452. // 保存对话记录
  4453. $records = [
  4454. [
  4455. 'uid' => $uid,
  4456. 'anime_id' => $anime_id,
  4457. 'sequence' => 0,
  4458. 'role' => 'user',
  4459. 'content' => $prompt,
  4460. 'created_at' => $now,
  4461. 'updated_at' => $now
  4462. ],
  4463. [
  4464. 'uid' => $uid,
  4465. 'anime_id' => $anime_id,
  4466. 'sequence' => 0,
  4467. 'role' => 'assistant',
  4468. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4469. 'created_at' => $now,
  4470. 'updated_at' => $now
  4471. ]
  4472. ];
  4473. DB::table('mp_anime_records')->insert($records);
  4474. } catch (\Exception $e) {
  4475. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4476. }
  4477. yield [
  4478. 'type' => 'done',
  4479. 'script' => [],
  4480. 'episode' => [],
  4481. 'answer' => $fullContent,
  4482. 'reasoning' => $fullReasoningContent,
  4483. 'usage' => $usage,
  4484. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4485. ];
  4486. return;
  4487. }
  4488. // 替换美术风格
  4489. if ($mappedArtStyle !== '') {
  4490. $script_arr['art_style'] = $mappedArtStyle;
  4491. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4492. }
  4493. if ($user_anime_name != '新剧本策划') {
  4494. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4495. // 确认对话名称唯一性
  4496. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4497. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4498. }
  4499. }else {
  4500. $anime_name = $user_anime_name;
  4501. }
  4502. $table_data = [
  4503. 'user_id' => $uid,
  4504. 'model' => $model,
  4505. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4506. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4507. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4508. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4509. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4510. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4511. 'art_style_type' => $input_art_style,
  4512. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4513. 'status' => '解析完成',
  4514. 'generate_status' => '待执行',
  4515. 'updated_at' => date('Y-m-d H:i:s')
  4516. ];
  4517. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4518. // 如果是修改集数,则将content内容更新(会改变原文)
  4519. if (isset($episode_count) && $episode_count > 0) {
  4520. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4521. $table_data['start_episode_sequence'] = 1;
  4522. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4523. }else {
  4524. // 如果需要生成原文内容,从script_arr中提取
  4525. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4526. $table_data['content'] = $script_arr['content'];
  4527. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4528. if (!$table_data['content']) {
  4529. yield [
  4530. 'type' => 'done',
  4531. 'script' => [],
  4532. 'episode' => [],
  4533. 'answer' => $fullContent,
  4534. 'reasoning' => $fullReasoningContent,
  4535. 'usage' => $usage,
  4536. 'error' => '未生成剧本内容,请调整提示词再试'
  4537. ];
  4538. return;
  4539. }
  4540. }
  4541. if (isset($table_data['content']) && $table_data['content']) {
  4542. $chapters = splitContent($table_data['content']);
  4543. $chapter_count = count($chapters);
  4544. if ($chapter_count > 0) {
  4545. $table_data['start_episode_sequence'] = 1;
  4546. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4547. }
  4548. }
  4549. }
  4550. $single_episode = [];
  4551. try {
  4552. DB::beginTransaction();
  4553. $now = date('Y-m-d H:i:s');
  4554. // 更新动漫大纲
  4555. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4556. if (!$boolen) {
  4557. dLog('deepseek')->info('对话修改失败', $table_data);
  4558. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4559. Utils::throwError('20003:对话修改失败');
  4560. }
  4561. // 保存对话记录
  4562. $records = [
  4563. [
  4564. 'uid' => $uid,
  4565. 'anime_id' => $anime_id,
  4566. 'sequence' => 0,
  4567. 'role' => 'user',
  4568. 'content' => $prompt,
  4569. 'created_at' => $now,
  4570. 'updated_at' => $now
  4571. ],
  4572. [
  4573. 'uid' => $uid,
  4574. 'anime_id' => $anime_id,
  4575. 'sequence' => 0,
  4576. 'role' => 'assistant',
  4577. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4578. 'content' => $fullContent,
  4579. 'created_at' => $now,
  4580. 'updated_at' => $now
  4581. ]
  4582. ];
  4583. // 保存对话记录
  4584. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4585. if (!$boolen3) {
  4586. Utils::throwError('20003:对话记录保存失败');
  4587. }
  4588. // 单剧集模式:生成并保存剧集信息
  4589. if ($is_single) {
  4590. $anime_name = getProp($anime, 'anime_name', '未命名');
  4591. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4592. if (empty($episode_arr['acts'])) {
  4593. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4594. }
  4595. $saveResult = $this->saveEpisodeVersionData(
  4596. $anime_id,
  4597. 1,
  4598. $episode_arr,
  4599. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4600. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4601. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4602. null,
  4603. null,
  4604. false,
  4605. $content,
  4606. $now
  4607. );
  4608. $single_episode = $saveResult['episode'];
  4609. $episode_id = $saveResult['episode_id'];
  4610. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4611. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4612. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4613. 'props' => json_encode($saveResult['merged_props'], 256),
  4614. 'updated_at' => $now
  4615. ]);
  4616. if ($boolen5 === false) {
  4617. Utils::throwError('20003:单剧集主表资源同步失败');
  4618. }
  4619. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4620. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4621. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4622. $episode_record_content = '确认分镜大纲';
  4623. if ($content !== '') {
  4624. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4625. }
  4626. $episode_records = [
  4627. [
  4628. 'uid' => $uid,
  4629. 'anime_id' => $anime_id,
  4630. 'role' => 'user',
  4631. 'content' => $episode_record_content,
  4632. 'sequence' => 1,
  4633. 'episode_id' => $episode_id,
  4634. 'created_at' => $now,
  4635. 'updated_at' => $now
  4636. ],
  4637. [
  4638. 'uid' => $uid,
  4639. 'anime_id' => $anime_id,
  4640. 'role' => 'assistant',
  4641. 'content' => $fullContent,
  4642. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4643. 'sequence' => 1,
  4644. 'episode_id' => $episode_id,
  4645. 'created_at' => $now,
  4646. 'updated_at' => $now
  4647. ]
  4648. ];
  4649. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4650. if (!$boolen4) {
  4651. Utils::throwError('20003:单剧集分镜记录保存失败');
  4652. }
  4653. }
  4654. }catch (\Exception $e) {
  4655. DB::rollBack();
  4656. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4657. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4658. yield [
  4659. 'type' => 'done',
  4660. 'answer' => $fullContent,
  4661. 'reasoning' => $fullReasoningContent,
  4662. 'usage' => $usage,
  4663. 'error' => $e->getMessage(),
  4664. ];
  4665. return;
  4666. }
  4667. DB::commit();
  4668. dLog('deepseek')->info('保存完毕');
  4669. if ($is_single && !empty($single_episode)) {
  4670. // $this->batchSetGlobalRoleImg([
  4671. // 'anime_id' => $anime_id,
  4672. // ]);
  4673. // $this->batchSetGlobalSceneImg([
  4674. // 'anime_id' => $anime_id,
  4675. // ]);
  4676. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4677. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4678. }
  4679. $table_data['anime_id'] = $anime_id;
  4680. $table_data['roles'] = json_decode($table_data['roles'], true);
  4681. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4682. unset($table_data['updated_at']);
  4683. unset($table_data['status']);
  4684. yield [
  4685. 'type' => 'done',
  4686. 'script' => $table_data,
  4687. 'episode' => $single_episode,
  4688. 'answer' => $fullContent,
  4689. 'reasoning' => $fullReasoningContent,
  4690. 'usage' => $usage
  4691. ];
  4692. }
  4693. public function chat($data) {
  4694. $uid = Site::getUid();
  4695. $anime_id = getProp($data, 'anime_id');
  4696. $file = getProp($data, 'file');
  4697. $content = getProp($data, 'content', '');
  4698. $bid = getProp($data, 'bid', 0);
  4699. $script_id = getProp($data, 'script_id', 0);
  4700. $episode_number = getProp($data, 'episode_number', 1);
  4701. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4702. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4703. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4704. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4705. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4706. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4707. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4708. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4709. $roles = is_array($roles) ? $roles : [];
  4710. $scenes = is_array($scenes) ? $scenes : [];
  4711. // 获取最后一集序号
  4712. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4713. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4714. // 转换主体列表和场景列表的格式
  4715. // 获取参考主体或场景
  4716. if ((int)$episode_number === 1) {
  4717. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4718. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4719. }else {
  4720. $prev_episode_number = $episode_number - 1;
  4721. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4722. }
  4723. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4724. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4725. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4726. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4727. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4728. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4729. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4730. 中年女:邻居阿姨
  4731. 老年男:幽默大爷
  4732. 老年女:婆婆
  4733. 萌娃:奶气萌娃";
  4734. if ($roles_content) {
  4735. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4736. 主体范围:\n {$roles_content}\n
  4737. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4738. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4739. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4740. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4741. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4742. }else {
  4743. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4744. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4745. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4746. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4747. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4748. }
  4749. if ($scenes_content) {
  4750. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4751. 场景范围:\n {$scenes_content}\n
  4752. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4753. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4754. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4755. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4756. }else {
  4757. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4758. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4759. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4760. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4761. }
  4762. // 提取文件内容
  4763. if ($file) {
  4764. $uploaded_content = $this->extractFileContent($file);
  4765. if (!$uploaded_content) {
  4766. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4767. }
  4768. } elseif ($script_id) {
  4769. $uploaded_content = $this->getContentByScriptId($script_id);
  4770. if (!$uploaded_content) {
  4771. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4772. }
  4773. } elseif ($bid) {
  4774. $uploaded_content = $this->getContentByBid($bid);
  4775. if (!$uploaded_content) {
  4776. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4777. }
  4778. } elseif ($content) {
  4779. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4780. }
  4781. // elseif ($prompt) {
  4782. // $uploaded_content = filterContent($prompt);
  4783. // }
  4784. else {
  4785. $uploaded_content = '';
  4786. }
  4787. $input_art_style = getProp($anime, 'art_style');
  4788. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4789. // 美术风格
  4790. if (!$mappedArtStyle) {
  4791. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4792. }else {
  4793. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4794. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4795. }else {
  4796. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4797. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4798. }
  4799. }
  4800. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4801. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4802. // 强制要求:
  4803. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4804. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4805. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4806. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4807. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4808. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4809. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4810. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4811. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4812. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4813. // - 分镜要和场景列表、人物主体保持一致\n
  4814. // 普通要求:
  4815. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4816. // {$role_demo}
  4817. // {$scene_demo}
  4818. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4819. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4820. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4821. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4822. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4823. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4824. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4825. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4826. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4827. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4828. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4829. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4830. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4831. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4832. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4833. // 5.$mappedArtStyle_prompt\n\n
  4834. // 示例格式:\n
  4835. // 第1集:隐形的守护者
  4836. // ###故事梗概
  4837. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4838. // ###美术风格
  4839. // 基础画风风格词:韩漫二次元
  4840. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4841. // ###主体列表
  4842. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4843. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4844. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4845. // ###场景列表
  4846. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4847. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4848. // 无人物。}
  4849. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4850. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4851. // 无人物。}
  4852. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4853. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4854. // 无人物。}
  4855. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4856. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4857. // 无人物。}
  4858. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4859. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4860. // 无人物。}
  4861. // ###分镜剧本
  4862. // ##第1幕:徐家老旧厨房 白天 室内
  4863. // 分镜1
  4864. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4865. // 场景:徐家老旧厨房
  4866. // 构图设计:全景,低角度仰视
  4867. // 运镜调度:手持拍摄
  4868. // 配音角色:旁白
  4869. // 出镜角色:许芸-校服装、徐母
  4870. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4871. // 画面类型:普通画面
  4872. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4873. // 分镜2
  4874. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4875. // 场景:徐家老旧厨房
  4876. // 构图设计:近景,徐母面部特写
  4877. // 运镜调度:固定镜头
  4878. // 配音角色:徐母
  4879. // 出镜角色:徐母
  4880. // 台词内容:问我夜不归宿死哪儿去了。
  4881. // 画面类型:对口型
  4882. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4883. // ##第2幕:徐家简陋客厅 黄昏 室内
  4884. // 分镜3
  4885. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4886. // 场景:徐家简陋客厅
  4887. // 构图设计:全景,景深虚化
  4888. // 运镜调度:固定镜头
  4889. // 配音角色:旁白
  4890. // 出镜角色:无
  4891. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4892. // 画面类型:普通画面
  4893. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4894. // 分镜4
  4895. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4896. // 场景:徐家简陋客厅
  4897. // 构图设计:特写,火车票
  4898. // 运镜调度:固定镜头
  4899. // 配音角色:旁白
  4900. // 出镜角色:无
  4901. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4902. // 画面类型:普通画面
  4903. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4904. // \n\n";
  4905. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4906. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4907. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4908. 普通要求:
  4909. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4910. {$role_demo}
  4911. {$scene_demo}
  4912. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4913. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4914. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4915. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4916. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4917. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4918. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4919. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4920. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4921. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4922. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4923. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4924. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4925. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4926. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4927. 5.$mappedArtStyle_prompt
  4928. 6.《情绪-视听语言映射表》:
  4929. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4930. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4931. -----|---------|------------|----------------
  4932. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4933. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4934. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4935. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4936. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4937. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4938. -----|---------|------------|----------------
  4939. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4940. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4941. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4942. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4943. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4944. --------|---------|--------------|-------------
  4945. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4946. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4947. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4948. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4949. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4950. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4951. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4952. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4953. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4954. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4955. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4956. -----|---------|------------|------------
  4957. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4958. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4959. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4960. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4961. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4962. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4963. --------|---------|--------------|----------
  4964. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4965. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4966. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4967. 6.6 声音设计与潜意识影响 (Soundscape)
  4968. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4969. -----|---------|------------|------------------
  4970. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4971. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4972. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4973. 理论基石:
  4974. - The Five C's of Cinematography by Joseph V. Mascelli
  4975. - Film Art: An Introduction by David Bordwell
  4976. - Sight, Sound, Motion by Herbert Zettl
  4977. - Notes on the Cinematograph by Robert Bresson
  4978. \n\n
  4979. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4980. 示例格式:\n
  4981. 第1集:隐形的守护者
  4982. ###故事梗概
  4983. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4984. ###美术风格
  4985. 基础画风风格词:韩漫二次元
  4986. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4987. ###主体列表
  4988. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4989. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4990. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4991. ###场景列表
  4992. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4993. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4994. 无人物。}
  4995. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4996. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4997. 无人物。}
  4998. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4999. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5000. 无人物。}
  5001. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5002. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5003. 无人物。}
  5004. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5005. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5006. 无人物。}
  5007. ###分镜剧本
  5008. ##第1幕:徐家老旧厨房 白天 室内
  5009. 分镜1
  5010. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5011. 场景:徐家老旧厨房
  5012. 构图设计:全景,低角度仰视
  5013. 运镜调度:手持拍摄
  5014. 配音角色:旁白
  5015. 出镜角色:许芸-校服装、徐母
  5016. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5017. 画面类型:普通画面
  5018. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5019. 分镜2
  5020. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5021. 场景:徐家老旧厨房
  5022. 构图设计:近景,徐母面部特写
  5023. 运镜调度:固定镜头
  5024. 配音角色:徐母
  5025. 出镜角色:徐母
  5026. 台词内容:问我夜不归宿死哪儿去了。
  5027. 画面类型:对口型
  5028. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5029. ##第2幕:徐家简陋客厅 黄昏 室内
  5030. 分镜3
  5031. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5032. 场景:徐家简陋客厅
  5033. 构图设计:全景,景深虚化
  5034. 运镜调度:固定镜头
  5035. 配音角色:旁白
  5036. 出镜角色:无
  5037. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5038. 画面类型:普通画面
  5039. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5040. 分镜4
  5041. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5042. 场景:徐家简陋客厅
  5043. 构图设计:特写,火车票
  5044. 运镜调度:固定镜头
  5045. 配音角色:旁白
  5046. 出镜角色:无
  5047. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5048. 画面类型:普通画面
  5049. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5050. \n\n";
  5051. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5052. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5053. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5054. $prompt = $origin_prompt;
  5055. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5056. // 获取章节内容
  5057. $full_content = getProp($anime, 'content');
  5058. if ($uploaded_content) {
  5059. $full_content = $uploaded_content;
  5060. }
  5061. // 根据章节内容拆分章节
  5062. $chapters = splitContent($full_content);
  5063. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5064. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5065. $messages = [];
  5066. if ($prompt == '确认分镜大纲') {
  5067. // 暂时保留
  5068. $content = $chapter_content;
  5069. if ($is_single) $content = $full_content; // 单剧集使用全文
  5070. if (!$content) {
  5071. Utils::throwError('20003:章节内容无法获取,请确认');
  5072. }
  5073. $question = $is_single
  5074. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5075. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5076. // 构建消息
  5077. $messages[] =
  5078. [
  5079. 'role' => 'user',
  5080. 'content' => $question
  5081. ];
  5082. }else if ($prompt == '继续策划下一集') {
  5083. if ($is_single) {
  5084. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5085. }
  5086. $content = $chapter_content;
  5087. if (!$content) {
  5088. Utils::throwError('20003:章节内容无法获取,请确认');
  5089. }
  5090. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5091. // 获取上一集最后记录
  5092. $prev_sequence = $episode_number - 1;
  5093. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5094. // 构建消息
  5095. $messages[] =
  5096. [
  5097. 'role' => 'user',
  5098. 'content' => $question
  5099. ];
  5100. }else {
  5101. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5102. if (!$content) {
  5103. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5104. }
  5105. if (!$content) {
  5106. Utils::throwError('20003:章节内容无法获取,请确认');
  5107. }
  5108. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5109. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5110. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5111. if ($origin_prompt) {
  5112. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5113. }
  5114. $messages[] =
  5115. [
  5116. 'role' => 'user',
  5117. 'content' => $question
  5118. ];
  5119. }
  5120. // 处理文本模型
  5121. $model = getProp($data, 'model');
  5122. if (!$model) {
  5123. // 用户没有输入,从anime表获取
  5124. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5125. $model = getProp($anime, 'model');
  5126. if (!$model) {
  5127. // anime表也没有,使用默认值
  5128. $model = 'doubao-seed-2-0-mini-260215';
  5129. }
  5130. }
  5131. // 验证模型是否在可用模型表中
  5132. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5133. $model = 'doubao-seed-2-0-mini-260215';
  5134. }
  5135. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5136. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5137. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5138. if ($model === 'deepseek-chat') {
  5139. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5140. $model = 'deepseek-v4-flash';
  5141. $thinkingMode = 'disabled';
  5142. } elseif ($model === 'deepseek-reasoner') {
  5143. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5144. $model = 'deepseek-v4-flash';
  5145. $thinkingMode = 'enabled';
  5146. }
  5147. $post_data = [
  5148. 'model' => $model,
  5149. 'messages' => $messages,
  5150. // 'max_tokens' => 8192,
  5151. 'temperature' => 0.2,
  5152. 'frequency_penalty' => 0,
  5153. 'presence_penalty' => 0,
  5154. 'response_format' => ['type' => 'text'],
  5155. 'thinking' => ['type' => $thinkingMode],
  5156. 'stream' => true // 启用流式输出
  5157. ];
  5158. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5159. // 根据模型类型选择调用方法
  5160. $fullContent = '';
  5161. $fullReasoningContent = '';
  5162. $usage = [];
  5163. try {
  5164. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5165. // DeepSeek 官方模型使用 DeepSeek API
  5166. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5167. } else if (in_array($model, $this->gpt_text_models)) {
  5168. // GPT-5.4 模型使用 TokenRouter API
  5169. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5170. } else {
  5171. // 其他模型使用火山引擎API
  5172. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5173. }
  5174. // 验证返回值类型
  5175. if (!is_iterable($streamGenerator)) {
  5176. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5177. dLog('deepseek')->error('chat流式生成器无效', [
  5178. 'generator_type' => $errorType,
  5179. 'model' => $model,
  5180. 'anime_id' => $anime_id,
  5181. 'episode_number' => $episode_number
  5182. ]);
  5183. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5184. 'type' => $errorType,
  5185. 'model' => $model
  5186. ]);
  5187. yield [
  5188. 'type' => 'error',
  5189. 'episode' => [],
  5190. 'answer' => '',
  5191. 'reasoning' => '',
  5192. 'usage' => [],
  5193. 'error' => '接口返回数据异常,请重新请求'
  5194. ];
  5195. return;
  5196. }
  5197. // 处理流式输出
  5198. foreach ($streamGenerator as $chunk) {
  5199. if (isset($chunk['type'])) {
  5200. if ($chunk['type'] === 'done') {
  5201. // 最终结果
  5202. $fullContent = $chunk['full_content'];
  5203. $fullReasoningContent = $chunk['full_reasoning'];
  5204. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5205. } else {
  5206. // 逐块yield数据
  5207. yield $chunk;
  5208. }
  5209. }
  5210. }
  5211. } catch (\Exception $e) {
  5212. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5213. 'model' => $model,
  5214. 'anime_id' => $anime_id,
  5215. 'episode_number' => $episode_number,
  5216. 'trace' => $e->getTraceAsString()
  5217. ]);
  5218. logDB('deepseek', 'error', 'chat流式处理失败', [
  5219. 'error' => $e->getMessage(),
  5220. 'model' => $model
  5221. ]);
  5222. yield [
  5223. 'type' => 'error',
  5224. 'episode' => [],
  5225. 'answer' => '',
  5226. 'reasoning' => '',
  5227. 'usage' => [],
  5228. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5229. ];
  5230. return;
  5231. }
  5232. dLog('deepseek')->info('完整内容: '.$fullContent);
  5233. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5234. // 处理完整内容并返回最终结果
  5235. $episode_arr = handleEpisodeContent($fullContent);
  5236. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5237. if (empty($episode_arr['acts'])) {
  5238. // 未生成剧本相关内容,保存对话记录并返回提示
  5239. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5240. try {
  5241. $now = date('Y-m-d H:i:s');
  5242. // 保存对话记录
  5243. $records = [
  5244. [
  5245. 'uid' => $uid,
  5246. 'anime_id' => $anime_id,
  5247. 'sequence' => $episode_number,
  5248. 'role' => 'user',
  5249. 'content' => $prompt,
  5250. 'created_at' => $now,
  5251. 'updated_at' => $now
  5252. ],
  5253. [
  5254. 'uid' => $uid,
  5255. 'anime_id' => $anime_id,
  5256. 'sequence' => $episode_number,
  5257. 'role' => 'assistant',
  5258. 'content' => $fullContent,
  5259. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5260. 'created_at' => $now,
  5261. 'updated_at' => $now
  5262. ]
  5263. ];
  5264. DB::table('mp_anime_records')->insert($records);
  5265. } catch (\Exception $e) {
  5266. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5267. }
  5268. yield [
  5269. 'type' => 'done',
  5270. 'episode' => [],
  5271. 'answer' => $fullContent,
  5272. 'reasoning' => $fullReasoningContent,
  5273. 'usage' => $usage,
  5274. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5275. ];
  5276. return;
  5277. }
  5278. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5279. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5280. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5281. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5282. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5283. $existing_props = is_array($existing_props) ? $existing_props : [];
  5284. $now = date('Y-m-d H:i:s');
  5285. try {
  5286. DB::beginTransaction();
  5287. $saveResult = $this->saveEpisodeVersionData(
  5288. $anime_id,
  5289. $episode_number,
  5290. $episode_arr,
  5291. $existing_roles,
  5292. $existing_scenes,
  5293. $existing_props,
  5294. $current_episode,
  5295. $base_episode,
  5296. $is_regenerate_version,
  5297. $content,
  5298. $now
  5299. );
  5300. $episode = $saveResult['episode'];
  5301. $episode_id = $saveResult['episode_id'];
  5302. $merged_roles = $saveResult['merged_roles'];
  5303. $merged_scenes = $saveResult['merged_scenes'];
  5304. $merged_props = $saveResult['merged_props'];
  5305. $record_content = $origin_prompt;
  5306. if ($uploaded_content !== '') {
  5307. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5308. }
  5309. $records = [
  5310. [
  5311. 'uid' => $uid,
  5312. 'anime_id' => $anime_id,
  5313. 'role' => 'user',
  5314. 'content' => $record_content,
  5315. 'sequence' => $episode_number,
  5316. 'episode_id' => $episode_id,
  5317. 'created_at' => $now,
  5318. 'updated_at' => $now
  5319. ],
  5320. [
  5321. 'uid' => $uid,
  5322. 'anime_id' => $anime_id,
  5323. 'role' => 'assistant',
  5324. 'content' => $fullContent,
  5325. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5326. 'sequence' => $episode_number,
  5327. 'episode_id' => $episode_id,
  5328. 'created_at' => $now,
  5329. 'updated_at' => $now
  5330. ]
  5331. ];
  5332. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5333. if (!$boolen4) {
  5334. Utils::throwError('20003:对话记录保存失败');
  5335. }
  5336. // 保存模型和内容到anime表
  5337. $update_anime_data = [
  5338. 'model' => $model,
  5339. 'updated_at' => $now
  5340. ];
  5341. if ($uploaded_content) {
  5342. $update_anime_data['content'] = $uploaded_content;
  5343. }
  5344. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5345. }catch (\Exception $e) {
  5346. DB::rollBack();
  5347. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5348. yield [
  5349. 'type' => 'done',
  5350. 'answer' => $fullContent,
  5351. 'reasoning' => $fullReasoningContent,
  5352. 'usage' => $usage,
  5353. 'error' => $e->getMessage(),
  5354. ];
  5355. return;
  5356. }
  5357. DB::commit();
  5358. if ($is_global_generate_pics) {
  5359. // // 批量生成全局角色图片
  5360. // $this->batchSetGlobalRoleImg([
  5361. // 'anime_id' => $anime_id,
  5362. // ], true);
  5363. // // 批量生成全局场景图片
  5364. // $this->batchSetGlobalSceneImg([
  5365. // 'anime_id' => $anime_id,
  5366. // ], true);
  5367. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5368. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5369. }
  5370. $episode['episode_id'] = $episode_id;
  5371. $episode['roles'] = $merged_roles;
  5372. $episode['scenes'] = $merged_scenes;
  5373. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5374. yield [
  5375. 'type' => 'done',
  5376. 'episode' => $episode,
  5377. 'answer' => $fullContent,
  5378. 'reasoning' => $fullReasoningContent,
  5379. 'usage' => $usage
  5380. ];
  5381. }
  5382. public function addChatForAce($data) {
  5383. $uid = Site::getUid();
  5384. $anime_id = getProp($data, 'anime_id');
  5385. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5386. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5387. if (!$anime) Utils::throwError('20003:对话不存在');
  5388. $file = getProp($data, 'file');
  5389. $content = getProp($data, 'content', '');
  5390. $bid = getProp($data, 'bid', 0);
  5391. $script_id = getProp($data, 'script_id', 0);
  5392. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5393. $prompt = getProp($data, 'prompt');
  5394. $is_multi = getProp($anime, 'is_multi');
  5395. $is_single = (int)$is_multi !== 1;
  5396. $extra_products = getProp($data, 'products', []);
  5397. if (!$extra_products) {
  5398. $extra_products = getProp($anime, 'extra_products');
  5399. if ($extra_products) {
  5400. $extra_products = json_decode($extra_products, true);
  5401. }else {
  5402. $extra_products = [];
  5403. }
  5404. }else {
  5405. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5406. }
  5407. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5408. $anime_script_id = getProp($anime, 'script_id');
  5409. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5410. $cpid = Site::getCpid();
  5411. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5412. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5413. ->where('mapping.script_id', $anime_script_id)
  5414. ->where('product.cpid', $cpid)
  5415. ->where('product.is_deleted', 0);
  5416. $mappings = $script_products_mappings->select(
  5417. 'mapping.product_id',
  5418. 'mapping.episode_number',
  5419. 'product.product_name',
  5420. 'product.type',
  5421. 'product.product',
  5422. 'product.pic_prompt',
  5423. 'product.url',
  5424. 'product.pic_task_id',
  5425. 'product.pic_task_status',
  5426. 'product.three_view_image_url'
  5427. )
  5428. ->get();
  5429. // 按 product_id 分组,合并 episode_number
  5430. $productMap = [];
  5431. foreach ($mappings as $item) {
  5432. $product_id = $item->product_id;
  5433. $product_name = $item->product_name;
  5434. // 处理product_name两边的符号
  5435. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5436. if (!isset($productMap[$product_id])) {
  5437. $productMap[$product_id] = [
  5438. 'product_id' => $product_id,
  5439. 'product_name' => $product_name,
  5440. 'type' => (int)$item->type,
  5441. 'product' => (int)$item->product,
  5442. 'pic_prompt' => $item->pic_prompt,
  5443. 'url' => $item->url,
  5444. 'pic_task_id' => $item->pic_task_id,
  5445. 'pic_task_status' => $item->pic_task_status,
  5446. 'episode_numbers' => [],
  5447. ];
  5448. }
  5449. // 添加 episode_number(去重)
  5450. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5451. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5452. }
  5453. }
  5454. // 将查询到的剧本资产合并到extra_products中
  5455. // 先构建extra_products的索引(以product_id为key,用于去重)
  5456. $extraProductsMap = [];
  5457. foreach ($extra_products as $item) {
  5458. $key = getProp($item, 'product_id');
  5459. if ($key) {
  5460. $extraProductsMap[$key] = $item;
  5461. }
  5462. }
  5463. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5464. foreach ($productMap as $product) {
  5465. $product_id = $product['product_id'];
  5466. // 如果不存在则添加(不带episode_number信息)
  5467. if (!isset($extraProductsMap[$product_id])) {
  5468. $extraProductsMap[$product_id] = [
  5469. 'product_id' => $product['product_id'],
  5470. 'product_name' => $product['product_name'],
  5471. 'type' => $product['type'],
  5472. 'product' => $product['product'],
  5473. 'pic_prompt' => $product['pic_prompt'],
  5474. 'url' => $product['url'],
  5475. 'pic_task_id' => $product['pic_task_id'],
  5476. 'pic_task_status' => $product['pic_task_status'],
  5477. ];
  5478. }
  5479. }
  5480. // 重新赋值给extra_products
  5481. $extra_products = array_values($extraProductsMap);
  5482. }
  5483. $user_anime_name = getProp($anime, 'anime_name');
  5484. // 处理提示词
  5485. if ($prompt && $extra_products) {
  5486. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5487. foreach($extra_products as $item) {
  5488. $product_name = getProp($item, 'product_name');
  5489. if ($product_name) {
  5490. // 替换 {product_name} 为 product_name
  5491. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5492. }
  5493. }
  5494. }
  5495. // 处理文本模型
  5496. $model = getProp($data, 'model');
  5497. if (!$model) {
  5498. // 用户没有输入,从anime表获取
  5499. $model = getProp($anime, 'model');
  5500. if (!$model) {
  5501. // anime表也没有,使用默认值
  5502. $model = 'deepseek-v4-pro';
  5503. }
  5504. }
  5505. // 验证模型是否在可用模型表中
  5506. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5507. $model = 'deepseek-v4-pro';
  5508. }
  5509. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5510. if ($prompt) {
  5511. $question .= "本次修改要求如下:\n{$prompt}";
  5512. }
  5513. // if (!$file && !$content && !$bid) {
  5514. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5515. // }
  5516. // 提取文件内容
  5517. if ($file) {
  5518. $content = $this->extractFileContent($file);
  5519. if (!$content) {
  5520. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5521. }
  5522. } elseif ($script_id) {
  5523. $content = $this->getContentByScriptId($script_id);
  5524. if (!$content) {
  5525. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5526. }
  5527. } elseif ($bid) {
  5528. $content = $this->getContentByBid($bid);
  5529. if (!$content) {
  5530. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5531. }
  5532. } elseif ($content) {
  5533. $content = filterContent($content);
  5534. } else {
  5535. $content = getProp($anime, 'content');
  5536. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5537. $need_generate_content = true;
  5538. }
  5539. }
  5540. // 美术风格
  5541. $input_art_style = getProp($data, 'art_style');
  5542. if (!$input_art_style) {
  5543. $mappedArtStyle = getProp($anime, 'art_style');
  5544. }else {
  5545. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5546. }
  5547. // 判断是否需要生成原文内容
  5548. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5549. // 如果需要生成原文内容,添加额外的要求
  5550. $content_generation_requirement = $need_generate_content
  5551. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5552. : "";
  5553. // 美术风格
  5554. if (!$mappedArtStyle) {
  5555. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5556. }else {
  5557. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5558. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5559. }else {
  5560. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5561. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5562. }
  5563. }
  5564. // 构建主体、场景和道具提示词
  5565. $extra_role_prompt = "\n";
  5566. $extra_scene_prompt = "\n";
  5567. $extra_prop_prompt = "\n";
  5568. $ref_products = []; // 参考资产
  5569. if ($extra_products) {
  5570. foreach($extra_products as $item) {
  5571. $product = getProp($item, 'product');
  5572. $product_name = getProp($item, 'product_name');
  5573. if ($product_name == '旁白') continue;
  5574. $ref_products[$product_name] = $item;
  5575. $pic_prompt = getProp($item, 'pic_prompt');
  5576. if ((int)$product === 1) {
  5577. // 拼接角色信息
  5578. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5579. } elseif ((int)$product === 2) {
  5580. // 拼接场景信息
  5581. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5582. } elseif ((int)$product === 3) {
  5583. // 拼接道具信息
  5584. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5585. }
  5586. }
  5587. // 优化提示词,融入剧本
  5588. if (!empty(trim($extra_role_prompt))) {
  5589. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5590. }
  5591. if (!empty(trim($extra_scene_prompt))) {
  5592. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5593. }
  5594. if (!empty(trim($extra_prop_prompt))) {
  5595. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5596. }
  5597. }
  5598. if ($anime_script_id && $is_single) {
  5599. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5600. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5601. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5602. }else {
  5603. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5604. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5605. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5606. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5607. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5608. {$extra_role_prompt}";
  5609. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5610. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5611. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5612. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5613. {$extra_scene_prompt}";
  5614. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5615. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5616. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5617. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5618. {$extra_prop_prompt}";
  5619. }
  5620. $systemPrompt = $is_single
  5621. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5622. 强制要求:
  5623. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5624. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5625. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5626. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5627. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5628. 普通要求:
  5629. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5630. $role_demo
  5631. $scene_demo
  5632. $prop_demo
  5633. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5634. 5.1片段分割逻辑(优先级从高到低):
  5635. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5636. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5637. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5638. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5639. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5640. - 片段数量格式为: 片段数量:8
  5641. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5642. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5643. 5.3分镜结构:每个分镜包含以下字段:
  5644. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5645. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5646. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5647. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5648. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5649. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5650. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5651. - 运镜:场景+画面描述+运镜
  5652. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5653. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5654. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5655. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5656. 6.{$mappedArtStyle_prompt}\n\n
  5657. 示例如下:\n
  5658. ###剧本名:西昆仑
  5659. ###故事梗概
  5660. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5661. ###剧本亮点
  5662. 亮点1:绝境奇药,生死一线
  5663. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5664. 亮点2:结拜兄妹,化解尴尬
  5665. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5666. 亮点3:纤发夺命,情愫暗涌
  5667. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5668. ###人物关系
  5669. 阿雪与梁萧之间存在兄妹之情。
  5670. ###核心矛盾
  5671. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5672. ###主体列表
  5673. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5674. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5675. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5676. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5677. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5678. 全景,正面拍摄,青年女性,亚洲人。
  5679. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5680. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5681. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5682. ###美术风格
  5683. 基础画风风格词:厚涂古风
  5684. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5685. ###场景列表
  5686. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5687. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5688. 无人物。}
  5689. ###分段剧本
  5690. 片段数量:8
  5691. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5692. ##片段1
  5693. 时长:12s
  5694. 分镜1
  5695. 出场角色:刀疤脸
  5696. 场景:边境小镇街道
  5697. 出场道具:酒杯-高脚杯
  5698. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5699. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5700. 配音台词:
  5701. 背景音效:
  5702. 分镜2
  5703. 出场角色:刀疤脸
  5704. 场景:悦来酒馆
  5705. 出场道具:酒杯-高脚杯
  5706. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5707. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5708. 配音台词:
  5709. 背景音效:
  5710. 分镜3
  5711. 出场角色:刀疤脸
  5712. 场景:悦来酒馆
  5713. 出场道具:酒杯-高脚杯
  5714. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5715. 运镜:从中景推向令牌特写。
  5716. 配音台词:
  5717. 背景音效:
  5718. 分镜4
  5719. 出场角色:刀疤脸
  5720. 场景:悦来酒馆
  5721. 出场道具:酒杯-高脚杯
  5722. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5723. 运镜:极速推向酒水溅起的瞬间。
  5724. 配音台词:
  5725. 背景音效:
  5726. 分镜5
  5727. 出场角色:刀疤脸
  5728. 场景:悦来酒馆
  5729. 出场道具:酒杯-高脚杯
  5730. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5731. 运镜:固定机位,利用倾斜构图制造压迫感。
  5732. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5733. 背景音效:
  5734. \n\n"
  5735. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5736. 强制要求:\n
  5737. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5738. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5739. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5740. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5741. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5742. 普通要求:\n
  5743. 1.剧本名(必须生成)必须与文档内容高度相关
  5744. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5745. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5746. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5747. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5748. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5749. {$extra_role_prompt}
  5750. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5751. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5752. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5753. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5754. {$extra_scene_prompt}
  5755. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5756. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5757. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5758. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5759. {$extra_prop_prompt}
  5760. 5.{$mappedArtStyle_prompt}\n\n
  5761. 示例如下:\n
  5762. ###剧本名:西昆仑
  5763. ###故事梗概
  5764. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5765. ###剧本亮点
  5766. 亮点1:绝境奇药,生死一线
  5767. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5768. 亮点2:结拜兄妹,化解尴尬
  5769. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5770. 亮点3:纤发夺命,情愫暗涌
  5771. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5772. ###人物关系
  5773. 阿雪与梁萧之间存在兄妹之情。
  5774. ###核心矛盾
  5775. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5776. ###主体列表
  5777. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5778. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5779. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5780. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5781. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5782. 全景,正面拍摄,青年女性,亚洲人。
  5783. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5784. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5785. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5786. ###美术风格
  5787. 基础画风风格词:厚涂古风
  5788. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5789. ###场景列表
  5790. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5791. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5792. 无人物。}
  5793. ###道具列表
  5794. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5795. // 构建消息
  5796. $messages = [
  5797. [
  5798. 'role' => 'system',
  5799. 'content' => $systemPrompt
  5800. ],
  5801. [
  5802. 'role' => 'user',
  5803. 'content' => "以下是文档内容:
  5804. {$content}
  5805. 用户问题:
  5806. {$question}"
  5807. ]
  5808. ];
  5809. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5810. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5811. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5812. if ($model === 'deepseek-chat') {
  5813. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5814. $model = 'deepseek-v4-flash';
  5815. $thinkingMode = 'disabled';
  5816. } elseif ($model === 'deepseek-reasoner') {
  5817. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5818. $model = 'deepseek-v4-flash';
  5819. $thinkingMode = 'enabled';
  5820. }
  5821. $post_data = [
  5822. 'model' => $model,
  5823. 'messages' => $messages,
  5824. // 'max_tokens' => 8192,
  5825. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5826. 'frequency_penalty' => 0,
  5827. 'presence_penalty' => 0,
  5828. 'response_format' => ['type' => 'text'],
  5829. 'thinking' => ['type'=>$thinkingMode],
  5830. 'stream' => true // 启用流式输出
  5831. ];
  5832. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5833. // 根据模型类型选择调用方法
  5834. $fullContent = '';
  5835. $fullReasoningContent = '';
  5836. $usage = [];
  5837. try {
  5838. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5839. // DeepSeek 官方模型使用 DeepSeek API
  5840. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5841. } else if (in_array($model, $this->gpt_text_models)) {
  5842. // GPT-5.4 模型使用 TokenRouter API
  5843. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5844. } else {
  5845. // 其他模型使用火山引擎API
  5846. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5847. }
  5848. // 验证返回值类型
  5849. if (!is_iterable($streamGenerator)) {
  5850. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5851. dLog('deepseek')->error('addChat流式生成器无效', [
  5852. 'generator_type' => $errorType,
  5853. 'model' => $model,
  5854. 'anime_id' => $anime_id
  5855. ]);
  5856. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5857. 'type' => $errorType,
  5858. 'model' => $model
  5859. ]);
  5860. yield [
  5861. 'type' => 'error',
  5862. 'script' => [],
  5863. 'episode' => [],
  5864. 'answer' => '',
  5865. 'reasoning' => '',
  5866. 'usage' => [],
  5867. 'error' => '接口返回数据异常,请重新请求'
  5868. ];
  5869. return;
  5870. }
  5871. // 处理流式输出
  5872. foreach ($streamGenerator as $chunk) {
  5873. if (isset($chunk['type'])) {
  5874. if ($chunk['type'] === 'done') {
  5875. // 最终结果
  5876. $fullContent = $chunk['full_content'];
  5877. $fullReasoningContent = $chunk['full_reasoning'];
  5878. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5879. } else {
  5880. // 逐块yield数据
  5881. yield $chunk;
  5882. }
  5883. }
  5884. }
  5885. } catch (\Exception $e) {
  5886. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5887. 'model' => $model,
  5888. 'anime_id' => $anime_id,
  5889. 'trace' => $e->getTraceAsString()
  5890. ]);
  5891. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5892. 'error' => $e->getMessage(),
  5893. 'model' => $model
  5894. ]);
  5895. yield [
  5896. 'type' => 'error',
  5897. 'script' => [],
  5898. 'episode' => [],
  5899. 'answer' => '',
  5900. 'reasoning' => '',
  5901. 'usage' => [],
  5902. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5903. ];
  5904. return;
  5905. }
  5906. dLog('deepseek')->info('完整内容: '.$fullContent);
  5907. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5908. // 处理完整内容并返回最终结果
  5909. $script_arr = [];
  5910. if ($fullContent) {
  5911. $script_arr = handleScriptContentForAce($fullContent);
  5912. dLog('deepseek')->info('解析内容', $script_arr);
  5913. logDB('deepseek', 'info', '解析内容', $script_arr);
  5914. }
  5915. if (empty($script_arr['roles'])) {
  5916. // 未生成剧本相关内容,保存对话记录并返回提示
  5917. dLog('deepseek')->info('未生成剧本相关的内容');
  5918. try {
  5919. DB::beginTransaction();
  5920. $now = date('Y-m-d H:i:s');
  5921. // 保存对话记录
  5922. $records = [
  5923. [
  5924. 'uid' => $uid,
  5925. 'anime_id' => $anime_id,
  5926. 'sequence' => 0,
  5927. 'role' => 'user',
  5928. 'content' => $prompt,
  5929. 'created_at' => $now,
  5930. 'updated_at' => $now
  5931. ],
  5932. [
  5933. 'uid' => $uid,
  5934. 'anime_id' => $anime_id,
  5935. 'sequence' => 0,
  5936. 'role' => 'assistant',
  5937. // 'content' => $fullContent,
  5938. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5939. 'created_at' => $now,
  5940. 'updated_at' => $now
  5941. ]
  5942. ];
  5943. DB::table('mp_anime_records')->insert($records);
  5944. DB::commit();
  5945. } catch (\Exception $e) {
  5946. DB::rollBack();
  5947. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5948. }
  5949. yield [
  5950. 'type' => 'done',
  5951. 'script' => [],
  5952. 'episode' => [],
  5953. 'answer' => $fullContent,
  5954. 'reasoning' => $fullReasoningContent,
  5955. 'usage' => $usage,
  5956. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5957. ];
  5958. return;
  5959. }
  5960. // 如果需要生成原文内容,从script_arr中提取
  5961. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5962. $content = $script_arr['content'];
  5963. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5964. if (!$content) {
  5965. yield [
  5966. 'type' => 'done',
  5967. 'script' => [],
  5968. 'episode' => [],
  5969. 'answer' => $fullContent,
  5970. 'reasoning' => $fullReasoningContent,
  5971. 'usage' => $usage,
  5972. 'error' => '未生成剧本内容,请调整提示词再试'
  5973. ];
  5974. return;
  5975. }
  5976. }
  5977. // 替换美术风格
  5978. if ($mappedArtStyle !== '') {
  5979. $script_arr['art_style'] = $mappedArtStyle;
  5980. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5981. }
  5982. // 新建动漫
  5983. if ($user_anime_name == '新剧本策划') {
  5984. $anime_name = getProp($script_arr, 'script_name');
  5985. // if (!$anime_name) {
  5986. // // 未识别到剧本名,保存对话记录并返回提示
  5987. // dLog('deepseek')->info('未能识别到剧本名称');
  5988. // try {
  5989. // DB::beginTransaction();
  5990. // $now = date('Y-m-d H:i:s');
  5991. // // 保存对话记录
  5992. // $records = [
  5993. // [
  5994. // 'uid' => $uid,
  5995. // 'anime_id' => $anime_id,
  5996. // 'sequence' => 0,
  5997. // 'role' => 'user',
  5998. // 'content' => $prompt,
  5999. // 'created_at' => $now,
  6000. // 'updated_at' => $now
  6001. // ],
  6002. // [
  6003. // 'uid' => $uid,
  6004. // 'anime_id' => $anime_id,
  6005. // 'sequence' => 0,
  6006. // 'role' => 'assistant',
  6007. // 'content' => '未能生成剧本名称,请重试',
  6008. // 'created_at' => $now,
  6009. // 'updated_at' => $now
  6010. // ]
  6011. // ];
  6012. // DB::table('mp_anime_records')->insert($records);
  6013. // DB::commit();
  6014. // } catch (\Exception $e) {
  6015. // DB::rollBack();
  6016. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6017. // }
  6018. // yield [
  6019. // 'type' => 'done',
  6020. // 'script' => [],
  6021. // 'episode' => [],
  6022. // 'answer' => $fullContent,
  6023. // 'reasoning' => $fullReasoningContent,
  6024. // 'usage' => $usage,
  6025. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6026. // ];
  6027. // return;
  6028. // }
  6029. // 确认对话名称唯一性
  6030. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6031. $anime_name = $anime_name . '_' . date('YmdHis');
  6032. }
  6033. }else {
  6034. $anime_name = $user_anime_name;
  6035. }
  6036. $table_data = [
  6037. 'user_id' => $uid,
  6038. 'anime_name' => $anime_name,
  6039. 'model' => $model,
  6040. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6041. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6042. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6043. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6044. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6045. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6046. 'art_style_type' => $input_art_style,
  6047. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6048. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6049. 'status' => '解析完成',
  6050. 'content' => $content,
  6051. 'is_multi' => $is_multi,
  6052. 'ace_mode' => $ace_mode,
  6053. 'generate_status' => '待执行',
  6054. 'updated_at' => date('Y-m-d H:i:s')
  6055. ];
  6056. if ($table_data['content']) {
  6057. $chapters = splitContent($table_data['content']);
  6058. $chapter_count = count($chapters);
  6059. if ($chapter_count > 0) {
  6060. $table_data['start_episode_sequence'] = 1;
  6061. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6062. }
  6063. }
  6064. if ($extra_products) {
  6065. $table_data['extra_products'] = json_encode($extra_products, 256);
  6066. }
  6067. // 如果有剧本ID则进行绑定
  6068. if ($script_id) {
  6069. $table_data['script_id'] = $script_id;
  6070. }
  6071. $single_episode = [];
  6072. try {
  6073. DB::beginTransaction();
  6074. $now = date('Y-m-d H:i:s');
  6075. // 更新动漫大纲
  6076. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6077. if (!$boolen) {
  6078. dLog('deepseek')->info('动漫保存失败', $table_data);
  6079. Utils::throwError('20003:动漫保存失败');
  6080. }
  6081. // 保存对话记录
  6082. $records = [
  6083. [
  6084. 'uid' => $uid,
  6085. 'anime_id' => $anime_id,
  6086. 'sequence' => 0,
  6087. 'role' => 'user',
  6088. 'content' => $prompt,
  6089. 'created_at' => date('Y-m-d H:i:s'),
  6090. 'updated_at' => date('Y-m-d H:i:s')
  6091. ],
  6092. [
  6093. 'uid' => $uid,
  6094. 'anime_id' => $anime_id,
  6095. 'sequence' => 0,
  6096. 'role' => 'assistant',
  6097. 'content' => $fullContent,
  6098. 'created_at' => date('Y-m-d H:i:s'),
  6099. 'updated_at' => date('Y-m-d H:i:s')
  6100. ]
  6101. ];
  6102. // 保存对话记录
  6103. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6104. if (!$boolen3) {
  6105. Utils::throwError('20003:对话记录保存失败');
  6106. }
  6107. if ($is_single) {
  6108. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6109. if (empty($episode_arr['acts'])) {
  6110. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6111. }
  6112. $saveResult = $this->saveEpisodeVersionData(
  6113. $anime_id,
  6114. 1,
  6115. $episode_arr,
  6116. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6117. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6118. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6119. null,
  6120. null,
  6121. false,
  6122. $content,
  6123. $now,
  6124. $ref_products
  6125. );
  6126. $single_episode = $saveResult['episode'];
  6127. $episode_id = $saveResult['episode_id'];
  6128. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6129. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6130. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6131. 'props' => json_encode($saveResult['merged_props'], 256),
  6132. 'updated_at' => $now
  6133. ]);
  6134. if ($boolen5 === false) {
  6135. Utils::throwError('20003:单剧集主表资源同步失败');
  6136. }
  6137. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6138. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6139. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6140. $episode_record_content = '确认分镜大纲';
  6141. if ($content !== '') {
  6142. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6143. }
  6144. $episode_records = [
  6145. [
  6146. 'uid' => $uid,
  6147. 'anime_id' => $anime_id,
  6148. 'role' => 'user',
  6149. 'content' => $episode_record_content,
  6150. 'sequence' => 1,
  6151. 'episode_id' => $episode_id,
  6152. 'created_at' => $now,
  6153. 'updated_at' => $now
  6154. ],
  6155. [
  6156. 'uid' => $uid,
  6157. 'anime_id' => $anime_id,
  6158. 'role' => 'assistant',
  6159. 'content' => $fullContent,
  6160. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6161. 'sequence' => 1,
  6162. 'episode_id' => $episode_id,
  6163. 'created_at' => $now,
  6164. 'updated_at' => $now
  6165. ]
  6166. ];
  6167. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6168. if (!$boolen4) {
  6169. Utils::throwError('20003:单剧集分镜记录保存失败');
  6170. }
  6171. }
  6172. }catch (\Exception $e) {
  6173. DB::rollBack();
  6174. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6175. yield [
  6176. 'type' => 'done',
  6177. 'answer' => $fullContent,
  6178. 'reasoning' => $fullReasoningContent,
  6179. 'usage' => $usage,
  6180. 'error' => $e->getMessage(),
  6181. ];
  6182. return;
  6183. }
  6184. DB::commit();
  6185. dLog('deepseek')->info('保存完毕');
  6186. if ($is_single && !empty($single_episode)) {
  6187. // $this->batchSetGlobalRoleImg([
  6188. // 'anime_id' => $anime_id,
  6189. // ]);
  6190. // $this->batchSetGlobalSceneImg([
  6191. // 'anime_id' => $anime_id,
  6192. // ]);
  6193. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6194. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6195. }
  6196. $table_data['anime_id'] = $anime_id;
  6197. $table_data['roles'] = json_decode($table_data['roles'], true);
  6198. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6199. // $table_data['episodes'] = $script_arr['episodes'];
  6200. unset($table_data['created_at']);
  6201. unset($table_data['updated_at']);
  6202. unset($table_data['status']);
  6203. dLog('deepseek')->info('开始返回');
  6204. yield [
  6205. 'type' => 'done',
  6206. 'script' => $table_data,
  6207. 'episode' => $single_episode,
  6208. 'answer' => $fullContent,
  6209. 'reasoning' => $fullReasoningContent,
  6210. 'usage' => $usage
  6211. ];
  6212. }
  6213. public function reGenerateAnimeForAce($data) {
  6214. $uid = Site::getUid();
  6215. $file = getProp($data, 'file');
  6216. $content = getProp($data, 'content', '');
  6217. $bid = getProp($data, 'bid', 0);
  6218. $script_id = getProp($data, 'script_id', 0);
  6219. $anime_id = getProp($data, 'anime_id');
  6220. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6221. if (!$anime) {
  6222. Utils::throwError('20003:该对话不存在');
  6223. }
  6224. $is_multi = getProp($anime, 'is_multi', 1);
  6225. $is_single = (int)$is_multi !== 1;
  6226. $extra_products = getProp($data, 'products', []);
  6227. if (!$extra_products) {
  6228. $extra_products = getProp($anime, 'extra_products');
  6229. if ($extra_products) {
  6230. $extra_products = json_decode($extra_products, true);
  6231. }else {
  6232. $extra_products = [];
  6233. }
  6234. }else {
  6235. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6236. }
  6237. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6238. $anime_script_id = getProp($anime, 'script_id');
  6239. if ($anime_script_id && $is_single) {
  6240. $cpid = Site::getCpid();
  6241. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6242. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6243. ->where('mapping.script_id', $anime_script_id)
  6244. ->where('product.cpid', $cpid)
  6245. ->where('product.is_deleted', 0);
  6246. $mappings = $script_products_mappings->select(
  6247. 'mapping.product_id',
  6248. 'mapping.episode_number',
  6249. 'product.product_name',
  6250. 'product.type',
  6251. 'product.product',
  6252. 'product.pic_prompt',
  6253. 'product.url',
  6254. 'product.pic_task_id',
  6255. 'product.pic_task_status',
  6256. 'product.three_view_image_url'
  6257. )
  6258. ->get();
  6259. // 按 product_id 分组,合并 episode_number
  6260. $productMap = [];
  6261. foreach ($mappings as $item) {
  6262. $product_id = $item->product_id;
  6263. $product_name = $item->product_name;
  6264. // 处理product_name两边的符号
  6265. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6266. if (!isset($productMap[$product_id])) {
  6267. $productMap[$product_id] = [
  6268. 'product_id' => $product_id,
  6269. 'product_name' => $product_name,
  6270. 'type' => (int)$item->type,
  6271. 'product' => (int)$item->product,
  6272. 'pic_prompt' => $item->pic_prompt,
  6273. 'url' => $item->url,
  6274. 'pic_task_id' => $item->pic_task_id,
  6275. 'pic_task_status' => $item->pic_task_status,
  6276. 'episode_numbers' => [],
  6277. ];
  6278. }
  6279. // 添加 episode_number(去重)
  6280. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6281. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6282. }
  6283. }
  6284. // 将查询到的剧本资产合并到extra_products中
  6285. // 先构建extra_products的索引(以product_id为key,用于去重)
  6286. $extraProductsMap = [];
  6287. foreach ($extra_products as $item) {
  6288. $key = getProp($item, 'product_id');
  6289. if ($key) {
  6290. $extraProductsMap[$key] = $item;
  6291. }
  6292. }
  6293. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6294. foreach ($productMap as $product) {
  6295. $product_id = $product['product_id'];
  6296. // 如果不存在则添加(不带episode_number信息)
  6297. if (!isset($extraProductsMap[$product_id])) {
  6298. $extraProductsMap[$product_id] = [
  6299. 'product_id' => $product['product_id'],
  6300. 'product_name' => $product['product_name'],
  6301. 'type' => $product['type'],
  6302. 'product' => $product['product'],
  6303. 'pic_prompt' => $product['pic_prompt'],
  6304. 'url' => $product['url'],
  6305. 'pic_task_id' => $product['pic_task_id'],
  6306. 'pic_task_status' => $product['pic_task_status'],
  6307. ];
  6308. }
  6309. }
  6310. // 重新赋值给extra_products
  6311. $extra_products = array_values($extraProductsMap);
  6312. }
  6313. $user_anime_name = getProp($anime, 'anime_name');
  6314. $prompt = getProp($data, 'prompt');
  6315. // 处理提示词
  6316. if ($prompt && $extra_products) {
  6317. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6318. foreach($extra_products as $item) {
  6319. $product_name = getProp($item, 'product_name');
  6320. if ($product_name) {
  6321. // 替换 {product_name} 为 product_name
  6322. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6323. }
  6324. }
  6325. }
  6326. // 处理文本模型
  6327. $model = getProp($data, 'model');
  6328. if (!$model) {
  6329. // 用户没有输入,从anime表获取
  6330. $model = getProp($anime, 'model');
  6331. if (!$model) {
  6332. // anime表也没有,使用默认值
  6333. $model = 'deepseek-v4-pro';
  6334. }
  6335. }
  6336. // 验证模型是否在可用模型表中
  6337. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6338. $model = 'deepseek-v4-pro';
  6339. }
  6340. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6341. if ($is_single) {
  6342. $episode_exists = DB::table('mp_anime_episodes')
  6343. ->where('anime_id', $anime_id)
  6344. ->where('sequence', 1)
  6345. ->exists();
  6346. if ($episode_exists) {
  6347. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6348. }
  6349. }
  6350. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6351. if ($prompt) {
  6352. $question .= "本次修改要求如下:\n{$prompt}";
  6353. }
  6354. // 提取文件内容
  6355. if ($file) {
  6356. $content = $this->extractFileContent($file);
  6357. if (!$content) {
  6358. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6359. }
  6360. } elseif ($script_id) {
  6361. $content = $this->getContentByScriptId($script_id);
  6362. if (!$content) {
  6363. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6364. }
  6365. } elseif ($bid) {
  6366. $content = $this->getContentByBid($bid);
  6367. if (!$content) {
  6368. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6369. }
  6370. } elseif ($content) {
  6371. $content = filterContent($content);
  6372. }else {
  6373. $content = filterContent(getProp($anime, 'content'));
  6374. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6375. $need_generate_content = true;
  6376. }
  6377. }
  6378. // 判断是否需要生成原文内容
  6379. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6380. // 如果需要生成原文内容,添加额外的要求
  6381. $content_generation_requirement = $need_generate_content
  6382. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6383. : "";
  6384. // 美术风格
  6385. $input_art_style = getProp($data, 'art_style');
  6386. if (!$input_art_style) {
  6387. $mappedArtStyle = getProp($anime, 'art_style');
  6388. }else {
  6389. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6390. }
  6391. if (!$mappedArtStyle) {
  6392. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6393. }else {
  6394. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6395. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6396. }else {
  6397. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6398. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6399. }
  6400. }
  6401. // 构建主体、场景和道具提示词
  6402. $extra_role_prompt = "\n";
  6403. $extra_scene_prompt = "\n";
  6404. $extra_prop_prompt = "\n";
  6405. $ref_products = []; // 参考资产
  6406. if ($extra_products) {
  6407. foreach($extra_products as $item) {
  6408. $product = getProp($item, 'product');
  6409. $product_name = getProp($item, 'product_name');
  6410. if ($product_name == '旁白') continue;
  6411. $ref_products[$product_name] = $item;
  6412. $pic_prompt = getProp($item, 'pic_prompt');
  6413. if ((int)$product === 1) {
  6414. // 拼接角色信息
  6415. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6416. } elseif ((int)$product === 2) {
  6417. // 拼接场景信息
  6418. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6419. } elseif ((int)$product === 3) {
  6420. // 拼接道具信息
  6421. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6422. }
  6423. }
  6424. // 优化提示词,融入剧本
  6425. if (!empty(trim($extra_role_prompt))) {
  6426. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6427. }
  6428. if (!empty(trim($extra_scene_prompt))) {
  6429. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6430. }
  6431. if (!empty(trim($extra_prop_prompt))) {
  6432. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6433. }
  6434. }
  6435. if ($anime_script_id && $is_single) {
  6436. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6437. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6438. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6439. }else {
  6440. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6441. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6442. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6443. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6444. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6445. {$extra_role_prompt}";
  6446. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6447. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6448. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6449. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6450. {$extra_scene_prompt}";
  6451. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6452. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6453. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6454. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6455. {$extra_prop_prompt}";
  6456. }
  6457. $system_message = ['role'=>'system', 'content'=>$is_single
  6458. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6459. 强制要求:
  6460. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6461. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6462. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6463. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6464. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6465. 普通要求:
  6466. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6467. $role_demo
  6468. $scene_demo
  6469. $prop_demo
  6470. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6471. 5.1片段分割逻辑(优先级从高到低):
  6472. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6473. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6474. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6475. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6476. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6477. - 片段数量格式为: 片段数量:8
  6478. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6479. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6480. 5.3分镜结构:每个分镜包含以下字段:
  6481. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6482. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6483. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6484. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6485. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6486. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6487. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6488. - 运镜:场景+画面描述+运镜
  6489. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6490. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6491. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6492. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6493. 6.{$mappedArtStyle_prompt}\n\n
  6494. 示例如下:\n
  6495. ###剧本名:西昆仑
  6496. ###故事梗概
  6497. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6498. ###剧本亮点
  6499. 亮点1:绝境奇药,生死一线
  6500. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6501. 亮点2:结拜兄妹,化解尴尬
  6502. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6503. 亮点3:纤发夺命,情愫暗涌
  6504. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6505. ###人物关系
  6506. 阿雪与梁萧之间存在兄妹之情。
  6507. ###核心矛盾
  6508. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6509. ###主体列表
  6510. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6511. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6512. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6513. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6514. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6515. 全景,正面拍摄,青年女性,亚洲人。
  6516. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6517. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6518. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6519. ###美术风格
  6520. 基础画风风格词:厚涂古风
  6521. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6522. ###场景列表
  6523. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6524. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6525. 无人物。}
  6526. ###分段剧本
  6527. 片段数量:8
  6528. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6529. ##片段1
  6530. 时长:12s
  6531. 分镜1
  6532. 出场角色:刀疤脸
  6533. 场景:边境小镇街道
  6534. 出场道具:酒杯-高脚杯
  6535. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6536. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6537. 配音台词:
  6538. 背景音效:
  6539. 分镜2
  6540. 出场角色:刀疤脸
  6541. 场景:悦来酒馆
  6542. 出场道具:酒杯-高脚杯
  6543. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6544. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6545. 配音台词:
  6546. 背景音效:
  6547. 分镜3
  6548. 出场角色:刀疤脸
  6549. 场景:悦来酒馆
  6550. 出场道具:酒杯-高脚杯
  6551. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6552. 运镜:从中景推向令牌特写。
  6553. 配音台词:
  6554. 背景音效:
  6555. 分镜4
  6556. 出场角色:刀疤脸
  6557. 场景:悦来酒馆
  6558. 出场道具:酒杯-高脚杯
  6559. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6560. 运镜:极速推向酒水溅起的瞬间。
  6561. 配音台词:
  6562. 背景音效:
  6563. 分镜5
  6564. 出场角色:刀疤脸
  6565. 场景:悦来酒馆
  6566. 出场道具:酒杯-高脚杯
  6567. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6568. 运镜:固定机位,利用倾斜构图制造压迫感。
  6569. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6570. 背景音效:
  6571. \n\n"
  6572. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6573. 强制要求:\n
  6574. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6575. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6576. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6577. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6578. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6579. 普通要求:\n
  6580. 1.剧本名(必须生成)必须与文档内容高度相关
  6581. $role_demo
  6582. $scene_demo
  6583. $prop_demo
  6584. 5.{$mappedArtStyle_prompt}\n\n
  6585. 示例如下:\n
  6586. ###剧本名:西昆仑
  6587. ###故事梗概
  6588. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6589. ###剧本亮点
  6590. 亮点1:绝境奇药,生死一线
  6591. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6592. 亮点2:结拜兄妹,化解尴尬
  6593. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6594. 亮点3:纤发夺命,情愫暗涌
  6595. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6596. ###人物关系
  6597. 阿雪与梁萧之间存在兄妹之情。
  6598. ###核心矛盾
  6599. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6600. ###主体列表
  6601. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6602. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6603. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6604. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6605. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6606. 全景,正面拍摄,青年女性,亚洲人。
  6607. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6608. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6609. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6610. ###美术风格
  6611. 基础画风风格词:厚涂古风
  6612. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6613. ###场景列表
  6614. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6615. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6616. 无人物。}
  6617. ###道具列表
  6618. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6619. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6620. $episode_count = $this->extractEpisodeNumber($prompt);
  6621. if ((int)getProp($anime, 'is_multi') !== 1) {
  6622. yield [
  6623. 'type' => 'done',
  6624. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6625. 'reasoning' => '',
  6626. 'usage' => []
  6627. ];
  6628. return;
  6629. }
  6630. if ($episode_count) {
  6631. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6632. $system_message = [
  6633. 'role' => 'system',
  6634. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6635. 强制要求:\n
  6636. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6637. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6638. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6639. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6640. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6641. 普通要求:\n
  6642. 1.<故事梗概>控制在200-300字左右
  6643. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6644. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6645. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6646. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6647. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6648. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6649. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6650. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6651. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6652. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6653. 示例如下:\n
  6654. ###剧本名:西昆仑
  6655. ###故事梗概
  6656. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6657. ###剧本亮点
  6658. 亮点1:绝境奇药,生死一线
  6659. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6660. 亮点2:结拜兄妹,化解尴尬
  6661. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6662. 亮点3:纤发夺命,情愫暗涌
  6663. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6664. ###人物关系
  6665. 阿雪与梁萧之间存在兄妹之情。
  6666. ###核心矛盾
  6667. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6668. ###主体列表
  6669. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6670. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6671. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6672. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6673. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6674. 全景,正面拍摄,青年女性,亚洲人。
  6675. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6676. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6677. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6678. ###美术风格
  6679. 基础画风风格词:厚涂古风
  6680. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6681. ###场景列表
  6682. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6683. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6684. 无人物。}
  6685. ###分集详细内容
  6686. ##第1章 重生
  6687. 我重生了。
  6688. 源于一个男人偏执的暗恋。
  6689. ##第2章 相救
  6690. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6691. 我眼睛扫向站在锅炉后的卞大伟。"
  6692. ];
  6693. // 构建消息
  6694. $messages = [
  6695. $system_message,
  6696. [
  6697. 'role' => 'user',
  6698. 'content' => "以下是文档内容:
  6699. {$content}
  6700. 用户问题:
  6701. {$question}"
  6702. ]
  6703. ];
  6704. }else {
  6705. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6706. // 构建消息
  6707. $messages = [
  6708. $system_message,
  6709. [
  6710. 'role' => 'user',
  6711. 'content' => "以下是文档内容:
  6712. {$content}
  6713. 用户问题:
  6714. {$question}"
  6715. ]
  6716. ];
  6717. }else {
  6718. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6719. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6720. return (array)$value;
  6721. })->toArray();
  6722. array_unshift($messages, $system_message);
  6723. $messages[] = [
  6724. 'role' => 'user',
  6725. 'content' => $prompt
  6726. ];
  6727. }
  6728. }
  6729. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6730. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6731. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6732. if ($model === 'deepseek-chat') {
  6733. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6734. $model = 'deepseek-v4-flash';
  6735. $thinkingMode = 'disabled';
  6736. } elseif ($model === 'deepseek-reasoner') {
  6737. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6738. $model = 'deepseek-v4-flash';
  6739. $thinkingMode = 'enabled';
  6740. }
  6741. $post_data = [
  6742. 'model' => $model,
  6743. 'messages' => $messages,
  6744. // 'max_tokens' => 8192,
  6745. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6746. 'frequency_penalty' => 0,
  6747. 'presence_penalty' => 0,
  6748. 'response_format' => ['type' => 'text'],
  6749. 'thinking' => ['type' => $thinkingMode],
  6750. 'stream' => true // 启用流式输出
  6751. ];
  6752. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6753. // 根据模型类型选择调用方法
  6754. $fullContent = '';
  6755. $fullReasoningContent = '';
  6756. $usage = [];
  6757. // dd($post_data);
  6758. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6759. try {
  6760. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6761. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6762. } else if (in_array($model, $this->gpt_text_models)) {
  6763. // GPT-5.4 模型使用 TokenRouter API
  6764. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6765. } else {
  6766. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6767. }
  6768. // 验证返回值类型
  6769. if (!is_iterable($streamGenerator)) {
  6770. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6771. dLog('deepseek')->error('方法名流式生成器无效', [
  6772. 'generator_type' => $errorType,
  6773. 'model' => $model,
  6774. // 添加其他上下文信息
  6775. ]);
  6776. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6777. 'type' => $errorType,
  6778. 'model' => $model
  6779. ]);
  6780. yield [
  6781. 'type' => 'error',
  6782. // 根据方法返回相应的空数据结构
  6783. 'answer' => '',
  6784. 'reasoning' => '',
  6785. 'usage' => [],
  6786. 'error' => '接口返回数据异常,请重新请求'
  6787. ];
  6788. return;
  6789. }
  6790. // 处理流式输出
  6791. foreach ($streamGenerator as $chunk) {
  6792. if (isset($chunk['type'])) {
  6793. if ($chunk['type'] === 'done') {
  6794. $fullContent = $chunk['full_content'];
  6795. $fullReasoningContent = $chunk['full_reasoning'];
  6796. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6797. } else {
  6798. yield $chunk;
  6799. }
  6800. }
  6801. }
  6802. } catch (\Exception $e) {
  6803. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6804. 'model' => $model,
  6805. 'trace' => $e->getTraceAsString()
  6806. ]);
  6807. logDB('deepseek', 'error', '方法名流式处理失败', [
  6808. 'error' => $e->getMessage(),
  6809. 'model' => $model
  6810. ]);
  6811. yield [
  6812. 'type' => 'error',
  6813. // 根据方法返回相应的空数据结构
  6814. 'answer' => '',
  6815. 'reasoning' => '',
  6816. 'usage' => [],
  6817. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6818. ];
  6819. return;
  6820. }
  6821. dLog('deepseek')->info('完整内容: '.$fullContent);
  6822. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6823. // 处理完整内容并返回最终结果
  6824. $script_arr = [];
  6825. if ($fullContent) {
  6826. $script_arr = handleScriptContentForAce($fullContent);
  6827. dLog('deepseek')->info('解析内容', $script_arr);
  6828. logDB('deepseek', 'info', '解析内容', $script_arr);
  6829. }
  6830. if (empty($script_arr['roles'])) {
  6831. // 未生成剧本相关内容,保存对话记录并返回提示
  6832. dLog('deepseek')->info('未生成剧本相关的内容');
  6833. try {
  6834. $now = date('Y-m-d H:i:s');
  6835. // 保存对话记录
  6836. $records = [
  6837. [
  6838. 'uid' => $uid,
  6839. 'anime_id' => $anime_id,
  6840. 'sequence' => 0,
  6841. 'role' => 'user',
  6842. 'content' => $prompt,
  6843. 'created_at' => $now,
  6844. 'updated_at' => $now
  6845. ],
  6846. [
  6847. 'uid' => $uid,
  6848. 'anime_id' => $anime_id,
  6849. 'sequence' => 0,
  6850. 'role' => 'assistant',
  6851. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6852. 'created_at' => $now,
  6853. 'updated_at' => $now
  6854. ]
  6855. ];
  6856. DB::table('mp_anime_records')->insert($records);
  6857. } catch (\Exception $e) {
  6858. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6859. }
  6860. yield [
  6861. 'type' => 'done',
  6862. 'script' => [],
  6863. 'episode' => [],
  6864. 'answer' => $fullContent,
  6865. 'reasoning' => $fullReasoningContent,
  6866. 'usage' => $usage,
  6867. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6868. ];
  6869. return;
  6870. }
  6871. // 替换美术风格
  6872. if ($mappedArtStyle !== '') {
  6873. $script_arr['art_style'] = $mappedArtStyle;
  6874. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6875. }
  6876. if ($user_anime_name != '新剧本策划') {
  6877. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6878. // 确认对话名称唯一性
  6879. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6880. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6881. }
  6882. }else {
  6883. $anime_name = $user_anime_name;
  6884. }
  6885. $table_data = [
  6886. 'user_id' => $uid,
  6887. 'model' => $model,
  6888. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6889. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6890. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6891. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6892. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6893. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6894. 'art_style_type' => $input_art_style,
  6895. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6896. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6897. 'status' => '解析完成',
  6898. 'generate_status' => '待执行',
  6899. 'updated_at' => date('Y-m-d H:i:s')
  6900. ];
  6901. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6902. // 如果是修改集数,则将content内容更新(会改变原文)
  6903. if (isset($episode_count) && $episode_count > 0) {
  6904. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6905. $table_data['start_episode_sequence'] = 1;
  6906. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6907. }else {
  6908. // 如果需要生成原文内容,从script_arr中提取
  6909. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6910. $table_data['content'] = $script_arr['content'];
  6911. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6912. if (!$table_data['content']) {
  6913. yield [
  6914. 'type' => 'done',
  6915. 'script' => [],
  6916. 'episode' => [],
  6917. 'answer' => $fullContent,
  6918. 'reasoning' => $fullReasoningContent,
  6919. 'usage' => $usage,
  6920. 'error' => '未生成剧本内容,请调整提示词再试'
  6921. ];
  6922. return;
  6923. }
  6924. }
  6925. if (isset($table_data['content']) && $table_data['content']) {
  6926. $chapters = splitContent($table_data['content']);
  6927. $chapter_count = count($chapters);
  6928. if ($chapter_count > 0) {
  6929. $table_data['start_episode_sequence'] = 1;
  6930. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6931. }
  6932. }
  6933. }
  6934. if ($extra_products) {
  6935. $table_data['extra_products'] = json_encode($extra_products, 256);
  6936. }
  6937. $single_episode = [];
  6938. try {
  6939. DB::beginTransaction();
  6940. $now = date('Y-m-d H:i:s');
  6941. // 更新动漫大纲
  6942. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6943. if (!$boolen) {
  6944. dLog('deepseek')->info('对话修改失败', $table_data);
  6945. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6946. Utils::throwError('20003:对话修改失败');
  6947. }
  6948. // 保存对话记录
  6949. $records = [
  6950. [
  6951. 'uid' => $uid,
  6952. 'anime_id' => $anime_id,
  6953. 'sequence' => 0,
  6954. 'role' => 'user',
  6955. 'content' => $prompt,
  6956. 'created_at' => $now,
  6957. 'updated_at' => $now
  6958. ],
  6959. [
  6960. 'uid' => $uid,
  6961. 'anime_id' => $anime_id,
  6962. 'sequence' => 0,
  6963. 'role' => 'assistant',
  6964. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6965. 'content' => $fullContent,
  6966. 'created_at' => $now,
  6967. 'updated_at' => $now
  6968. ]
  6969. ];
  6970. // 保存对话记录
  6971. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6972. if (!$boolen3) {
  6973. Utils::throwError('20003:对话记录保存失败');
  6974. }
  6975. // 单剧集模式:生成并保存剧集信息
  6976. if ($is_single) {
  6977. $anime_name = getProp($anime, 'anime_name', '未命名');
  6978. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6979. if (empty($episode_arr['acts'])) {
  6980. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6981. }
  6982. $saveResult = $this->saveEpisodeVersionData(
  6983. $anime_id,
  6984. 1,
  6985. $episode_arr,
  6986. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6987. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6988. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6989. null,
  6990. null,
  6991. false,
  6992. $content,
  6993. $now,
  6994. $ref_products
  6995. );
  6996. $single_episode = $saveResult['episode'];
  6997. $episode_id = $saveResult['episode_id'];
  6998. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6999. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7000. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7001. 'props' => json_encode($saveResult['merged_props'], 256),
  7002. 'updated_at' => $now
  7003. ]);
  7004. if ($boolen5 === false) {
  7005. Utils::throwError('20003:单剧集主表资源同步失败');
  7006. }
  7007. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7008. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7009. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7010. $episode_record_content = '确认分镜大纲';
  7011. if ($content !== '') {
  7012. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7013. }
  7014. $episode_records = [
  7015. [
  7016. 'uid' => $uid,
  7017. 'anime_id' => $anime_id,
  7018. 'role' => 'user',
  7019. 'content' => $episode_record_content,
  7020. 'sequence' => 1,
  7021. 'episode_id' => $episode_id,
  7022. 'created_at' => $now,
  7023. 'updated_at' => $now
  7024. ],
  7025. [
  7026. 'uid' => $uid,
  7027. 'anime_id' => $anime_id,
  7028. 'role' => 'assistant',
  7029. 'content' => $fullContent,
  7030. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7031. 'sequence' => 1,
  7032. 'episode_id' => $episode_id,
  7033. 'created_at' => $now,
  7034. 'updated_at' => $now
  7035. ]
  7036. ];
  7037. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7038. if (!$boolen4) {
  7039. Utils::throwError('20003:单剧集分镜记录保存失败');
  7040. }
  7041. }
  7042. }catch (\Exception $e) {
  7043. DB::rollBack();
  7044. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7045. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7046. yield [
  7047. 'type' => 'done',
  7048. 'answer' => $fullContent,
  7049. 'reasoning' => $fullReasoningContent,
  7050. 'usage' => $usage,
  7051. 'error' => $e->getMessage(),
  7052. ];
  7053. return;
  7054. }
  7055. DB::commit();
  7056. dLog('deepseek')->info('保存完毕');
  7057. if ($is_single && !empty($single_episode)) {
  7058. // $this->batchSetGlobalRoleImg([
  7059. // 'anime_id' => $anime_id,
  7060. // ]);
  7061. // $this->batchSetGlobalSceneImg([
  7062. // 'anime_id' => $anime_id,
  7063. // ]);
  7064. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7065. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7066. }
  7067. $table_data['anime_id'] = $anime_id;
  7068. $table_data['roles'] = json_decode($table_data['roles'], true);
  7069. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7070. $table_data['props'] = json_decode($table_data['props'], true);
  7071. unset($table_data['updated_at']);
  7072. unset($table_data['status']);
  7073. yield [
  7074. 'type' => 'done',
  7075. 'script' => $table_data,
  7076. 'episode' => $single_episode,
  7077. 'answer' => $fullContent,
  7078. 'reasoning' => $fullReasoningContent,
  7079. 'usage' => $usage
  7080. ];
  7081. }
  7082. public function chatForAce($data) {
  7083. $uid = Site::getUid();
  7084. $anime_id = getProp($data, 'anime_id');
  7085. $file = getProp($data, 'file');
  7086. $content = getProp($data, 'content', '');
  7087. $bid = getProp($data, 'bid', 0);
  7088. $script_id = getProp($data, 'script_id', 0);
  7089. $episode_number = getProp($data, 'episode_number', 1);
  7090. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7091. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7092. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7093. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7094. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7095. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7096. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7097. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7098. $roles = is_array($roles) ? $roles : [];
  7099. $scenes = is_array($scenes) ? $scenes : [];
  7100. $extra_products = getProp($data, 'products', []);
  7101. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7102. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7103. $anime_script_id = getProp($anime, 'script_id');
  7104. if ($anime_script_id) {
  7105. $cpid = Site::getCpid();
  7106. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7107. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7108. ->where('mapping.script_id', $anime_script_id)
  7109. ->where('product.cpid', $cpid)
  7110. ->where('product.is_deleted', 0);
  7111. // 如果提供了 episode_number,则过滤指定集数
  7112. if ($episode_number !== null && $episode_number !== '') {
  7113. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7114. }
  7115. $mappings = $script_products_mappings->select(
  7116. 'mapping.product_id',
  7117. 'mapping.episode_number',
  7118. 'product.product_name',
  7119. 'product.type',
  7120. 'product.product',
  7121. 'product.pic_prompt',
  7122. 'product.url',
  7123. 'product.pic_task_id',
  7124. 'product.pic_task_status',
  7125. 'product.three_view_image_url'
  7126. )
  7127. ->get();
  7128. // 按 product_id 分组,合并 episode_number
  7129. $productMap = [];
  7130. foreach ($mappings as $item) {
  7131. $product_id = $item->product_id;
  7132. $product_name = $item->product_name;
  7133. // 处理product_name两边的符号
  7134. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7135. if (!isset($productMap[$product_id])) {
  7136. $productMap[$product_id] = [
  7137. 'product_id' => $product_id,
  7138. 'product_name' => $product_name,
  7139. 'type' => (int)$item->type,
  7140. 'product' => (int)$item->product,
  7141. 'pic_prompt' => $item->pic_prompt,
  7142. 'url' => $item->url,
  7143. 'pic_task_id' => $item->pic_task_id,
  7144. 'pic_task_status' => $item->pic_task_status,
  7145. 'episode_numbers' => [],
  7146. ];
  7147. }
  7148. // 添加 episode_number(去重)
  7149. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7150. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7151. }
  7152. }
  7153. // 将查询到的剧本资产合并到extra_products中
  7154. // 先构建extra_products的索引(以product_id+episode_number为key)
  7155. $extraProductsMap = [];
  7156. foreach ($extra_products as $item) {
  7157. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7158. $extraProductsMap[$key] = $item;
  7159. }
  7160. // 合并剧本资产(去重:product_id+episode_number)
  7161. foreach ($productMap as $product) {
  7162. foreach ($product['episode_numbers'] as $ep_num) {
  7163. $key = $product['product_id'] . '_' . $ep_num;
  7164. // 如果不存在则添加
  7165. if (!isset($extraProductsMap[$key])) {
  7166. $extraProductsMap[$key] = [
  7167. 'product_id' => $product['product_id'],
  7168. 'product_name' => $product['product_name'],
  7169. 'type' => $product['type'],
  7170. 'product' => $product['product'],
  7171. 'pic_prompt' => $product['pic_prompt'],
  7172. 'url' => $product['url'],
  7173. 'pic_task_id' => $product['pic_task_id'],
  7174. 'pic_task_status' => $product['pic_task_status'],
  7175. 'episode_number' => $ep_num,
  7176. ];
  7177. }
  7178. }
  7179. }
  7180. // 重新赋值给extra_products
  7181. $extra_products = array_values($extraProductsMap);
  7182. }
  7183. // 处理提示词
  7184. if ($prompt && $extra_products) {
  7185. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7186. foreach($extra_products as $item) {
  7187. $product_name = getProp($item, 'product_name');
  7188. if ($product_name) {
  7189. // 替换 {product_name} 为 product_name
  7190. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7191. }
  7192. }
  7193. }
  7194. // 获取最后一集序号
  7195. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7196. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7197. // 转换主体列表和场景列表的格式
  7198. // 获取参考主体或场景
  7199. if ((int)$episode_number === 1) {
  7200. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7201. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7202. }else {
  7203. $prev_episode_number = $episode_number - 1;
  7204. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7205. }
  7206. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7207. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7208. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7209. // 合并anime_products和extra_products(extra_products优先,去重)
  7210. $anime_products = getProp($anime, 'extra_products');
  7211. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7212. $ref_products = [];
  7213. foreach($anime_products as $item) {
  7214. $product_name = getProp($item, 'product_name');
  7215. $ref_products[$product_name] = $item;
  7216. }
  7217. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7218. $extra_roles = []; // 从extra_products中提取的角色
  7219. $extra_scenes = []; // 从extra_products中提取的场景
  7220. $extra_props = []; // 从extra_products中提取的道具
  7221. if ($extra_products && is_array($extra_products)) {
  7222. foreach($extra_products as $item) {
  7223. $product = (int)getProp($item, 'product');
  7224. $product_name = getProp($item, 'product_name');
  7225. if ($product_name == '旁白') continue;
  7226. $pic_prompt = getProp($item, 'pic_prompt');
  7227. $ref_products[$product_name] = $item;
  7228. if ($product === 1) {
  7229. // 角色
  7230. $extra_roles[$product_name] = [
  7231. 'role' => $product_name,
  7232. 'pic_prompt' => $pic_prompt,
  7233. 'url' => getProp($item, 'url', ''),
  7234. ];
  7235. } elseif ($product === 2) {
  7236. // 场景
  7237. $extra_scenes[$product_name] = [
  7238. 'scene' => $product_name,
  7239. 'pic_prompt' => $pic_prompt,
  7240. 'url' => getProp($item, 'url', ''),
  7241. ];
  7242. } elseif ($product === 3) {
  7243. // 道具
  7244. $extra_props[$product_name] = [
  7245. 'prop' => $product_name,
  7246. 'pic_prompt' => $pic_prompt,
  7247. 'url' => getProp($item, 'url', ''),
  7248. ];
  7249. }
  7250. }
  7251. }
  7252. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7253. $merged_roles = [];
  7254. foreach($ref_roles as $role) {
  7255. $role_name = getProp($role, 'role');
  7256. if (!isset($extra_roles[$role_name])) {
  7257. $merged_roles[$role_name] = $role;
  7258. }
  7259. }
  7260. // 添加extra_roles
  7261. foreach($extra_roles as $role_name => $role) {
  7262. $merged_roles[$role_name] = $role;
  7263. }
  7264. $ref_roles = array_values($merged_roles);
  7265. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7266. $merged_scenes = [];
  7267. foreach($ref_scenes as $scene) {
  7268. $scene_name = getProp($scene, 'scene');
  7269. if (!isset($extra_scenes[$scene_name])) {
  7270. $merged_scenes[$scene_name] = $scene;
  7271. }
  7272. }
  7273. // 添加extra_scenes
  7274. foreach($extra_scenes as $scene_name => $scene) {
  7275. $merged_scenes[$scene_name] = $scene;
  7276. }
  7277. $ref_scenes = array_values($merged_scenes);
  7278. // 合并ref_props和extra_props(extra_props优先,去重)
  7279. $merged_props = [];
  7280. foreach($ref_props as $prop) {
  7281. $prop_name = getProp($prop, 'prop');
  7282. if (!isset($extra_props[$prop_name])) {
  7283. $merged_props[$prop_name] = $prop;
  7284. }
  7285. }
  7286. // 添加extra_props
  7287. foreach($extra_props as $prop_name => $prop) {
  7288. $merged_props[$prop_name] = $prop;
  7289. }
  7290. $ref_props = array_values($merged_props);
  7291. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7292. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7293. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7294. // 构建强制主体、场景和道具提示词
  7295. $forced_roles_prompt = "";
  7296. $forced_scenes_prompt = "";
  7297. $forced_props_prompt = "";
  7298. if (!empty($extra_roles)) {
  7299. $forced_roles_list = "";
  7300. foreach($extra_roles as $role_name => $role) {
  7301. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7302. }
  7303. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7304. }
  7305. if (!empty($extra_scenes)) {
  7306. $forced_scenes_list = "";
  7307. foreach($extra_scenes as $scene_name => $scene) {
  7308. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7309. }
  7310. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7311. }
  7312. if (!empty($extra_props)) {
  7313. $forced_props_list = "";
  7314. foreach($extra_props as $prop_name => $prop) {
  7315. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7316. }
  7317. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7318. }
  7319. if ($anime_script_id) {
  7320. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7321. }else if ($roles_content) {
  7322. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7323. 主体范围:\n {$roles_content}\n
  7324. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7325. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7326. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7327. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7328. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7329. }else {
  7330. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7331. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7332. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7333. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7334. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7335. }
  7336. if ($anime_script_id) {
  7337. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7338. }else if ($scenes_content) {
  7339. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7340. 场景范围:\n {$scenes_content}\n
  7341. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7342. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7343. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7344. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7345. }else {
  7346. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7347. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7348. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7349. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7350. }
  7351. if ($anime_script_id) {
  7352. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7353. }else if ($props_content) {
  7354. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7355. 道具范围:\n {$props_content}\n
  7356. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7357. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7358. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7359. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7360. }else {
  7361. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7362. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7363. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7364. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7365. }
  7366. // 提取文件内容
  7367. if ($file) {
  7368. $uploaded_content = $this->extractFileContent($file);
  7369. if (!$uploaded_content) {
  7370. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7371. }
  7372. } elseif ($script_id) {
  7373. $uploaded_content = $this->getContentByScriptId($script_id);
  7374. if (!$uploaded_content) {
  7375. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7376. }
  7377. } elseif ($bid) {
  7378. $uploaded_content = $this->getContentByBid($bid);
  7379. if (!$uploaded_content) {
  7380. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7381. }
  7382. } elseif ($content) {
  7383. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7384. }
  7385. // elseif ($prompt) {
  7386. // $uploaded_content = filterContent($prompt);
  7387. // }
  7388. else {
  7389. $uploaded_content = '';
  7390. }
  7391. // 美术风格
  7392. $input_art_style = getProp($data, 'art_style');
  7393. if (!$input_art_style) {
  7394. $mappedArtStyle = getProp($anime, 'art_style');
  7395. }else {
  7396. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7397. }
  7398. if (!$mappedArtStyle) {
  7399. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7400. }else {
  7401. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7402. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7403. }else {
  7404. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7405. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7406. }
  7407. }
  7408. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7409. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7410. // 强制要求:
  7411. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7412. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7413. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7414. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7415. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7416. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7417. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7418. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7419. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7420. // 10.分镜要和场景列表、人物主体保持一致\n
  7421. // 普通要求:
  7422. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7423. // {$role_demo}
  7424. // {$scene_demo}
  7425. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7426. // 4.1片段分割逻辑(优先级从高到低):
  7427. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7428. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7429. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7430. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7431. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7432. // - 片段数量格式为: 片段数量:8
  7433. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7434. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7435. // 4.3分镜结构:每个分镜包含以下字段:
  7436. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7437. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7438. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7439. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7440. // - 运镜:场景+画面描述+运镜
  7441. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7442. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7443. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7444. // 5.$mappedArtStyle_prompt\n\n
  7445. // 示例格式:\n
  7446. // 第1集:隐形的守护者
  7447. // ###故事梗概
  7448. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7449. // ###美术风格
  7450. // 基础画风风格词:胡金铨武侠
  7451. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7452. // ###主体列表
  7453. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7454. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7455. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7456. // ###场景列表
  7457. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7458. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7459. // ###分段剧本
  7460. // 片段数量:8
  7461. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7462. // ##片段1
  7463. // 时长:12s
  7464. // 分镜1
  7465. // 场景:边境小镇街道
  7466. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7467. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7468. // 配音台词:
  7469. // 背景音效:
  7470. // 分镜2
  7471. // 场景:悦来酒馆
  7472. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7473. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7474. // 配音台词:
  7475. // 背景音效:
  7476. // 分镜3
  7477. // 场景:悦来酒馆
  7478. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7479. // 运镜:从中景推向令牌特写。
  7480. // 配音台词:
  7481. // 背景音效:
  7482. // 分镜4
  7483. // 场景:悦来酒馆
  7484. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7485. // 运镜:极速推向酒水溅起的瞬间。
  7486. // 配音台词:
  7487. // 背景音效:
  7488. // 分镜5
  7489. // 镜头描述
  7490. // 场景:悦来酒馆
  7491. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7492. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7493. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7494. // 背景音效:
  7495. // \n\n";
  7496. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7497. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7498. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7499. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7500. 普通要求:
  7501. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7502. {$role_demo}
  7503. {$scene_demo}
  7504. {$prop_demo}
  7505. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7506. 5.1片段分割逻辑(优先级从高到低):
  7507. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7508. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7509. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7510. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7511. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7512. - 片段数量格式为: 片段数量:8
  7513. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7514. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7515. 5.3分镜结构:每个分镜包含以下字段:
  7516. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7517. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7518. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7519. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7520. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7521. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7522. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7523. - 运镜:场景+画面描述+运镜
  7524. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7525. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7526. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7527. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7528. 6.《情绪-视听语言映射表》:
  7529. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7530. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7531. -----|---------|------------|----------------
  7532. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7533. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7534. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7535. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7536. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7537. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7538. -----|---------|------------|----------------
  7539. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7540. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7541. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7542. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7543. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7544. --------|---------|--------------|-------------
  7545. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7546. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7547. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7548. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7549. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7550. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7551. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7552. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7553. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7554. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7555. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7556. -----|---------|------------|------------
  7557. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7558. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7559. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7560. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7561. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7562. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7563. --------|---------|--------------|----------
  7564. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7565. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7566. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7567. 6.6 声音设计与潜意识影响 (Soundscape)
  7568. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7569. -----|---------|------------|------------------
  7570. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7571. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7572. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7573. 理论基石:
  7574. - The Five C's of Cinematography by Joseph V. Mascelli
  7575. - Film Art: An Introduction by David Bordwell
  7576. - Sight, Sound, Motion by Herbert Zettl
  7577. - Notes on the Cinematograph by Robert Bresson
  7578. \n\n
  7579. 7.{$mappedArtStyle_prompt}
  7580. 示例格式:\n
  7581. 第1集:隐形的守护者
  7582. ###故事梗概
  7583. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7584. ###美术风格
  7585. 基础画风风格词:胡金铨武侠
  7586. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7587. ###主体列表
  7588. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7589. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7590. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7591. ###场景列表
  7592. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7593. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7594. ###道具列表
  7595. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7596. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7597. ###分段剧本
  7598. 片段数量:8
  7599. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7600. ##片段1
  7601. 时长:12s
  7602. 分镜1
  7603. 出场角色:刀疤脸
  7604. 场景:边境小镇街道
  7605. 出场道具:酒杯-高脚杯
  7606. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7607. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7608. 配音台词:
  7609. 背景音效:
  7610. 分镜2
  7611. 出场角色:刀疤脸
  7612. 场景:悦来酒馆
  7613. 出场道具:酒杯-高脚杯
  7614. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7615. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7616. 配音台词:
  7617. 背景音效:
  7618. 分镜3
  7619. 出场角色:刀疤脸
  7620. 场景:悦来酒馆
  7621. 出场道具:酒杯-高脚杯
  7622. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7623. 运镜:从中景推向令牌特写。
  7624. 配音台词:
  7625. 背景音效:
  7626. 分镜4
  7627. 出场角色:刀疤脸
  7628. 场景:悦来酒馆
  7629. 出场道具:酒杯-高脚杯
  7630. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7631. 运镜:极速推向酒水溅起的瞬间。
  7632. 配音台词:
  7633. 背景音效:
  7634. 分镜5
  7635. 出场角色:刀疤脸
  7636. 场景:悦来酒馆
  7637. 出场道具:酒杯-高脚杯
  7638. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7639. 运镜:固定机位,利用倾斜构图制造压迫感。
  7640. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7641. 背景音效:
  7642. \n\n";
  7643. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7644. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7645. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7646. $prompt = $origin_prompt;
  7647. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7648. // 获取章节内容
  7649. $full_content = getProp($anime, 'content');
  7650. if ($uploaded_content) {
  7651. $full_content = $uploaded_content;
  7652. }
  7653. // 根据章节内容拆分章节
  7654. $chapters = splitContent($full_content);
  7655. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7656. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7657. $messages = [];
  7658. if ($prompt == '确认分镜大纲') {
  7659. // 暂时保留
  7660. $content = $chapter_content;
  7661. if ($is_single) $content = $full_content; // 单剧集使用全文
  7662. if (!$content) {
  7663. Utils::throwError('20003:章节内容无法获取,请确认');
  7664. }
  7665. $question = $is_single
  7666. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7667. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7668. // 构建消息
  7669. $messages[] =
  7670. [
  7671. 'role' => 'user',
  7672. 'content' => $question
  7673. ];
  7674. }else if ($prompt == '继续策划下一集') {
  7675. if ($is_single) {
  7676. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7677. }
  7678. $content = $chapter_content;
  7679. if (!$content) {
  7680. Utils::throwError('20003:章节内容无法获取,请确认');
  7681. }
  7682. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7683. // 获取上一集最后记录
  7684. $prev_sequence = $episode_number - 1;
  7685. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7686. // 构建消息
  7687. $messages[] =
  7688. [
  7689. 'role' => 'user',
  7690. 'content' => $question
  7691. ];
  7692. // dd($messages);
  7693. }else {
  7694. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7695. if (!$content) {
  7696. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7697. }
  7698. if (!$content) {
  7699. Utils::throwError('20003:章节内容无法获取,请确认');
  7700. }
  7701. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7702. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7703. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7704. if ($origin_prompt) {
  7705. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7706. }
  7707. $messages[] =
  7708. [
  7709. 'role' => 'user',
  7710. 'content' => $question
  7711. ];
  7712. }
  7713. // 处理文本模型
  7714. $model = getProp($data, 'model');
  7715. if (!$model) {
  7716. // 用户没有输入,从anime表获取
  7717. $model = getProp($anime, 'model');
  7718. if (!$model) {
  7719. // anime表也没有,使用默认值
  7720. $model = 'deepseek-v4-pro';
  7721. }
  7722. }
  7723. // 验证模型是否在可用模型表中
  7724. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7725. $model = 'deepseek-v4-pro';
  7726. }
  7727. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7728. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7729. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7730. if ($model === 'deepseek-chat') {
  7731. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7732. $model = 'deepseek-v4-flash';
  7733. $thinkingMode = 'disabled';
  7734. } elseif ($model === 'deepseek-reasoner') {
  7735. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7736. $model = 'deepseek-v4-flash';
  7737. $thinkingMode = 'enabled';
  7738. }
  7739. $post_data = [
  7740. 'model' => $model,
  7741. 'messages' => $messages,
  7742. // 'max_tokens' => 8192,
  7743. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7744. 'frequency_penalty' => 0,
  7745. 'presence_penalty' => 0,
  7746. 'response_format' => ['type' => 'text'],
  7747. 'thinking' => ['type' => $thinkingMode],
  7748. 'stream' => true // 启用流式输出
  7749. ];
  7750. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7751. // 根据模型类型选择调用方法
  7752. $fullContent = '';
  7753. $fullReasoningContent = '';
  7754. $usage = [];
  7755. try {
  7756. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7757. // DeepSeek 官方模型使用 DeepSeek API
  7758. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7759. } else if (in_array($model, $this->gpt_text_models)) {
  7760. // GPT-5.4 模型使用 TokenRouter API
  7761. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7762. } else {
  7763. // 其他模型使用火山引擎API
  7764. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7765. }
  7766. // 验证返回值类型
  7767. if (!is_iterable($streamGenerator)) {
  7768. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7769. dLog('deepseek')->error('chat流式生成器无效', [
  7770. 'generator_type' => $errorType,
  7771. 'model' => $model,
  7772. 'anime_id' => $anime_id,
  7773. 'episode_number' => $episode_number
  7774. ]);
  7775. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7776. 'type' => $errorType,
  7777. 'model' => $model
  7778. ]);
  7779. yield [
  7780. 'type' => 'error',
  7781. 'episode' => [],
  7782. 'answer' => '',
  7783. 'reasoning' => '',
  7784. 'usage' => [],
  7785. 'error' => '接口返回数据异常,请重新请求'
  7786. ];
  7787. return;
  7788. }
  7789. // 处理流式输出
  7790. foreach ($streamGenerator as $chunk) {
  7791. if (isset($chunk['type'])) {
  7792. if ($chunk['type'] === 'done') {
  7793. // 最终结果
  7794. $fullContent = $chunk['full_content'];
  7795. $fullReasoningContent = $chunk['full_reasoning'];
  7796. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7797. } else {
  7798. // 逐块yield数据
  7799. yield $chunk;
  7800. }
  7801. }
  7802. }
  7803. } catch (\Exception $e) {
  7804. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7805. 'model' => $model,
  7806. 'anime_id' => $anime_id,
  7807. 'episode_number' => $episode_number,
  7808. 'trace' => $e->getTraceAsString()
  7809. ]);
  7810. logDB('deepseek', 'error', 'chat流式处理失败', [
  7811. 'error' => $e->getMessage(),
  7812. 'model' => $model
  7813. ]);
  7814. yield [
  7815. 'type' => 'error',
  7816. 'episode' => [],
  7817. 'answer' => '',
  7818. 'reasoning' => '',
  7819. 'usage' => [],
  7820. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7821. ];
  7822. return;
  7823. }
  7824. dLog('deepseek')->info('完整内容: '.$fullContent);
  7825. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7826. // 处理完整内容并返回最终结果
  7827. $episode_arr = handleEpisodeContentForAce($fullContent);
  7828. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7829. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7830. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7831. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7832. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7833. // }
  7834. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7835. $max_retries = 3;
  7836. $retry_count = 0;
  7837. $validation_failed = false;
  7838. $validation_error_msg = '';
  7839. // 验证生成的内容
  7840. if ($anime_script_id) {
  7841. // 检查是否有acts数据
  7842. if (empty($episode_arr['acts'])) {
  7843. $validation_failed = true;
  7844. $validation_error_msg = '未生成分镜剧本相关的内容';
  7845. } else {
  7846. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7847. $generated_roles = array_column($episode_arr['roles'], 'role');
  7848. // 过滤掉"旁白"角色
  7849. $generated_roles = array_filter($generated_roles, function($role) {
  7850. return $role !== '旁白';
  7851. });
  7852. $expected_roles = array_keys($extra_roles);
  7853. // 找出生成的主体中不在预期列表中的主体
  7854. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7855. if (!empty($invalid_roles)) {
  7856. $validation_failed = true;
  7857. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7858. }
  7859. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7860. if (!$validation_failed) {
  7861. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7862. $expected_scenes = array_keys($extra_scenes);
  7863. // 找出生成的场景中不在预期列表中的场景
  7864. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7865. if (!empty($invalid_scenes)) {
  7866. $validation_failed = true;
  7867. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7868. }
  7869. }
  7870. }
  7871. } else {
  7872. // 如果没有anime_script_id,只检查是否有acts数据
  7873. if (empty($episode_arr['acts'])) {
  7874. $validation_failed = true;
  7875. $validation_error_msg = '未生成分镜剧本相关的内容';
  7876. }
  7877. }
  7878. // 重试逻辑
  7879. while ($validation_failed && $retry_count < $max_retries) {
  7880. $retry_count++;
  7881. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7882. 'reason' => $validation_error_msg,
  7883. 'anime_id' => $anime_id,
  7884. 'episode_number' => $episode_number
  7885. ]);
  7886. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7887. 'reason' => $validation_error_msg,
  7888. 'anime_id' => $anime_id
  7889. ]);
  7890. // 发送流式重试提示
  7891. yield [
  7892. 'type' => 'retry',
  7893. 'retry_count' => $retry_count,
  7894. 'reason' => $validation_error_msg
  7895. ];
  7896. // 构建重试提示词
  7897. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7898. if ($anime_script_id) {
  7899. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7900. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7901. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7902. } else {
  7903. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7904. }
  7905. // 添加重试消息到messages
  7906. $messages[] = [
  7907. 'role' => 'assistant',
  7908. 'content' => $fullContent
  7909. ];
  7910. $messages[] = [
  7911. 'role' => 'user',
  7912. 'content' => $retry_prompt
  7913. ];
  7914. // 更新post_data的messages
  7915. $post_data['messages'] = $messages;
  7916. // 重新调用API
  7917. try {
  7918. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7919. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7920. } else if (in_array($model, $this->gpt_text_models)) {
  7921. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7922. } else {
  7923. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7924. }
  7925. // 处理流式输出
  7926. $fullContent = '';
  7927. $fullReasoningContent = '';
  7928. foreach ($streamGenerator as $chunk) {
  7929. if (isset($chunk['type'])) {
  7930. if ($chunk['type'] === 'done') {
  7931. $fullContent = $chunk['full_content'];
  7932. $fullReasoningContent = $chunk['full_reasoning'];
  7933. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7934. } else {
  7935. yield $chunk;
  7936. }
  7937. }
  7938. }
  7939. // 重新解析内容
  7940. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7941. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7942. $episode_arr = handleEpisodeContentForAce($fullContent);
  7943. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7944. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7945. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7946. // }
  7947. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7948. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7949. // 重新验证
  7950. $validation_failed = false;
  7951. $validation_error_msg = '';
  7952. if ($anime_script_id) {
  7953. if (empty($episode_arr['acts'])) {
  7954. $validation_failed = true;
  7955. $validation_error_msg = '未生成分镜剧本相关的内容';
  7956. } else {
  7957. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7958. $generated_roles = array_column($episode_arr['roles'], 'role');
  7959. // 过滤掉"旁白"角色
  7960. $generated_roles = array_filter($generated_roles, function($role) {
  7961. return $role !== '旁白';
  7962. });
  7963. $expected_roles = array_keys($extra_roles);
  7964. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7965. if (!empty($invalid_roles)) {
  7966. $validation_failed = true;
  7967. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7968. }
  7969. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7970. if (!$validation_failed) {
  7971. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7972. $expected_scenes = array_keys($extra_scenes);
  7973. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7974. if (!empty($invalid_scenes)) {
  7975. $validation_failed = true;
  7976. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7977. }
  7978. }
  7979. }
  7980. } else {
  7981. if (empty($episode_arr['acts'])) {
  7982. $validation_failed = true;
  7983. $validation_error_msg = '未生成分镜剧本相关的内容';
  7984. }
  7985. }
  7986. } catch (\Exception $e) {
  7987. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7988. 'trace' => $e->getTraceAsString()
  7989. ]);
  7990. break;
  7991. }
  7992. }
  7993. // 如果重试后仍然失败
  7994. if ($validation_failed) {
  7995. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7996. 'retry_count' => $retry_count,
  7997. 'last_error' => $validation_error_msg
  7998. ]);
  7999. try {
  8000. $now = date('Y-m-d H:i:s');
  8001. $records = [
  8002. [
  8003. 'uid' => $uid,
  8004. 'anime_id' => $anime_id,
  8005. 'sequence' => $episode_number,
  8006. 'role' => 'user',
  8007. 'content' => $prompt,
  8008. 'created_at' => $now,
  8009. 'updated_at' => $now
  8010. ],
  8011. [
  8012. 'uid' => $uid,
  8013. 'anime_id' => $anime_id,
  8014. 'sequence' => $episode_number,
  8015. 'role' => 'assistant',
  8016. 'content' => $fullContent,
  8017. 'created_at' => $now,
  8018. 'updated_at' => $now
  8019. ]
  8020. ];
  8021. DB::table('mp_anime_records')->insert($records);
  8022. } catch (\Exception $e) {
  8023. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8024. }
  8025. yield [
  8026. 'type' => 'done',
  8027. 'episode' => [],
  8028. 'answer' => $fullContent,
  8029. 'reasoning' => $fullReasoningContent,
  8030. 'usage' => $usage,
  8031. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8032. ];
  8033. return;
  8034. }
  8035. // 验证成功,记录日志
  8036. if ($retry_count > 0) {
  8037. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8038. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8039. }
  8040. // 老逻辑
  8041. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8042. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8043. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8044. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8045. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8046. $existing_props = is_array($existing_props) ? $existing_props : [];
  8047. $now = date('Y-m-d H:i:s');
  8048. try {
  8049. DB::beginTransaction();
  8050. $saveResult = $this->saveEpisodeVersionData(
  8051. $anime_id,
  8052. $episode_number,
  8053. $episode_arr,
  8054. $existing_roles,
  8055. $existing_scenes,
  8056. $existing_props,
  8057. $current_episode,
  8058. $base_episode,
  8059. $is_regenerate_version,
  8060. $content,
  8061. $now,
  8062. $ref_products
  8063. );
  8064. $episode = $saveResult['episode'];
  8065. $episode_id = $saveResult['episode_id'];
  8066. $merged_roles = $saveResult['merged_roles'];
  8067. $merged_scenes = $saveResult['merged_scenes'];
  8068. $merged_props = $saveResult['merged_props'];
  8069. $record_content = $origin_prompt;
  8070. if ($uploaded_content !== '') {
  8071. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8072. }
  8073. $records = [
  8074. [
  8075. 'uid' => $uid,
  8076. 'anime_id' => $anime_id,
  8077. 'role' => 'user',
  8078. 'content' => $record_content,
  8079. 'sequence' => $episode_number,
  8080. 'episode_id' => $episode_id,
  8081. 'created_at' => $now,
  8082. 'updated_at' => $now
  8083. ],
  8084. [
  8085. 'uid' => $uid,
  8086. 'anime_id' => $anime_id,
  8087. 'role' => 'assistant',
  8088. 'content' => $fullContent,
  8089. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8090. 'sequence' => $episode_number,
  8091. 'episode_id' => $episode_id,
  8092. 'created_at' => $now,
  8093. 'updated_at' => $now
  8094. ]
  8095. ];
  8096. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8097. if (!$boolen4) {
  8098. Utils::throwError('20003:对话记录保存失败');
  8099. }
  8100. // 保存模型到anime表
  8101. $update_anime_data = [
  8102. 'model' => $model,
  8103. 'updated_at' => $now
  8104. ];
  8105. if ($uploaded_content) {
  8106. $update_anime_data['content'] = $uploaded_content;
  8107. }
  8108. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8109. }catch (\Exception $e) {
  8110. DB::rollBack();
  8111. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8112. yield [
  8113. 'type' => 'done',
  8114. 'answer' => $fullContent,
  8115. 'reasoning' => $fullReasoningContent,
  8116. 'usage' => $usage,
  8117. 'error' => $e->getMessage(),
  8118. ];
  8119. return;
  8120. }
  8121. DB::commit();
  8122. if ($is_global_generate_pics) {
  8123. // // 批量生成全局角色图片
  8124. // $this->batchSetGlobalRoleImg([
  8125. // 'anime_id' => $anime_id,
  8126. // ], true);
  8127. // // 批量生成全局场景图片
  8128. // $this->batchSetGlobalSceneImg([
  8129. // 'anime_id' => $anime_id,
  8130. // ], true);
  8131. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8132. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8133. }
  8134. $episode['episode_id'] = $episode_id;
  8135. $episode['roles'] = $merged_roles;
  8136. $episode['scenes'] = $merged_scenes;
  8137. $episode['props'] = $merged_props;
  8138. $episode['end_episode_sequence'] = $end_episode_sequence;
  8139. // 获取mp_animes表中的视频参数
  8140. $episode['video_params'] = [
  8141. 'video_model' => getProp($anime, 'video_model'),
  8142. 'video_resolution' => getProp($anime, 'video_resolution'),
  8143. 'ratio' => getProp($anime, 'video_ratio'),
  8144. ];
  8145. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8146. yield [
  8147. 'type' => 'done',
  8148. 'episode' => $episode,
  8149. 'answer' => $fullContent,
  8150. 'reasoning' => $fullReasoningContent,
  8151. 'usage' => $usage
  8152. ];
  8153. }
  8154. /**
  8155. * chatForAce的非流式版本 - 用于定时任务
  8156. * 只获取最终 type=done 的数据,并验证必要字段
  8157. *
  8158. * @param array $data 请求数据
  8159. * @return array 生成结果
  8160. */
  8161. public function chatForAceNonStream($data) {
  8162. $finalResult = null;
  8163. // 调用流式方法,只保存 type=done 的数据
  8164. foreach ($this->chatForAce($data) as $chunk) {
  8165. // 只关注最终结果
  8166. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8167. $finalResult = $chunk;
  8168. break; // 找到 done 就退出循环
  8169. }
  8170. }
  8171. // 验证最终结果
  8172. if (!$finalResult) {
  8173. return ['error' => '生成失败:未获取到最终结果'];
  8174. }
  8175. // 检查是否有错误
  8176. if (isset($finalResult['error']) && $finalResult['error']) {
  8177. return $finalResult;
  8178. }
  8179. // 验证必要字段
  8180. $episode = $finalResult['episode'] ?? [];
  8181. // 验证 roles
  8182. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8183. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8184. }
  8185. // 验证 scenes
  8186. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8187. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8188. }
  8189. // 验证 props(道具可以为空,但必须存在且为数组)
  8190. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8191. $episode['props'] = [];
  8192. }
  8193. // 验证 acts(分镜剧本)
  8194. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8195. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8196. }
  8197. // 更新验证后的 episode 数据
  8198. $finalResult['episode'] = $episode;
  8199. // 记录验证成功日志
  8200. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8201. 'roles_count' => count($episode['roles']),
  8202. 'scenes_count' => count($episode['scenes']),
  8203. 'props_count' => count($episode['props']),
  8204. 'acts_count' => count($episode['acts'])
  8205. ]);
  8206. return $finalResult;
  8207. }
  8208. /**
  8209. * 批量生成多个分集
  8210. *
  8211. * @param array $data 请求数据
  8212. * @return array 任务信息
  8213. */
  8214. public function batchGenerateEpisodes($data) {
  8215. $uid = Site::getUid();
  8216. $cpid = Site::getCpid();
  8217. $anime_id = getProp($data, 'anime_id');
  8218. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8219. if (!$anime_id) {
  8220. Utils::throwError('20003:anime_id参数缺失');
  8221. }
  8222. if ($generate_episode_number < 1) {
  8223. Utils::throwError('20003:生成集数必须大于0');
  8224. }
  8225. // 获取动漫信息
  8226. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8227. if (!$anime) {
  8228. Utils::throwError('20003:该剧集不存在');
  8229. }
  8230. // 检查是否是全能模式
  8231. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8232. Utils::throwError('20003:只有全能模式才支持批量生成');
  8233. }
  8234. // 检查是否是多剧集模式
  8235. if ((int)getProp($anime, 'is_multi') !== 1) {
  8236. Utils::throwError('20003:单剧集不支持批量生成');
  8237. }
  8238. // 获取当前已生成的最大集数
  8239. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8240. ->where('anime_id', $anime_id)
  8241. ->where('is_default', 1)
  8242. ->max('episode_number');
  8243. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8244. // 确定起始集数
  8245. $startEpisodeNumber = $currentMaxEpisode + 1;
  8246. // 计算结束集数
  8247. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8248. // 检查是否超过总集数限制
  8249. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8250. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8251. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8252. }
  8253. $now = date('Y-m-d H:i:s');
  8254. $createdTasks = [];
  8255. $skippedTasks = [];
  8256. // 为每一集创建详情记录
  8257. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8258. // 检查是否已有该集的任务记录
  8259. $existingTask = DB::table('mp_batch_episode_generation_details')
  8260. ->where('anime_id', $anime_id)
  8261. ->where('episode_number', $episodeNumber)
  8262. ->first();
  8263. if ($existingTask) {
  8264. // 如果已存在且未完成,跳过
  8265. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8266. $skippedTasks[] = $episodeNumber;
  8267. continue;
  8268. }
  8269. // 如果是失败状态,可以重新创建(删除旧记录)
  8270. if ($existingTask->status === 'failed') {
  8271. DB::table('mp_batch_episode_generation_details')
  8272. ->where('id', $existingTask->id)
  8273. ->delete();
  8274. }
  8275. // 如果是已完成状态,也跳过
  8276. if ($existingTask->status === 'completed') {
  8277. $skippedTasks[] = $episodeNumber;
  8278. continue;
  8279. }
  8280. }
  8281. // 准备任务数据
  8282. $taskData = [
  8283. 'anime_id' => $anime_id,
  8284. 'uid' => $uid,
  8285. 'cpid' => $cpid,
  8286. 'episode_number' => $episodeNumber,
  8287. 'status' => 'pending',
  8288. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8289. 'retry_count' => 0,
  8290. 'created_at' => $now,
  8291. 'updated_at' => $now
  8292. ];
  8293. // 创建任务记录
  8294. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8295. if ($taskId) {
  8296. $createdTasks[] = $episodeNumber;
  8297. }
  8298. }
  8299. if (empty($createdTasks)) {
  8300. if (!empty($skippedTasks)) {
  8301. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8302. } else {
  8303. Utils::throwError('20003:创建批量生成任务失败');
  8304. }
  8305. }
  8306. return [
  8307. 'anime_id' => $anime_id,
  8308. 'start_episode' => $startEpisodeNumber,
  8309. 'end_episode' => $endEpisodeNumber,
  8310. 'total_episodes' => $generate_episode_number,
  8311. 'created_episodes' => $createdTasks,
  8312. 'skipped_episodes' => $skippedTasks,
  8313. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8314. "已创建: " . implode(',', $createdTasks) .
  8315. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8316. ];
  8317. }
  8318. /**
  8319. * 获取批量生成任务状态
  8320. *
  8321. * @param array $data 请求数据
  8322. * @return array 任务状态信息
  8323. */
  8324. public function getBatchGenerationTaskStatus($data) {
  8325. $anime_id = getProp($data, 'anime_id');
  8326. if (!$anime_id) {
  8327. Utils::throwError('20003:anime_id参数缺失');
  8328. }
  8329. // 获取该anime的所有任务
  8330. $tasks = DB::table('mp_batch_episode_generation_details')
  8331. ->where('anime_id', $anime_id)
  8332. ->orderBy('episode_number')
  8333. ->get()
  8334. ->map(function($item) {
  8335. return [
  8336. 'id' => $item->id,
  8337. 'episode_number' => $item->episode_number,
  8338. 'status' => $item->status,
  8339. 'error_message' => $item->error_message,
  8340. 'retry_count' => $item->retry_count,
  8341. 'created_at' => $item->created_at,
  8342. 'updated_at' => $item->updated_at,
  8343. 'completed_at' => $item->completed_at
  8344. ];
  8345. })
  8346. ->toArray();
  8347. if (empty($tasks)) {
  8348. Utils::throwError('20003:该剧集没有批量生成任务');
  8349. }
  8350. // 统计各状态数量
  8351. $totalCount = count($tasks);
  8352. $pendingCount = 0;
  8353. $processingCount = 0;
  8354. $completedCount = 0;
  8355. $failedCount = 0;
  8356. foreach ($tasks as $task) {
  8357. switch ($task['status']) {
  8358. case 'pending':
  8359. $pendingCount++;
  8360. break;
  8361. case 'processing':
  8362. $processingCount++;
  8363. break;
  8364. case 'completed':
  8365. $completedCount++;
  8366. break;
  8367. case 'failed':
  8368. $failedCount++;
  8369. break;
  8370. }
  8371. }
  8372. // 计算进度百分比
  8373. $progress = 0;
  8374. if ($totalCount > 0) {
  8375. $progress = round(($completedCount / $totalCount) * 100, 2);
  8376. }
  8377. // 判断整体状态
  8378. $overallStatus = 'processing';
  8379. if ($completedCount === $totalCount) {
  8380. $overallStatus = 'completed';
  8381. } elseif ($pendingCount === $totalCount) {
  8382. $overallStatus = 'pending';
  8383. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8384. $overallStatus = 'failed';
  8385. }
  8386. return [
  8387. 'anime_id' => $anime_id,
  8388. 'total_episodes' => $totalCount,
  8389. 'pending_count' => $pendingCount,
  8390. 'processing_count' => $processingCount,
  8391. 'completed_count' => $completedCount,
  8392. 'failed_count' => $failedCount,
  8393. 'progress' => $progress,
  8394. 'overall_status' => $overallStatus,
  8395. 'tasks' => $tasks
  8396. ];
  8397. }
  8398. /**
  8399. * 智能匹配并替换主体和场景名称
  8400. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8401. *
  8402. * @param array $episode_arr 解析后的剧集数据
  8403. * @param array $extra_roles 强制主体设定(key为主体名称)
  8404. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8405. * @return array 替换后的剧集数据
  8406. */
  8407. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8408. $replaced_count = 0;
  8409. // 1. 处理主体列表
  8410. if (!empty($episode_arr['roles'])) {
  8411. foreach ($episode_arr['roles'] as &$role) {
  8412. $generated_role_name = $role['role'] ?? '';
  8413. // 跳过旁白
  8414. if ($generated_role_name === '旁白') {
  8415. continue;
  8416. }
  8417. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8418. if (!isset($extra_roles[$generated_role_name])) {
  8419. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8420. if ($matched_role) {
  8421. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8422. $role['role'] = $matched_role;
  8423. $replaced_count++;
  8424. }
  8425. }
  8426. }
  8427. }
  8428. // 2. 处理场景列表
  8429. if (!empty($episode_arr['scenes'])) {
  8430. foreach ($episode_arr['scenes'] as &$scene) {
  8431. $generated_scene_name = $scene['scene'] ?? '';
  8432. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8433. if (!isset($extra_scenes[$generated_scene_name])) {
  8434. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8435. if ($matched_scene) {
  8436. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8437. $scene['scene'] = $matched_scene;
  8438. $replaced_count++;
  8439. }
  8440. }
  8441. }
  8442. }
  8443. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8444. if (!empty($episode_arr['acts'])) {
  8445. foreach ($episode_arr['acts'] as &$act) {
  8446. if (!empty($act['segments'])) {
  8447. foreach ($act['segments'] as &$segment) {
  8448. if (!empty($segment['segment_content'])) {
  8449. $original_content = $segment['segment_content'];
  8450. $replaced_content = $original_content;
  8451. // 替换场景名 - 在文本中查找并替换
  8452. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8453. // 尝试找到可能的短名称
  8454. $potential_short_names = [];
  8455. // 提取场景名的主要部分(冒号之前)
  8456. if (mb_strpos($full_scene_name, ':') !== false) {
  8457. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8458. $potential_short_names[] = $short_name;
  8459. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8460. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8461. $potential_short_names[] = $short_name;
  8462. }
  8463. // 替换场景字段中的短名称
  8464. foreach ($potential_short_names as $short_name) {
  8465. if ($short_name !== $full_scene_name) {
  8466. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8467. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8468. if ($new_content !== $replaced_content) {
  8469. $replaced_content = $new_content;
  8470. $replaced_count++;
  8471. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8472. }
  8473. }
  8474. }
  8475. }
  8476. // 替换配音角色名(跳过旁白)
  8477. foreach (array_keys($extra_roles) as $full_role_name) {
  8478. if ($full_role_name === '旁白') {
  8479. continue;
  8480. }
  8481. // 尝试找到可能的短名称
  8482. $potential_short_names = [];
  8483. // 提取角色名的主要部分(短横线之前)
  8484. if (mb_strpos($full_role_name, '-') !== false) {
  8485. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8486. $potential_short_names[] = $short_name;
  8487. }
  8488. // 替换配音台词中的短名称
  8489. foreach ($potential_short_names as $short_name) {
  8490. if ($short_name !== $full_role_name) {
  8491. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8492. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8493. if ($new_content !== $replaced_content) {
  8494. $replaced_content = $new_content;
  8495. $replaced_count++;
  8496. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8497. }
  8498. }
  8499. }
  8500. }
  8501. // 如果有替换,更新segment_content
  8502. if ($replaced_content !== $original_content) {
  8503. $segment['segment_content'] = $replaced_content;
  8504. }
  8505. }
  8506. }
  8507. }
  8508. }
  8509. }
  8510. if ($replaced_count > 0) {
  8511. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8512. 'replaced_count' => $replaced_count
  8513. ]);
  8514. }
  8515. return $episode_arr;
  8516. }
  8517. /**
  8518. * 查找匹配的名称
  8519. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8520. *
  8521. * @param string $generated_name 生成的名称
  8522. * @param array $expected_names 预期的名称列表
  8523. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8524. */
  8525. private function findMatchingName($generated_name, $expected_names) {
  8526. if (empty($generated_name)) {
  8527. return null;
  8528. }
  8529. // 尝试精确匹配
  8530. if (in_array($generated_name, $expected_names)) {
  8531. return $generated_name;
  8532. }
  8533. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8534. foreach ($expected_names as $expected_name) {
  8535. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8536. if (mb_strpos($expected_name, $generated_name) === 0) {
  8537. return $expected_name;
  8538. }
  8539. }
  8540. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8541. // 这样可以处理一些变体,但优先级较低
  8542. foreach ($expected_names as $expected_name) {
  8543. if (mb_strpos($expected_name, $generated_name) !== false) {
  8544. return $expected_name;
  8545. }
  8546. }
  8547. return null;
  8548. }
  8549. /**
  8550. * 重新生成分段剧本
  8551. * @param array $data 包含以下字段:
  8552. * - prompt: string|null 用户修改要求(可选)
  8553. * - template_id: int|null 提示词模板ID(可选)
  8554. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8555. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8556. * @return array 返回生成结果
  8557. */
  8558. public function regenerateSegmentScript($data) {
  8559. $uid = Site::getUid();
  8560. $prompt = trim((string)getProp($data, 'prompt', ''));
  8561. $template_id = getProp($data, 'template_id', 0);
  8562. $act_id = getProp($data, 'act_id', 0);
  8563. $episode_id = getProp($data, 'episode_id', 0);
  8564. // 验证:prompt和template_id至少提供一个
  8565. if (empty($prompt) && empty($template_id)) {
  8566. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8567. }
  8568. // 验证:act_id和episode_id二选一
  8569. if (empty($act_id) && empty($episode_id)) {
  8570. Utils::throwError('20003:请提供片段ID或剧集ID');
  8571. }
  8572. if (!empty($act_id) && !empty($episode_id)) {
  8573. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8574. }
  8575. // 如果提供了template_id,获取模板提示词
  8576. $template_prompt = '';
  8577. if ($template_id > 0) {
  8578. $template = DB::table('mp_prompt_templates')
  8579. ->where('id', $template_id)
  8580. ->where('is_deleted', 0)
  8581. ->first();
  8582. if (!$template) {
  8583. Utils::throwError('20003:提示词模板不存在或已删除');
  8584. }
  8585. $template_prompt = $template->template_prompt ?? '';
  8586. }
  8587. // 合并用户提示词和模板提示词
  8588. $final_prompt = '';
  8589. if (!empty($template_prompt)) {
  8590. $final_prompt = $template_prompt;
  8591. if (!empty($prompt)) {
  8592. $final_prompt .= "\n\n补充要求:" . $prompt;
  8593. }
  8594. } else {
  8595. $final_prompt = $prompt;
  8596. }
  8597. // 获取需要重新生成的内容参考
  8598. $reference_content = '';
  8599. $target_episode_id = 0;
  8600. $target_anime_id = 0;
  8601. $target_episode_number = 0;
  8602. if ($act_id > 0) {
  8603. // 单个片段模式:获取该片段的内容
  8604. $segment = DB::table('mp_episode_segments')
  8605. ->where('id', $act_id)
  8606. ->first();
  8607. if (!$segment) {
  8608. Utils::throwError('20003:片段不存在');
  8609. }
  8610. $target_episode_id = $segment->episode_id;
  8611. $target_anime_id = $segment->anime_id;
  8612. $target_episode_number = $segment->episode_number;
  8613. $reference_content = $segment->act_content ?? '';
  8614. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8615. } else {
  8616. // 整个剧集模式:获取所有片段的内容
  8617. $segments = DB::table('mp_episode_segments')
  8618. ->where('episode_id', $episode_id)
  8619. ->orderBy('act_number')
  8620. ->get();
  8621. if ($segments->isEmpty()) {
  8622. Utils::throwError('20003:该剧集没有片段数据');
  8623. }
  8624. $target_episode_id = $episode_id;
  8625. $target_anime_id = $segments[0]->anime_id;
  8626. $target_episode_number = $segments[0]->episode_number;
  8627. // 拼接所有片段内容,保留格式用于AI理解
  8628. $act_contents = [];
  8629. foreach ($segments as $seg) {
  8630. $act_number = $seg->act_number;
  8631. $act_content = $seg->act_content ?? '';
  8632. if (!empty($act_content)) {
  8633. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8634. }
  8635. }
  8636. $reference_content = implode("\n\n", $act_contents);
  8637. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8638. if ($episode_content) {
  8639. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8640. }else {
  8641. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8642. }
  8643. }
  8644. if (empty($reference_content)) {
  8645. Utils::throwError('20003:没有可参考的片段内容');
  8646. }
  8647. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8648. $episode = DB::table('mp_anime_episodes')
  8649. ->where('id', $target_episode_id)
  8650. ->first();
  8651. if (!$episode) {
  8652. Utils::throwError('20003:剧集不存在');
  8653. }
  8654. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8655. $anime_script_id = getProp($anime, 'script_id');
  8656. $intro = $episode->intro ?? '';
  8657. $art_style = $episode->art_style ?? '';
  8658. $roles = json_decode($episode->roles ?? '[]', true);
  8659. $scenes = json_decode($episode->scenes ?? '[]', true);
  8660. $props = json_decode($episode->props ?? '[]', true);
  8661. // 构建提示词中的主体列表和场景列表参考
  8662. $roles_ref = '';
  8663. if (!empty($roles) && is_array($roles)) {
  8664. $roles_list = [];
  8665. foreach ($roles as $role) {
  8666. $role_name = getProp($role, 'role', '');
  8667. $role_desc = getProp($role, 'description', '');
  8668. $pic_prompt = getProp($role, 'pic_prompt', '');
  8669. $voice_prompt = getProp($role, 'voice_prompt', '');
  8670. if (!empty($role_name)) {
  8671. $role_line = $role_name;
  8672. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8673. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8674. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8675. $roles_list[] = $role_line;
  8676. }
  8677. }
  8678. if (!empty($roles_list)) {
  8679. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8680. }
  8681. }
  8682. $scenes_ref = '';
  8683. if (!empty($scenes) && is_array($scenes)) {
  8684. $scenes_list = [];
  8685. foreach ($scenes as $scene) {
  8686. $scene_name = getProp($scene, 'scene', '');
  8687. $scene_desc = getProp($scene, 'description', '');
  8688. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8689. if (!empty($scene_name)) {
  8690. $scene_line = $scene_name;
  8691. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8692. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8693. $scenes_list[] = $scene_line;
  8694. }
  8695. }
  8696. if (!empty($scenes_list)) {
  8697. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8698. }
  8699. }
  8700. $props_ref = '';
  8701. if (!empty($props) && is_array($props)) {
  8702. $props_list = [];
  8703. foreach ($props as $prop) {
  8704. $prop_name = getProp($prop, 'prop', '');
  8705. $prop_desc = getProp($prop, 'description', '');
  8706. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8707. if (!empty($prop_name)) {
  8708. $prop_line = $prop_name;
  8709. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8710. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8711. $props_list[] = $prop_line;
  8712. }
  8713. }
  8714. if (!empty($props_list)) {
  8715. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8716. }
  8717. }
  8718. // 构建美术风格参考
  8719. $art_style_ref = '';
  8720. if (!empty($art_style)) {
  8721. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8722. }
  8723. // 构建内容简介参考
  8724. $intro_ref = '';
  8725. if (!empty($intro)) {
  8726. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8727. }
  8728. // 构建完整的AI提示词
  8729. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8730. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8731. $user_prompt .= $intro_ref;
  8732. $user_prompt .= $art_style_ref;
  8733. $user_prompt .= $reference_content;
  8734. // $user_prompt .= $roles_ref;
  8735. // $user_prompt .= $scenes_ref;
  8736. $system_prompt = "\n\n【强制要求】\n";
  8737. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8738. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8739. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8740. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8741. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8742. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8743. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8744. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8745. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8746. ###分段剧本
  8747. 片段数量:8
  8748. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8749. ##片段1
  8750. 时长:12s
  8751. 分镜1
  8752. 出场角色:刀疤脸
  8753. 场景:边境小镇街道
  8754. 出场道具:酒杯-高脚杯
  8755. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8756. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8757. 配音台词:
  8758. 背景音效:
  8759. 分镜2
  8760. 出场角色:刀疤脸
  8761. 场景:悦来酒馆
  8762. 出场道具:酒杯-高脚杯
  8763. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8764. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8765. 配音台词:
  8766. 背景音效:
  8767. 分镜3
  8768. 出场角色:刀疤脸
  8769. 场景:悦来酒馆
  8770. 出场道具:酒杯-高脚杯
  8771. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8772. 运镜:从中景推向令牌特写。
  8773. 配音台词:
  8774. 背景音效:
  8775. 分镜4
  8776. 出场角色:刀疤脸
  8777. 场景:悦来酒馆
  8778. 出场道具:酒杯-高脚杯
  8779. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8780. 运镜:极速推向酒水溅起的瞬间。
  8781. 配音台词:
  8782. 背景音效:
  8783. 分镜5
  8784. 出场角色:刀疤脸
  8785. 场景:悦来酒馆
  8786. 出场道具:酒杯-高脚杯
  8787. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8788. 运镜:固定机位,利用倾斜构图制造压迫感。
  8789. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8790. 背景音效:";
  8791. // 获取模型配置
  8792. $model = getProp($data, 'model');
  8793. if (!$model) {
  8794. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8795. }
  8796. // 验证模型是否在可用模型表中
  8797. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8798. $model = 'deepseek-v4-pro';
  8799. }
  8800. // 模型兼容性处理
  8801. $thinkingMode = 'disabled';
  8802. $reasoningEffort = 'high';
  8803. if ($model === 'deepseek-chat') {
  8804. $model = 'deepseek-v4-flash';
  8805. $thinkingMode = 'disabled';
  8806. } elseif ($model === 'deepseek-reasoner') {
  8807. $model = 'deepseek-v4-flash';
  8808. $thinkingMode = 'enabled';
  8809. }
  8810. // 构建消息
  8811. $messages = [
  8812. [
  8813. 'role' => 'system',
  8814. 'content' => $system_prompt
  8815. ],
  8816. [
  8817. 'role' => 'user',
  8818. 'content' => $user_prompt
  8819. ]
  8820. ];
  8821. // dd($messages);
  8822. // 构建请求参数
  8823. $post_data = [
  8824. 'model' => $model,
  8825. 'messages' => $messages,
  8826. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8827. 'frequency_penalty' => 0,
  8828. 'presence_penalty' => 0,
  8829. 'response_format' => ['type' => 'text'],
  8830. 'thinking' => ['type' => $thinkingMode],
  8831. 'stream' => false // 非流式输出
  8832. ];
  8833. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8834. // 调用AI生成新的分段剧本
  8835. try {
  8836. $fullContent = '';
  8837. $usage = [];
  8838. // 根据模型类型选择调用方法
  8839. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8840. // DeepSeek 官方模型使用 DeepSeek API
  8841. $chatResult = $this->chatOnly($post_data);
  8842. } else if (in_array($model, $this->gpt_text_models)) {
  8843. // GPT 模型使用 TokenRouter API
  8844. $chatResult = $this->gpt54ChatOnly($post_data);
  8845. } else {
  8846. // 其他模型使用火山引擎API
  8847. $chatResult = $this->volcEngineChatCompletion($post_data);
  8848. }
  8849. if (is_array($chatResult)) {
  8850. $fullContent = $chatResult['fullContent'] ?? '';
  8851. $usage = $chatResult['usage'] ?? [];
  8852. }
  8853. $generated_content = $fullContent;
  8854. if (empty($generated_content)) {
  8855. Utils::throwError('20003:AI生成内容为空,请重试');
  8856. }
  8857. // 解析生成的内容 - 按片段分割
  8858. $parsed_segments = [];
  8859. // 先在开头添加换行符,确保第1片段也能被正确分割
  8860. $normalizedText = "\n" . $generated_content;
  8861. $parts = preg_split('/\n\s*##/', $normalizedText);
  8862. foreach ($parts as $part) {
  8863. $part = trim($part);
  8864. if (empty($part)) continue;
  8865. // 匹配"片段X"格式
  8866. if (!preg_match('/^片段\d+/', $part)) {
  8867. continue;
  8868. }
  8869. // 分离标题和内容
  8870. $lines = explode("\n", $part, 2);
  8871. $actTitle = trim($lines[0]);
  8872. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8873. // 解析标题,提取序号
  8874. $actNumber = 0;
  8875. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8876. $actNumber = intval($segmentTitleMatch[1]);
  8877. } else {
  8878. $actNumber = count($parsed_segments) + 1;
  8879. }
  8880. // 提取时长(仅保留数字)
  8881. $actDuration = 0;
  8882. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8883. $actDurationStr = trim($actDurationMatch[1]);
  8884. // 提取数字部分(支持整数和小数)
  8885. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8886. $actDuration = (float)$numMatch[1];
  8887. }
  8888. }
  8889. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8890. // 只保留分镜内容,并确保分镜标记使用【】格式
  8891. $cleaned_content = '';
  8892. $content_lines = explode("\n", $actContent);
  8893. $is_capturing = false; // 标记是否开始捕获分镜内容
  8894. $count = 0;
  8895. foreach ($content_lines as $line) {
  8896. $trimmed_line = trim($line);
  8897. // 跳过时长和旁白音色行
  8898. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8899. continue;
  8900. }
  8901. // 检测是否是分镜开始
  8902. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8903. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8904. $count++;
  8905. $is_capturing = true;
  8906. // 如果没有【】,则添加
  8907. if (!preg_match('/^【/u', $trimmed_line)) {
  8908. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8909. }
  8910. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8911. }
  8912. // 如果已经开始捕获,则添加该行
  8913. if ($is_capturing && !empty($trimmed_line)) {
  8914. $cleaned_content .= $trimmed_line."\n";
  8915. }
  8916. }
  8917. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8918. $parsed_segments[] = [
  8919. 'act_number' => $actNumber,
  8920. 'act_title' => $actTitle,
  8921. 'act_duration' => $actDuration,
  8922. 'act_content' => $cleaned_content,
  8923. ];
  8924. }
  8925. if (empty($parsed_segments)) {
  8926. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8927. }
  8928. // 收集所有资产名称(角色、场景、道具)
  8929. $product_names = [];
  8930. // 收集角色名称
  8931. if (!empty($roles) && is_array($roles)) {
  8932. foreach ($roles as $role) {
  8933. $role_name = getProp($role, 'role', '');
  8934. if (!empty($role_name)) {
  8935. $product_names[] = $role_name;
  8936. }
  8937. }
  8938. }
  8939. // 收集场景名称
  8940. if (!empty($scenes) && is_array($scenes)) {
  8941. foreach ($scenes as $scene) {
  8942. $scene_name = getProp($scene, 'scene', '');
  8943. if (!empty($scene_name)) {
  8944. $product_names[] = $scene_name;
  8945. }
  8946. }
  8947. }
  8948. // 收集道具名称
  8949. if (!empty($props) && is_array($props)) {
  8950. foreach ($props as $prop) {
  8951. $prop_name = getProp($prop, 'prop', '');
  8952. if (!empty($prop_name)) {
  8953. $product_names[] = $prop_name;
  8954. }
  8955. }
  8956. }
  8957. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8958. $product_names = array_unique($product_names);
  8959. usort($product_names, function($a, $b) {
  8960. return mb_strlen($b) - mb_strlen($a);
  8961. });
  8962. // 处理每个片段的 act_show_content
  8963. foreach ($parsed_segments as &$segment) {
  8964. $act_content = getProp($segment, 'act_content', '');
  8965. if (empty($act_content)) {
  8966. $segment['act_show_content'] = '';
  8967. continue;
  8968. }
  8969. $processed_content = $act_content;
  8970. // 统一替换所有资产名称为 {资产名} 格式
  8971. // 使用占位符避免嵌套替换问题
  8972. $placeholder_map = [];
  8973. $placeholder_index = 0;
  8974. foreach ($product_names as $product_name) {
  8975. // 转义特殊字符
  8976. $escaped_product = preg_quote($product_name, '/');
  8977. // 检查是否匹配且未被 {} 包裹
  8978. $processed_content = preg_replace_callback(
  8979. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8980. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8981. // 使用唯一占位符
  8982. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8983. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8984. $placeholder_index++;
  8985. return $placeholder;
  8986. },
  8987. $processed_content
  8988. );
  8989. }
  8990. // 将所有占位符替换回实际内容
  8991. foreach ($placeholder_map as $placeholder => $replacement) {
  8992. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8993. }
  8994. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8995. $shot_counter = 0;
  8996. $processed_content = preg_replace_callback(
  8997. '/【(?:镜头|分镜)(\d+)】/u',
  8998. function($matches) use (&$shot_counter) {
  8999. $shot_counter++;
  9000. return '【镜头' . $shot_counter . '】';
  9001. },
  9002. $processed_content
  9003. );
  9004. $segment['act_show_content'] = $processed_content;
  9005. }
  9006. unset($segment); // 解除引用
  9007. // 保存到数据库
  9008. $now = date('Y-m-d H:i:s');
  9009. $saved_acts = []; // 用于记录保存后的片段信息
  9010. if ($act_id > 0) {
  9011. // 单个片段模式:更新单条记录
  9012. if (count($parsed_segments) > 0) {
  9013. $new_segment = $parsed_segments[0];
  9014. $update_data = [
  9015. 'act_content' => getProp($new_segment, 'act_content', ''),
  9016. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9017. 'act_title' => getProp($new_segment, 'act_title', ''),
  9018. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9019. 'updated_at' => $now,
  9020. ];
  9021. DB::table('mp_episode_segments')
  9022. ->where('id', $act_id)
  9023. ->update($update_data);
  9024. // 获取更新后的记录
  9025. $updated_act = DB::table('mp_episode_segments')
  9026. ->where('id', $act_id)
  9027. ->first();
  9028. if ($updated_act) {
  9029. $saved_acts[] = [
  9030. 'act_id' => $updated_act->id,
  9031. 'act_number' => $updated_act->act_number,
  9032. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9033. 'act_content' => $updated_act->act_content,
  9034. 'act_show_content' => $updated_act->act_show_content,
  9035. 'video_url' => $updated_act->video_url ?? '',
  9036. 'video_duration' => $updated_act->video_duration ?? 0,
  9037. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9038. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9039. ];
  9040. }
  9041. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9042. }
  9043. } else {
  9044. // 整个剧集模式:删除原有记录并批量保存新记录
  9045. DB::beginTransaction();
  9046. try {
  9047. // 删除原有的所有片段记录
  9048. DB::table('mp_episode_segments')
  9049. ->where('episode_id', $target_episode_id)
  9050. ->delete();
  9051. // 批量插入新的片段记录
  9052. $segments_to_insert = [];
  9053. foreach ($parsed_segments as $index => $segment) {
  9054. $act_number = $index + 1;
  9055. $segments_to_insert[] = [
  9056. 'anime_id' => $target_anime_id,
  9057. 'episode_id' => $target_episode_id,
  9058. 'episode_number' => $target_episode_number,
  9059. 'act_number' => $act_number,
  9060. 'act_title' => getProp($segment, 'act_title', ''),
  9061. 'act_duration' => getProp($segment, 'act_duration', 0),
  9062. 'act_content' => getProp($segment, 'act_content', ''),
  9063. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9064. 'created_at' => $now,
  9065. 'updated_at' => $now,
  9066. ];
  9067. }
  9068. if (!empty($segments_to_insert)) {
  9069. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9070. }
  9071. DB::commit();
  9072. // 查询保存后的所有片段记录
  9073. $saved_segments = DB::table('mp_episode_segments')
  9074. ->where('episode_id', $target_episode_id)
  9075. ->orderBy('act_number')
  9076. ->get();
  9077. foreach ($saved_segments as $saved_segment) {
  9078. $saved_acts[] = [
  9079. 'act_id' => $saved_segment->id,
  9080. 'act_number' => $saved_segment->act_number,
  9081. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9082. 'act_content' => $saved_segment->act_content,
  9083. 'act_show_content' => $saved_segment->act_show_content,
  9084. 'video_url' => $saved_segment->video_url ?? '',
  9085. 'video_duration' => $saved_segment->video_duration ?? 0,
  9086. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9087. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9088. ];
  9089. }
  9090. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9091. 'episode_id' => $target_episode_id,
  9092. 'segments_count' => count($segments_to_insert)
  9093. ]);
  9094. } catch (\Exception $e) {
  9095. DB::rollBack();
  9096. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9097. Utils::throwError('20003:保存失败,请重试');
  9098. }
  9099. }
  9100. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9101. return [
  9102. 'anime_id' => $target_anime_id,
  9103. 'episode_id' => $target_episode_id,
  9104. 'title' => getProp($episode, 'title', ''),
  9105. 'episode_number' => $target_episode_number,
  9106. 'is_generated' => getProp($episode, 'is_generated', 0),
  9107. 'acts' => $saved_acts,
  9108. ];
  9109. } catch (\Exception $e) {
  9110. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9111. throw $e;
  9112. }
  9113. }
  9114. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9115. {
  9116. $episode_arr = [
  9117. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9118. 'intro' => getProp($script_arr, 'intro'),
  9119. 'art_style' => getProp($script_arr, 'art_style'),
  9120. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9121. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9122. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9123. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9124. ];
  9125. if (empty($episode_arr['acts'])) {
  9126. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9127. if (!empty($fallback_episode_arr['acts'])) {
  9128. $episode_arr = array_merge($fallback_episode_arr, [
  9129. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9130. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9131. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9132. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9133. ]);
  9134. }
  9135. }
  9136. // if (!getProp($episode_arr, 'episode_title')) {
  9137. // $episode_title = '';
  9138. // $episodes = getProp($script_arr, 'episodes', []);
  9139. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9140. // $episode_title = '第1集:' . $episodes[0]['title'];
  9141. // }
  9142. // if (!$episode_title) {
  9143. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9144. // }
  9145. // $episode_arr['episode_title'] = $episode_title;
  9146. // }
  9147. return $episode_arr;
  9148. }
  9149. private function saveEpisodeVersionData(
  9150. int $anime_id,
  9151. int $episode_number,
  9152. array $episode_arr,
  9153. array $existing_roles,
  9154. array $existing_scenes,
  9155. array $existing_props,
  9156. $current_episode,
  9157. $base_episode,
  9158. bool $is_regenerate_version,
  9159. string $content,
  9160. string $now,
  9161. array $ref_products = []
  9162. ): array {
  9163. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9164. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9165. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9166. // 过滤掉关键字段为空的条目
  9167. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9168. return !empty($item['role'] ?? null);
  9169. }));
  9170. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9171. return !empty($item['scene'] ?? null);
  9172. }));
  9173. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9174. return !empty($item['prop'] ?? null);
  9175. }));
  9176. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9177. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9178. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9179. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9180. $ace_mode = getProp($anime, 'ace_mode');
  9181. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9182. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9183. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9184. $global_roles = is_array($global_roles) ? $global_roles : [];
  9185. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9186. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9187. $art_style_type = getProp($anime, 'art_style_type');
  9188. // 检查并创建 roles 的图片生成任务
  9189. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9190. // 检查并创建 scenes 的图片生成任务
  9191. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9192. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9193. if ($arr && is_array($arr)) {
  9194. $merged_roles = $arr['roles'];
  9195. $merged_scenes = $arr['scenes'];
  9196. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9197. }
  9198. // 确保数据是数组类型
  9199. if (!is_array($merged_roles)) {
  9200. dLog('deepseek')->error('merged_roles不是数组类型', [
  9201. 'type' => gettype($merged_roles),
  9202. 'value' => $merged_roles
  9203. ]);
  9204. $merged_roles = [];
  9205. }
  9206. if (!is_array($merged_scenes)) {
  9207. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9208. 'type' => gettype($merged_scenes),
  9209. 'value' => $merged_scenes
  9210. ]);
  9211. $merged_scenes = [];
  9212. }
  9213. if (!is_array($merged_props)) {
  9214. dLog('deepseek')->error('merged_props不是数组类型', [
  9215. 'type' => gettype($merged_props),
  9216. 'value' => $merged_props
  9217. ]);
  9218. $merged_props = [];
  9219. }
  9220. // 同步新出现的主体和场景到全局
  9221. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9222. $role_arr = [];
  9223. foreach ($merged_roles as $item) {
  9224. $role_arr[$item['role']] = $item;
  9225. }
  9226. $version_count = DB::table('mp_anime_episodes')
  9227. ->where('anime_id', $anime_id)
  9228. ->where('episode_number', $episode_number)
  9229. ->count('id');
  9230. $episode = [
  9231. 'anime_id' => $anime_id,
  9232. 'episode_number' => $episode_number,
  9233. 'title' => getProp($episode_arr, 'episode_title'),
  9234. 'content' => $content,
  9235. 'intro' => getProp($episode_arr, 'intro'),
  9236. 'art_style' => getProp($episode_arr, 'art_style'),
  9237. 'roles' => json_encode($merged_roles, 256),
  9238. 'scenes' => json_encode($merged_scenes, 256),
  9239. 'props' => json_encode($merged_props, 256),
  9240. 'generate_status' => '待执行',
  9241. 'generate_at' => $now,
  9242. 'is_default' => 1,
  9243. 'updated_at' => $now,
  9244. ];
  9245. $del_flag = false;
  9246. if ($is_regenerate_version) {
  9247. DB::table('mp_anime_episodes')
  9248. ->where('anime_id', $anime_id)
  9249. ->where('episode_number', $episode_number)
  9250. ->update(['is_default' => 0, 'updated_at' => $now]);
  9251. $episode['sequence'] = $version_count + 1;
  9252. $episode['created_at'] = $now;
  9253. $episode['cpid'] = Site::getCpid();
  9254. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9255. if (!$episode_id) {
  9256. Utils::throwError('20003:创建剧集版本失败');
  9257. }
  9258. } else {
  9259. $target_episode = $current_episode ?: $base_episode;
  9260. if ($target_episode) {
  9261. $episode_id = getProp($target_episode, 'id');
  9262. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9263. DB::table('mp_anime_episodes')
  9264. ->where('anime_id', $anime_id)
  9265. ->where('episode_number', $episode_number)
  9266. ->where('id', '<>', $episode_id)
  9267. ->update(['is_default' => 0, 'updated_at' => $now]);
  9268. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9269. if ($boolen === false) {
  9270. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9271. Utils::throwError('20003:分集内容保存失败');
  9272. }
  9273. $del_flag = true;
  9274. } else {
  9275. DB::table('mp_anime_episodes')
  9276. ->where('anime_id', $anime_id)
  9277. ->where('episode_number', $episode_number)
  9278. ->update(['is_default' => 0, 'updated_at' => $now]);
  9279. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9280. $episode['created_at'] = $now;
  9281. $episode['cpid'] = Site::getCpid();
  9282. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9283. if (!$episode_id) {
  9284. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9285. Utils::throwError('20003:分集内容保存失败');
  9286. }
  9287. }
  9288. }
  9289. $segments = [];
  9290. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9291. // 如果是第2集及以后,获取上一集的主体音色数据
  9292. $previous_roles_voice = [];
  9293. if ($episode_number >= 2) {
  9294. $previous_episode = DB::table('mp_anime_episodes')
  9295. ->where('anime_id', $anime_id)
  9296. ->where('episode_number', $episode_number - 1)
  9297. ->where('is_default', 1)
  9298. ->first();
  9299. if ($previous_episode) {
  9300. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9301. if (is_array($previous_roles)) {
  9302. foreach ($previous_roles as $prev_role) {
  9303. $role_name = getProp($prev_role, 'role');
  9304. if ($role_name) {
  9305. $previous_roles_voice[$role_name] = [
  9306. 'voice_name' => getProp($prev_role, 'voice_name'),
  9307. 'voice_type' => getProp($prev_role, 'voice_type'),
  9308. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9309. ];
  9310. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9311. if ($voice_prompt) {
  9312. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9313. }
  9314. }
  9315. }
  9316. }
  9317. }
  9318. }
  9319. // 将继承的音色数据同步到当前集的主体列表
  9320. if (!empty($previous_roles_voice)) {
  9321. foreach ($merged_roles as &$role) {
  9322. $role_name = getProp($role, 'role');
  9323. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9324. // 强制继承上一集的音色数据
  9325. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9326. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9327. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9328. // 如果上一集有 voice_prompt 则继承,否则跳过
  9329. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9330. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9331. }
  9332. }
  9333. }
  9334. unset($role); // 解除引用
  9335. // 更新 role_arr 以便后续使用
  9336. $role_arr = [];
  9337. foreach ($merged_roles as $item) {
  9338. $role_arr[$item['role']] = $item;
  9339. }
  9340. }
  9341. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9342. $emotion_list = array_flip($emotion_list);
  9343. foreach ($acts as $act) {
  9344. $act_segments = getProp($act, 'segments', []);
  9345. if (!is_array($act_segments)) {
  9346. continue;
  9347. }
  9348. if ((int)$ace_mode === 1) {
  9349. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9350. $merged_parts = [];
  9351. foreach ($act_segments as $seg) {
  9352. $seg_num = getProp($seg, 'segment_number');
  9353. $seg_content = getProp($seg, 'segment_content');
  9354. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9355. }
  9356. $act_content = implode("\n", $merged_parts);
  9357. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9358. $segments[] = [
  9359. 'anime_id' => $anime_id,
  9360. 'episode_id' => $episode_id,
  9361. 'episode_number' => $episode_number,
  9362. 'act_number' => getProp($act, 'act_number'),
  9363. 'act_title' => getProp($act, 'act_title'),
  9364. 'act_duration' => getProp($act, 'act_duration'),
  9365. 'act_content' => $act_content,
  9366. 'created_at' => $now,
  9367. 'updated_at' => $now
  9368. ];
  9369. } else {
  9370. foreach ($act_segments as $segment) {
  9371. $voice_actor = getProp($segment, 'voice_actor');
  9372. // 优先从上一集继承音色数据
  9373. $timbre_info = [];
  9374. if (isset($previous_roles_voice[$voice_actor])) {
  9375. // 从上一集继承音色数据
  9376. $timbre_info = $previous_roles_voice[$voice_actor];
  9377. } elseif (isset($role_arr[$voice_actor])) {
  9378. // 使用当前集的主体音色数据
  9379. $timbre_info = $role_arr[$voice_actor];
  9380. }
  9381. $voice_type = getProp($timbre_info, 'voice_type');
  9382. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9383. if ($timbre_emotion) {
  9384. $timbre_emotion = explode(',', $timbre_emotion);
  9385. } else {
  9386. $timbre_emotion = [];
  9387. }
  9388. $emotion = getProp($segment, 'emotion', '中性');
  9389. if (!in_array($emotion, $timbre_emotion)) {
  9390. $emotion = '中性';
  9391. }
  9392. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9393. $segments[] = [
  9394. 'anime_id' => $anime_id,
  9395. 'episode_id' => $episode_id,
  9396. 'episode_number' => $episode_number,
  9397. 'act_number' => getProp($act, 'act_number'),
  9398. 'act_title' => getProp($act, 'act_title'),
  9399. 'act_duration' => getProp($act, 'act_duration'),
  9400. 'segment_id' => getProp($segment, 'segment_id'),
  9401. 'segment_number' => getProp($segment, 'segment_number'),
  9402. 'segment_content' => getProp($segment, 'segment_content'),
  9403. 'description' => getProp($segment, 'description'),
  9404. 'composition' => getProp($segment, 'composition'),
  9405. 'camera_movement' => getProp($segment, 'camera_movement'),
  9406. 'voice_actor' => $voice_actor,
  9407. 'dialogue' => getProp($segment, 'dialogue'),
  9408. 'frame_type' => getProp($segment, 'frame_type'),
  9409. 'scene' => getProp($segment, 'scene'),
  9410. 'characters' => getProp($segment, 'characters'),
  9411. 'tail_frame' => getProp($segment, 'tail_frame'),
  9412. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9413. 'voice_type' => $voice_type,
  9414. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9415. 'emotion' => $emotion,
  9416. 'emotion_type' => $emotion_type,
  9417. 'gender' => getProp($segment, 'gender', '0'),
  9418. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9419. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9420. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9421. 'pitch' => getProp($segment, 'pitch', 0),
  9422. 'created_at' => $now,
  9423. 'updated_at' => $now
  9424. ];
  9425. }
  9426. }
  9427. }
  9428. if ($segments) {
  9429. if ($del_flag) {
  9430. DB::table('mp_episode_segments')
  9431. ->where('anime_id', $anime_id)
  9432. ->where('episode_id', $episode_id)
  9433. ->delete();
  9434. }
  9435. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9436. if (!$boolen) {
  9437. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9438. Utils::throwError('20003:分镜内容保存失败');
  9439. }
  9440. }
  9441. dLog('deepseek')->info('segments', $segments);
  9442. // ace_mode=1: acts 返回值按合并格式调整
  9443. if ((int)$ace_mode === 1) {
  9444. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9445. $act_map = [];
  9446. foreach ($table_act_data as $item) {
  9447. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9448. }
  9449. $restructured_acts = [];
  9450. foreach ($acts as $act) {
  9451. $act_segments = getProp($act, 'segments', []);
  9452. if (!is_array($act_segments)) {
  9453. continue;
  9454. }
  9455. $merged_parts = [];
  9456. foreach ($act_segments as $seg) {
  9457. $seg_num = getProp($seg, 'segment_number');
  9458. $seg_content = getProp($seg, 'segment_content');
  9459. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9460. }
  9461. $act_content = implode("\n", $merged_parts);
  9462. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9463. $restructured_acts[] = [
  9464. 'anime_id' => $anime_id,
  9465. 'episode_id' => $episode_id,
  9466. 'episode_number' => $episode_number,
  9467. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9468. 'act_number' => getProp($act, 'act_number'),
  9469. 'act_title' => getProp($act, 'act_title'),
  9470. 'act_duration' => getProp($act, 'act_duration'),
  9471. 'act_content' => $act_content,
  9472. 'created_at' => $now,
  9473. 'updated_at' => $now,
  9474. ];
  9475. }
  9476. $acts = $restructured_acts;
  9477. }
  9478. $episode['episode_id'] = $episode_id;
  9479. $episode['roles'] = $merged_roles;
  9480. $episode['scenes'] = $merged_scenes;
  9481. $episode['props'] = $merged_props;
  9482. $episode['acts'] = $acts;
  9483. return [
  9484. 'episode' => $episode,
  9485. 'episode_id' => $episode_id,
  9486. 'merged_roles' => $merged_roles,
  9487. 'merged_scenes' => $merged_scenes,
  9488. 'merged_props' => $merged_props,
  9489. ];
  9490. }
  9491. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9492. {
  9493. $content = '';
  9494. foreach ($items as $item) {
  9495. $name = trim((string)getProp($item, $nameKey));
  9496. if ($name === '' || $name === '旁白') {
  9497. continue;
  9498. }
  9499. $description = trim((string)getProp($item, 'description'));
  9500. $content .= $name . ': ' . $description;
  9501. if ($nameKey == 'role') {
  9502. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9503. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9504. $voice_name = trim(getProp($item, 'voice_name'));
  9505. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9506. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9507. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9508. }else {
  9509. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9510. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9511. }
  9512. $content .= "\n";
  9513. }
  9514. return trim($content);
  9515. }
  9516. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9517. if ((int)$sequence <= 0) {
  9518. return [];
  9519. }
  9520. $origin_content = '';
  9521. if ($content) {
  9522. $origin_content = '本集剧情内容:'.$content;
  9523. }else {
  9524. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9525. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9526. }
  9527. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9528. // 获取分集信息
  9529. $episode = DB::table('mp_anime_episodes')
  9530. ->where('anime_id', $animeId)
  9531. ->where('episode_number', $sequence)
  9532. ->where('is_default', 1)
  9533. ->first();
  9534. if (!$episode) {
  9535. return [];
  9536. }
  9537. $episode_id = getProp($episode, 'id');
  9538. $episode_number = getProp($episode, 'episode_number');
  9539. $title = getProp($episode, 'title');
  9540. $intro = getProp($episode, 'intro');
  9541. $art_style = getProp($episode, 'art_style');
  9542. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9543. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9544. // 组装纯文本内容
  9545. $content = '';
  9546. // 添加分集标题和梗概
  9547. $content .= "###第{$episode_number}集:{$title}\n\n";
  9548. $content .= "###故事梗概\n";
  9549. $content .= trim($intro) . "\n\n";
  9550. // 添加美术风格
  9551. $content .= "###美术风格\n";
  9552. $content .= trim($art_style) . "\n\n";
  9553. // 添加主体列表
  9554. $content .= "###主体列表\n";
  9555. $pangbai_voice_prompt = "";
  9556. foreach ($roles as $role) {
  9557. $name = getProp($role, 'role');
  9558. $description = getProp($role, 'description');
  9559. $pic_prompt = getProp($role, 'pic_prompt');
  9560. $voice_prompt = getProp($role, 'voice_prompt');
  9561. $voice_name = getProp($role, 'voice_name');
  9562. $content .= "{$name}: {$description}";
  9563. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9564. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9565. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9566. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9567. $content .= "\n";
  9568. }
  9569. $content .= "\n";
  9570. // 添加场景列表
  9571. $content .= "###场景列表\n";
  9572. foreach ($scenes as $scene) {
  9573. $name = getProp($scene, 'scene');
  9574. $description = getProp($scene, 'description');
  9575. $pic_prompt = getProp($scene, 'pic_prompt');
  9576. $content .= "{$name}: {$description}";
  9577. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9578. $content .= "\n";
  9579. }
  9580. $content .= "\n";
  9581. // 获取分镜信息
  9582. $segments = DB::table('mp_episode_segments')
  9583. ->where('anime_id', $animeId)
  9584. ->where('episode_id', $episode_id)
  9585. ->orderBy('segment_number')
  9586. ->get();
  9587. if ($segments && count($segments) > 0) {
  9588. if ((int)$ace_mode === 1) {
  9589. $content .= "###分段剧本\n";
  9590. // 获取片段数量
  9591. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9592. $content .= "片段数量:{$act_count}\n";
  9593. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9594. $content .= "\n";
  9595. }else {
  9596. $content .= "###分镜剧本\n";
  9597. }
  9598. // 按幕分组
  9599. $currentAct = null;
  9600. foreach ($segments as $segment) {
  9601. $act_number = getProp($segment, 'act_number');
  9602. $act_title = getProp($segment, 'act_title');
  9603. $act_duration = getProp($segment, 'act_duration');
  9604. $segment_number = getProp($segment, 'segment_number');
  9605. $segment_content = getProp($segment, 'segment_content');
  9606. $scene_description = getProp($segment, 'scene_description');
  9607. $scene_name = getProp($segment, 'scene_name');
  9608. $composition = getProp($segment, 'composition');
  9609. $camera_movement = getProp($segment, 'camera_movement');
  9610. $voice_type = getProp($segment, 'voice_type');
  9611. $characters = getProp($segment, 'characters');
  9612. $dialogue = getProp($segment, 'dialogue');
  9613. $frame_type = getProp($segment, 'frame_type');
  9614. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9615. // 判断是否是全能模式
  9616. if ((int)$ace_mode === 1) { // 全能模式
  9617. // 如果是新的分段,添加分段标题
  9618. if ($act_number !== $currentAct) {
  9619. $currentAct = $act_number;
  9620. $content .= "##{$act_title}\n";
  9621. $content .= "时长:{$act_duration}s\n";
  9622. }
  9623. }else {
  9624. // 如果是新的幕,添加幕标题
  9625. if ($act_number !== $currentAct) {
  9626. $currentAct = $act_number;
  9627. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9628. }
  9629. }
  9630. // 添加分镜信息
  9631. $content .= "分镜{$segment_number}\n";
  9632. $content .= "分镜内容:\n{$segment_content}\n";
  9633. // $content .= "画面描述:{$scene_description}\n";
  9634. // $content .= "场景:{$scene_name}\n";
  9635. // $content .= "构图设计:{$composition}\n";
  9636. // $content .= "运镜调度:{$camera_movement}\n";
  9637. // if (!empty($voice_type)) {
  9638. // $content .= "配音角色:{$voice_type}\n";
  9639. // }
  9640. // if (!empty($characters)) {
  9641. // $content .= "出镜角色:{$characters}\n";
  9642. // }
  9643. // if (!empty($dialogue)) {
  9644. // $content .= "台词内容:\"{$dialogue}\"\n";
  9645. // }
  9646. // $content .= "画面类型:{$frame_type}\n";
  9647. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9648. $content .= "\n";
  9649. }
  9650. }
  9651. $content = trim($content);
  9652. if($content) $content = "上集剧本内容:\n{$content}";
  9653. return [
  9654. [
  9655. 'role' => 'user',
  9656. 'content' => $origin_content
  9657. ],
  9658. [
  9659. 'role' => 'assistant',
  9660. 'content' => $content
  9661. ]
  9662. ];
  9663. }
  9664. private function getEpisodeChatMessages($animeId, $sequence): array
  9665. {
  9666. if ((int)$sequence <= 0) {
  9667. return [];
  9668. }
  9669. return DB::table('mp_anime_records')
  9670. ->where('anime_id', $animeId)
  9671. ->where('sequence', $sequence)
  9672. ->where('episode_id', '>', 0)
  9673. ->select('role', 'content')
  9674. ->orderBy('created_at')
  9675. ->orderBy('id')
  9676. ->get()
  9677. ->map(function ($value) {
  9678. return (array)$value;
  9679. })
  9680. ->toArray();
  9681. }
  9682. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9683. {
  9684. $existingMap = [];
  9685. foreach ($existingItems as $item) {
  9686. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9687. if ($itemKey === '') {
  9688. continue;
  9689. }
  9690. $existingMap[$itemKey] = $item;
  9691. }
  9692. if (!$generatedItems) {
  9693. return array_values($existingItems);
  9694. }
  9695. $merged = [];
  9696. foreach ($generatedItems as $item) {
  9697. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9698. if ($itemKey === '') {
  9699. continue;
  9700. }
  9701. if (isset($existingMap[$itemKey])) {
  9702. if (trim((string)getProp($item, 'description')) === '') {
  9703. $merged[] = $existingMap[$itemKey];
  9704. continue;
  9705. }
  9706. // 检查内容是否发生变化
  9707. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9708. if (!$isChanged) {
  9709. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9710. $mergedItem = [
  9711. $nameKey => trim((string)getProp($item, $nameKey)),
  9712. 'description' => trim((string)getProp($item, 'description')),
  9713. ];
  9714. // 如果有 pic_prompt,添加到合并项中
  9715. $picPrompt = getProp($item, 'pic_prompt');
  9716. if (!empty($picPrompt)) {
  9717. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9718. }
  9719. // 继承现有项的 URL
  9720. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9721. if (!empty($existingUrl)) {
  9722. $mergedItem['url'] = $existingUrl;
  9723. }
  9724. // 继承现有项的 task_id
  9725. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9726. if (!empty($existingTaskId)) {
  9727. $mergedItem['task_id'] = $existingTaskId;
  9728. }
  9729. // 继承现有项的 task_status
  9730. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9731. if (!empty($existingTaskStatus)) {
  9732. $mergedItem['task_status'] = $existingTaskStatus;
  9733. }
  9734. // 保留生成项的音色字段
  9735. $voiceName = getProp($item, 'voice_name');
  9736. if (!empty($voiceName)) {
  9737. $mergedItem['voice_name'] = $voiceName;
  9738. }
  9739. $voiceType = getProp($item, 'voice_type');
  9740. if (!empty($voiceType)) {
  9741. $mergedItem['voice_type'] = $voiceType;
  9742. }
  9743. $audioUrl = getProp($item, 'voice_audio_url');
  9744. if (!empty($audioUrl)) {
  9745. $mergedItem['voice_audio_url'] = $audioUrl;
  9746. }
  9747. $merged[] = $mergedItem;
  9748. } else {
  9749. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9750. $mergedItem = [
  9751. $nameKey => trim((string)getProp($item, $nameKey)),
  9752. 'description' => trim((string)getProp($item, 'description')),
  9753. ];
  9754. // 如果有 pic_prompt,添加到合并项中
  9755. $picPrompt = getProp($item, 'pic_prompt');
  9756. if (!empty($picPrompt)) {
  9757. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9758. }
  9759. // 保留生成项的音色字段
  9760. $voiceName = getProp($item, 'voice_name');
  9761. if (!empty($voiceName)) {
  9762. $mergedItem['voice_name'] = $voiceName;
  9763. }
  9764. $voiceType = getProp($item, 'voice_type');
  9765. if (!empty($voiceType)) {
  9766. $mergedItem['voice_type'] = $voiceType;
  9767. }
  9768. $audioUrl = getProp($item, 'voice_audio_url');
  9769. if (!empty($audioUrl)) {
  9770. $mergedItem['voice_audio_url'] = $audioUrl;
  9771. }
  9772. // 不继承 URL、task_id 和 task_status(重置状态)
  9773. $merged[] = $mergedItem;
  9774. }
  9775. } else {
  9776. // 新增项,保留生成项的所有字段
  9777. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9778. }
  9779. }
  9780. return $merged ?: array_values($existingItems);
  9781. }
  9782. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9783. {
  9784. $resetItem = [
  9785. $nameKey => trim((string)getProp($item, $nameKey)),
  9786. 'description' => trim((string)getProp($item, 'description')),
  9787. ];
  9788. // 保留指定的字段
  9789. foreach ($preserveFields as $field) {
  9790. $value = getProp($item, $field);
  9791. if (!empty($value)) {
  9792. $resetItem[$field] = $value;
  9793. }
  9794. }
  9795. return $resetItem;
  9796. }
  9797. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9798. {
  9799. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9800. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9801. if ($existingKey !== $generatedKey) {
  9802. return true;
  9803. }
  9804. // 比较 description 是否变化
  9805. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9806. return true;
  9807. }
  9808. // 比较 pic_prompt 是否变化
  9809. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9810. }
  9811. private function normalizeEpisodeResourceKey($value): string
  9812. {
  9813. $value = trim((string)$value);
  9814. if ($value === '') {
  9815. return '';
  9816. }
  9817. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9818. }
  9819. // 生成全局角色图片
  9820. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9821. $anime_id = getProp($data, 'anime_id');
  9822. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9823. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9824. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9825. $art_style = getProp($anime, 'art_style');
  9826. $update_flag = false;
  9827. foreach ($roles as &$role) {
  9828. $role_name = getProp($role, 'role');
  9829. if ($role_name == '旁白') continue;
  9830. // 优先使用 pic_prompt,如果没有则使用 description
  9831. $pic_prompt = getProp($role, 'pic_prompt');
  9832. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9833. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9834. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9835. // 参考图地址
  9836. $ref_img_url = getProp($role, 'url');
  9837. if (!$is_force && $ref_img_url) continue;
  9838. $update_flag = true;
  9839. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9840. try {
  9841. $params = [
  9842. 'prompt' => $description,
  9843. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9844. 'ref_img_urls' => []
  9845. ];
  9846. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9847. $task_id = $task->id;
  9848. if (!$task_id) {
  9849. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9850. }
  9851. $role['task_id'] = $task_id;
  9852. $role['task_status'] = 'processing';
  9853. } catch (\Exception $e) {
  9854. Utils::throwError("20003:" . $e->getMessage());
  9855. }
  9856. }
  9857. if (!$update_flag) return true;
  9858. // 保存角色信息
  9859. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9860. 'roles' => json_encode($roles, 256),
  9861. 'generate_status' => '执行中',
  9862. 'generate_at' => date('Y-m-d H:i:s'),
  9863. 'updated_at' => date('Y-m-d H:i:s')
  9864. ]);
  9865. if (!$boolen) {
  9866. Utils::throwError('20003:保存角色信息失败');
  9867. }
  9868. return $boolen;
  9869. }
  9870. // 生成全局场景图片
  9871. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9872. $anime_id = getProp($data, 'anime_id');
  9873. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9874. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9875. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9876. $art_style = getProp($anime, 'art_style');
  9877. $update_flag = false;
  9878. foreach ($scenes as &$scene) {
  9879. $scene_name = getProp($scene, 'scene');
  9880. // 优先使用 pic_prompt,如果没有则使用 description
  9881. $pic_prompt = getProp($scene, 'pic_prompt');
  9882. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9883. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9884. // 参考图地址
  9885. $ref_img_url = getProp($scene, 'url');
  9886. if (!$is_force && $ref_img_url) continue;
  9887. $update_flag = true;
  9888. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9889. try {
  9890. $params = [
  9891. 'prompt' => $description,
  9892. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9893. 'ref_img_urls' => []
  9894. ];
  9895. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9896. $task_id = $task->id;
  9897. if (!$task_id) {
  9898. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9899. }
  9900. $scene['task_id'] = $task_id;
  9901. $scene['task_status'] = 'processing';
  9902. } catch (\Exception $e) {
  9903. Utils::throwError("20003:" . $e->getMessage());
  9904. }
  9905. }
  9906. if (!$update_flag) return true;
  9907. // 保存角色信息
  9908. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9909. 'scenes' => json_encode($scenes, 256),
  9910. 'generate_status' => '执行中',
  9911. 'generate_at' => date('Y-m-d H:i:s'),
  9912. 'updated_at' => date('Y-m-d H:i:s')
  9913. ]);
  9914. if (!$boolen) {
  9915. Utils::throwError('20003:保存角色信息失败');
  9916. }
  9917. return $boolen;
  9918. }
  9919. // 生成分镜主体、场景和道具图片
  9920. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9921. $character_prefix = '';
  9922. $scene_prefix = '';
  9923. $prop_prefix = '';
  9924. if ($art_style_type) {
  9925. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9926. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9927. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9928. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9929. }
  9930. $update_flag = false;
  9931. // 获取上一集的roles、scenes和props数据
  9932. $prev_roles = [];
  9933. $prev_scenes = [];
  9934. $prev_props = [];
  9935. if ($episode_number > 1) {
  9936. $prev_episode = DB::table('mp_anime_episodes')
  9937. ->where('anime_id', $anime_id)
  9938. ->where('episode_number', $episode_number - 1)
  9939. ->where('is_default', 1)
  9940. ->first();
  9941. if ($prev_episode) {
  9942. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9943. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9944. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9945. dLog('deepseek')->info("获取上一集数据成功", [
  9946. 'anime_id' => $anime_id,
  9947. 'prev_episode_number' => $episode_number - 1,
  9948. 'prev_roles_count' => count($prev_roles),
  9949. 'prev_scenes_count' => count($prev_scenes),
  9950. 'prev_props_count' => count($prev_props)
  9951. ]);
  9952. }
  9953. }
  9954. // 处理角色图片生成
  9955. foreach ($roles as &$role) {
  9956. $role_name = getProp($role, 'role');
  9957. if ($role_name == '旁白') continue;
  9958. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9959. if (isset($ref_products[$role_name])) {
  9960. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9961. if ($role['url']) continue;
  9962. }
  9963. $role_description = getProp($role, 'description');
  9964. $role_pic_prompt = getProp($role, 'pic_prompt');
  9965. $role_url = getProp($role, 'url');
  9966. // 检查是否可以从上一集继承
  9967. $inherited = false;
  9968. if (!$is_force && !empty($prev_roles)) {
  9969. foreach ($prev_roles as $prev_role) {
  9970. $prev_role_name = getProp($prev_role, 'role');
  9971. $prev_description = getProp($prev_role, 'description');
  9972. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9973. $prev_url = getProp($prev_role, 'url');
  9974. $prev_task_id = getProp($prev_role, 'task_id');
  9975. $prev_task_status = getProp($prev_role, 'task_status');
  9976. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9977. if ($role_name == $prev_role_name
  9978. && $role_description == $prev_description
  9979. && $role_pic_prompt == $prev_pic_prompt
  9980. && !empty($prev_url)) {
  9981. $role['task_id'] = $prev_task_id;
  9982. $role['task_status'] = $prev_task_status;
  9983. $role['url'] = $prev_url;
  9984. $inherited = true;
  9985. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9986. 'anime_id' => $anime_id,
  9987. 'episode_number' => $episode_number,
  9988. 'task_id' => $prev_task_id,
  9989. 'url' => $prev_url
  9990. ]);
  9991. break;
  9992. }
  9993. }
  9994. }
  9995. // 如果已继承或已有url,跳过生成
  9996. if ($inherited || (!$is_force && $role_url)) {
  9997. continue;
  9998. }
  9999. // 优先使用 pic_prompt,如果没有则使用 description
  10000. $pic_prompt = getProp($role, 'pic_prompt');
  10001. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10002. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10003. $update_flag = true;
  10004. // 调用AIImageGenerationService的生成图片任务接口
  10005. try {
  10006. $params = [
  10007. 'prompt' => $description,
  10008. 'ref_img_urls' => []
  10009. ];
  10010. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10011. $task_id = $task->id;
  10012. if (!$task_id) {
  10013. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10014. continue; // 不中断,继续处理其他角色
  10015. }
  10016. $role['task_id'] = $task_id;
  10017. $role['task_status'] = 'processing';
  10018. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10019. 'anime_id' => $anime_id,
  10020. 'episode_number' => $episode_number,
  10021. 'task_id' => $task_id
  10022. ]);
  10023. } catch (\Exception $e) {
  10024. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10025. // 不抛出异常,继续处理其他角色
  10026. }
  10027. }
  10028. // 处理场景图片生成
  10029. foreach ($scenes as &$scene) {
  10030. $scene_name = getProp($scene, 'scene');
  10031. $scene_description = getProp($scene, 'description');
  10032. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10033. $scene_url = getProp($scene, 'url');
  10034. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10035. if (isset($ref_products[$scene_name])) {
  10036. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10037. if ($scene['url']) continue;
  10038. }
  10039. // 检查是否可以从上一集继承
  10040. $inherited = false;
  10041. if (!$is_force && !empty($prev_scenes)) {
  10042. foreach ($prev_scenes as $prev_scene) {
  10043. $prev_scene_name = getProp($prev_scene, 'scene');
  10044. $prev_description = getProp($prev_scene, 'description');
  10045. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10046. $prev_url = getProp($prev_scene, 'url');
  10047. $prev_task_id = getProp($prev_scene, 'task_id');
  10048. $prev_task_status = getProp($prev_scene, 'task_status');
  10049. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10050. if ($scene_name == $prev_scene_name
  10051. && $scene_description == $prev_description
  10052. && $scene_pic_prompt == $prev_pic_prompt
  10053. && !empty($prev_url)) {
  10054. $scene['task_id'] = $prev_task_id;
  10055. $scene['task_status'] = $prev_task_status;
  10056. $scene['url'] = $prev_url;
  10057. $inherited = true;
  10058. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10059. 'anime_id' => $anime_id,
  10060. 'episode_number' => $episode_number,
  10061. 'task_id' => $prev_task_id,
  10062. 'url' => $prev_url
  10063. ]);
  10064. break;
  10065. }
  10066. }
  10067. }
  10068. // 如果已继承或已有url,跳过生成
  10069. if ($inherited || (!$is_force && $scene_url)) {
  10070. continue;
  10071. }
  10072. // 优先使用 pic_prompt,如果没有则使用 description
  10073. $pic_prompt = getProp($scene, 'pic_prompt');
  10074. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10075. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10076. $update_flag = true;
  10077. // 调用AIImageGenerationService的生成图片任务接口
  10078. try {
  10079. $params = [
  10080. 'prompt' => $description,
  10081. 'ref_img_urls' => []
  10082. ];
  10083. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10084. $task_id = $task->id;
  10085. if (!$task_id) {
  10086. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10087. continue; // 不中断,继续处理其他场景
  10088. }
  10089. $scene['task_id'] = $task_id;
  10090. $scene['task_status'] = 'processing';
  10091. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10092. 'anime_id' => $anime_id,
  10093. 'episode_number' => $episode_number,
  10094. 'task_id' => $task_id
  10095. ]);
  10096. } catch (\Exception $e) {
  10097. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10098. // 不抛出异常,继续处理其他场景
  10099. }
  10100. }
  10101. // 处理道具图片生成(逻辑与场景一致)
  10102. foreach ($props as &$prop) {
  10103. $prop_name = getProp($prop, 'prop');
  10104. $prop_description = getProp($prop, 'description');
  10105. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10106. $prop_url = getProp($prop, 'url');
  10107. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10108. if (isset($ref_products[$prop_name])) {
  10109. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10110. if ($prop['url']) continue;
  10111. }
  10112. // 检查是否可以从上一集继承
  10113. $inherited = false;
  10114. if (!$is_force && !empty($prev_props)) {
  10115. foreach ($prev_props as $prev_prop) {
  10116. $prev_prop_name = getProp($prev_prop, 'prop');
  10117. $prev_description = getProp($prev_prop, 'description');
  10118. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10119. $prev_url = getProp($prev_prop, 'url');
  10120. $prev_task_id = getProp($prev_prop, 'task_id');
  10121. $prev_task_status = getProp($prev_prop, 'task_status');
  10122. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10123. if ($prop_name == $prev_prop_name
  10124. && $prop_description == $prev_description
  10125. && $prop_pic_prompt == $prev_pic_prompt
  10126. && !empty($prev_url)) {
  10127. $prop['task_id'] = $prev_task_id;
  10128. $prop['task_status'] = $prev_task_status;
  10129. $prop['url'] = $prev_url;
  10130. $inherited = true;
  10131. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10132. 'anime_id' => $anime_id,
  10133. 'episode_number' => $episode_number,
  10134. 'task_id' => $prev_task_id,
  10135. 'url' => $prev_url
  10136. ]);
  10137. break;
  10138. }
  10139. }
  10140. }
  10141. // 如果已继承或已有url,跳过生成
  10142. if ($inherited || (!$is_force && $prop_url)) {
  10143. continue;
  10144. }
  10145. // 优先使用 pic_prompt,如果没有则使用 description
  10146. $pic_prompt = getProp($prop, 'pic_prompt');
  10147. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10148. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10149. $update_flag = true;
  10150. // 调用AIImageGenerationService的生成图片任务接口
  10151. try {
  10152. $params = [
  10153. 'prompt' => $description,
  10154. 'ref_img_urls' => []
  10155. ];
  10156. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10157. $task_id = $task->id;
  10158. if (!$task_id) {
  10159. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10160. continue; // 不中断,继续处理其他道具
  10161. }
  10162. $prop['task_id'] = $task_id;
  10163. $prop['task_status'] = 'processing';
  10164. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10165. 'anime_id' => $anime_id,
  10166. 'episode_number' => $episode_number,
  10167. 'task_id' => $task_id
  10168. ]);
  10169. } catch (\Exception $e) {
  10170. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10171. // 不抛出异常,继续处理其他道具
  10172. }
  10173. }
  10174. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10175. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10176. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10177. // // 保存剧集的角色和场景信息
  10178. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10179. // 'roles' => json_encode($roles, 256),
  10180. // 'scenes' => json_encode($scenes, 256),
  10181. // 'generate_status' => '执行中',
  10182. // 'generate_at' => date('Y-m-d H:i:s'),
  10183. // 'updated_at' => date('Y-m-d H:i:s')
  10184. // ]);
  10185. // if (!$boolen) {
  10186. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10187. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10188. // }
  10189. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10190. // 'episode_id' => $episode_id,
  10191. 'roles_count' => count($roles),
  10192. 'scenes_count' => count($scenes),
  10193. 'props_count' => count($props)
  10194. ]);
  10195. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10196. }
  10197. /**
  10198. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10199. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10200. *
  10201. * @param int $anime_id 动漫对话ID
  10202. * @param array $episode_roles 剧集角色数据
  10203. * @param array $episode_scenes 剧集场景数据
  10204. * @param array $episode_props 剧集道具数据
  10205. * @return bool
  10206. */
  10207. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10208. // 获取全局数据
  10209. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10210. if (!$anime) {
  10211. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10212. return false;
  10213. }
  10214. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10215. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10216. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10217. $roles_added = false;
  10218. $roles_updated = false;
  10219. $scenes_added = false;
  10220. $props_added = false;
  10221. // 处理角色同步
  10222. foreach ($episode_roles as $episode_role) {
  10223. $episode_role_name = getProp($episode_role, 'role');
  10224. $episode_description = getProp($episode_role, 'description');
  10225. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10226. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10227. // 跳过旁白
  10228. if ($episode_role_name == '旁白') {
  10229. continue;
  10230. }
  10231. // 检查全局中是否已存在相同的角色
  10232. $exists = false;
  10233. $global_role_index = -1;
  10234. foreach ($global_roles as $index => $global_role) {
  10235. $global_role_name = getProp($global_role, 'role');
  10236. $global_description = getProp($global_role, 'description');
  10237. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10238. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10239. if ($episode_role_name == $global_role_name
  10240. && $episode_description == $global_description
  10241. && $episode_pic_prompt == $global_pic_prompt) {
  10242. $exists = true;
  10243. $global_role_index = $index;
  10244. break;
  10245. }
  10246. }
  10247. // 如果不存在,则添加到全局
  10248. if (!$exists) {
  10249. $global_roles[] = $episode_role;
  10250. $roles_added = true;
  10251. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10252. 'anime_id' => $anime_id,
  10253. 'role' => $episode_role_name
  10254. ]);
  10255. } else {
  10256. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10257. if (!empty($episode_voice_prompt)) {
  10258. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10259. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10260. if ($global_voice_prompt !== $episode_voice_prompt) {
  10261. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10262. $roles_updated = true;
  10263. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10264. 'anime_id' => $anime_id,
  10265. 'role' => $episode_role_name,
  10266. 'voice_prompt' => $episode_voice_prompt
  10267. ]);
  10268. }
  10269. }
  10270. }
  10271. }
  10272. // 处理场景同步
  10273. foreach ($episode_scenes as $episode_scene) {
  10274. $episode_scene_name = getProp($episode_scene, 'scene');
  10275. $episode_description = getProp($episode_scene, 'description');
  10276. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10277. // 检查全局中是否已存在相同的场景
  10278. $exists = false;
  10279. foreach ($global_scenes as $global_scene) {
  10280. $global_scene_name = getProp($global_scene, 'scene');
  10281. $global_description = getProp($global_scene, 'description');
  10282. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10283. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10284. if ($episode_scene_name == $global_scene_name
  10285. && $episode_description == $global_description
  10286. && $episode_pic_prompt == $global_pic_prompt) {
  10287. $exists = true;
  10288. break;
  10289. }
  10290. }
  10291. // 如果不存在,则添加到全局
  10292. if (!$exists) {
  10293. $global_scenes[] = $episode_scene;
  10294. $scenes_added = true;
  10295. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10296. 'anime_id' => $anime_id,
  10297. 'scene' => $episode_scene_name
  10298. ]);
  10299. }
  10300. }
  10301. // 处理道具同步(逻辑与场景一致)
  10302. foreach ($episode_props as $episode_prop) {
  10303. $episode_prop_name = getProp($episode_prop, 'prop');
  10304. $episode_description = getProp($episode_prop, 'description');
  10305. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10306. // 检查全局中是否已存在相同的道具
  10307. $exists = false;
  10308. foreach ($global_props as $global_prop) {
  10309. $global_prop_name = getProp($global_prop, 'prop');
  10310. $global_description = getProp($global_prop, 'description');
  10311. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10312. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10313. if ($episode_prop_name == $global_prop_name
  10314. && $episode_description == $global_description
  10315. && $episode_pic_prompt == $global_pic_prompt) {
  10316. $exists = true;
  10317. break;
  10318. }
  10319. }
  10320. // 如果不存在,则添加到全局
  10321. if (!$exists) {
  10322. $global_props[] = $episode_prop;
  10323. $props_added = true;
  10324. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10325. 'anime_id' => $anime_id,
  10326. 'prop' => $episode_prop_name
  10327. ]);
  10328. }
  10329. }
  10330. // 如果有新增或更新,则更新全局数据
  10331. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10332. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10333. if ($roles_added || $roles_updated) {
  10334. $update_data['roles'] = json_encode($global_roles, 256);
  10335. }
  10336. if ($scenes_added) {
  10337. $update_data['scenes'] = json_encode($global_scenes, 256);
  10338. }
  10339. if ($props_added) {
  10340. $update_data['props'] = json_encode($global_props, 256);
  10341. }
  10342. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10343. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10344. 'anime_id' => $anime_id,
  10345. 'roles_added' => $roles_added,
  10346. 'roles_updated' => $roles_updated,
  10347. 'scenes_added' => $scenes_added,
  10348. 'props_added' => $props_added,
  10349. 'global_roles_count' => count($global_roles),
  10350. 'global_scenes_count' => count($global_scenes),
  10351. 'global_props_count' => count($global_props)
  10352. ]);
  10353. }
  10354. return true;
  10355. }
  10356. /**
  10357. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10358. *
  10359. * @param int $anime_id 动漫对话ID
  10360. * @param int $episode_id 分集ID
  10361. * @return bool
  10362. */
  10363. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10364. // 获取全局角色和场景数据
  10365. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10366. if (!$anime) {
  10367. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10368. return false;
  10369. }
  10370. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10371. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10372. // 获取指定的分集
  10373. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10374. if (!$episode) {
  10375. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10376. return false;
  10377. }
  10378. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10379. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10380. $roles_updated = false;
  10381. $scenes_updated = false;
  10382. // 继承角色的task_id、task_status和url
  10383. foreach ($episode_roles as &$episode_role) {
  10384. $episode_role_name = getProp($episode_role, 'role');
  10385. $episode_description = getProp($episode_role, 'description');
  10386. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10387. $episode_url = getProp($episode_role, 'url');
  10388. // 跳过旁白角色
  10389. if ($episode_role_name == '旁白') {
  10390. continue;
  10391. }
  10392. // 如果剧集中已有URL,跳过
  10393. if (!empty($episode_url)) {
  10394. continue;
  10395. }
  10396. // 遍历全局角色数据,查找匹配的角色
  10397. foreach ($global_roles as $global_role) {
  10398. $global_role_name = getProp($global_role, 'role');
  10399. $global_description = getProp($global_role, 'description');
  10400. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10401. $global_url = getProp($global_role, 'url');
  10402. $global_task_id = getProp($global_role, 'task_id');
  10403. $global_task_status = getProp($global_role, 'task_status');
  10404. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10405. if ($episode_role_name == $global_role_name
  10406. && $episode_description == $global_description
  10407. && $episode_pic_prompt == $global_pic_prompt) {
  10408. // 继承 task_id、task_status 和 url
  10409. if (!empty($global_task_id)) {
  10410. $episode_role['task_id'] = $global_task_id;
  10411. $episode_role['task_status'] = $global_task_status;
  10412. $roles_updated = true;
  10413. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10414. 'episode_id' => $episode_id,
  10415. 'role' => $episode_role_name,
  10416. 'task_id' => $global_task_id,
  10417. 'task_status' => $global_task_status
  10418. ]);
  10419. }
  10420. if (!empty($global_url)) {
  10421. $episode_role['url'] = $global_url;
  10422. $roles_updated = true;
  10423. dLog('deepseek')->info('剧集角色继承全局url', [
  10424. 'episode_id' => $episode_id,
  10425. 'role' => $episode_role_name,
  10426. 'url' => $global_url
  10427. ]);
  10428. }
  10429. break;
  10430. }
  10431. }
  10432. }
  10433. // 继承场景的task_id、task_status和url
  10434. foreach ($episode_scenes as &$episode_scene) {
  10435. $episode_scene_name = getProp($episode_scene, 'scene');
  10436. $episode_description = getProp($episode_scene, 'description');
  10437. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10438. $episode_url = getProp($episode_scene, 'url');
  10439. // 如果剧集中已有URL,跳过
  10440. if (!empty($episode_url)) {
  10441. continue;
  10442. }
  10443. // 遍历全局场景数据,查找匹配的场景
  10444. foreach ($global_scenes as $global_scene) {
  10445. $global_scene_name = getProp($global_scene, 'scene');
  10446. $global_description = getProp($global_scene, 'description');
  10447. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10448. $global_url = getProp($global_scene, 'url');
  10449. $global_task_id = getProp($global_scene, 'task_id');
  10450. $global_task_status = getProp($global_scene, 'task_status');
  10451. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10452. if ($episode_scene_name == $global_scene_name
  10453. && $episode_description == $global_description
  10454. && $episode_pic_prompt == $global_pic_prompt) {
  10455. // 继承 task_id、task_status 和 url
  10456. if (!empty($global_task_id)) {
  10457. $episode_scene['task_id'] = $global_task_id;
  10458. $episode_scene['task_status'] = $global_task_status;
  10459. $scenes_updated = true;
  10460. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10461. 'episode_id' => $episode_id,
  10462. 'scene' => $episode_scene_name,
  10463. 'task_id' => $global_task_id,
  10464. 'task_status' => $global_task_status
  10465. ]);
  10466. }
  10467. if (!empty($global_url)) {
  10468. $episode_scene['url'] = $global_url;
  10469. $scenes_updated = true;
  10470. dLog('deepseek')->info('剧集场景继承全局url', [
  10471. 'episode_id' => $episode_id,
  10472. 'scene' => $episode_scene_name,
  10473. 'url' => $global_url
  10474. ]);
  10475. }
  10476. break;
  10477. }
  10478. }
  10479. }
  10480. // 如果有更新,则保存到数据库
  10481. if ($roles_updated || $scenes_updated) {
  10482. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10483. if ($roles_updated) {
  10484. $update_data['roles'] = json_encode($episode_roles, 256);
  10485. }
  10486. if ($scenes_updated) {
  10487. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10488. }
  10489. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10490. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10491. 'episode_id' => $episode_id,
  10492. 'roles_updated' => $roles_updated,
  10493. 'scenes_updated' => $scenes_updated
  10494. ]);
  10495. }
  10496. return true;
  10497. }
  10498. public function chatChangeImg($data) {
  10499. $segment = getProp($data, 'segment');
  10500. $segment_content = getProp($segment, 'segment_content');
  10501. $prompt = getProp($data, 'prompt');
  10502. $ref_img = getProp($data, 'ref_img');
  10503. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10504. // 处理文本模型
  10505. $model = getProp($data, 'model');
  10506. if (!$model) {
  10507. // 用户没有输入,从anime表获取
  10508. $segment_id = getProp($segment, 'segment_id');
  10509. if ($segment_id) {
  10510. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10511. if ($episode_id) {
  10512. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10513. if ($anime_id) {
  10514. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10515. }
  10516. }
  10517. }
  10518. if (!$model) {
  10519. // anime表也没有,使用默认值
  10520. $model = 'doubao-seed-2-0-mini-260215';
  10521. }
  10522. }
  10523. // 验证模型是否在可用模型表中
  10524. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10525. $model = 'doubao-seed-2-0-mini-260215';
  10526. }
  10527. $messages[] =
  10528. [
  10529. 'role' => 'user',
  10530. 'content' => $question
  10531. ];
  10532. $post_data = [
  10533. 'model' => $model,
  10534. 'messages' => $messages,
  10535. // 'max_tokens' => 8192,
  10536. 'temperature' => 0.7,
  10537. 'frequency_penalty' => 0,
  10538. 'presence_penalty' => 0,
  10539. 'response_format' => ['type' => 'text'],
  10540. 'stream' => false // 是否启用流式输出
  10541. ];
  10542. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10543. // DeepSeek 官方模型使用 DeepSeek API
  10544. $chatResult = $this->chatOnly($post_data);
  10545. } else if (in_array($model, $this->gpt_text_models)) {
  10546. // GPT-5.4 模型使用 TokenRouter API
  10547. $chatResult = $this->gpt54ChatOnly($post_data);
  10548. } else {
  10549. // 其他模型使用火山引擎API
  10550. $chatResult = $this->volcEngineChatCompletion($post_data);
  10551. }
  10552. if (is_array($chatResult)) {
  10553. extract($chatResult);
  10554. }else {
  10555. Utils::throwError('20003: 接口调用失败!');
  10556. }
  10557. return [
  10558. 'type' => 'done',
  10559. // 'episode' => $episode,
  10560. 'answer' => $fullContent,
  10561. 'reasoning' => $fullReasoningContent,
  10562. 'usage' => $usage
  10563. ];
  10564. }
  10565. // 仅调用deepseek对话接口
  10566. private function chatOnly($post_data) {
  10567. $post_data['max_tokens'] = 300000;
  10568. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10569. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10570. $response = $result->getBody()->getContents();
  10571. $response_arr = json_decode($response, true);
  10572. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10573. $fullContent = '';
  10574. $fullReasoningContent = [];
  10575. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10576. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10577. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10578. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10579. }
  10580. return [
  10581. 'fullContent' => $fullContent,
  10582. 'fullReasoningContent' => $fullReasoningContent,
  10583. 'usage' => $usage
  10584. ];
  10585. }
  10586. // 仅调用 GPT-5.4 对话接口(非流式)
  10587. private function gpt54ChatOnly($post_data) {
  10588. $apiKey = env('GPT_54_API_KEY');
  10589. if (empty($apiKey)) {
  10590. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10591. }
  10592. // 先探活,服务不可用时自动重试
  10593. $this->ensureGptServiceAvailable();
  10594. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10595. $headers = [
  10596. 'Authorization' => 'Bearer ' . $apiKey,
  10597. 'Content-Type' => 'application/json'
  10598. ];
  10599. // 移除 thinking 参数,GPT-5.4 不支持
  10600. if (isset($post_data['thinking'])) {
  10601. unset($post_data['thinking']);
  10602. }
  10603. if (isset($post_data['reasoning_effort'])) {
  10604. unset($post_data['reasoning_effort']);
  10605. }
  10606. $post_data['max_completion_tokens'] = 100000;
  10607. // 确保 stream 为 false
  10608. $post_data['stream'] = false;
  10609. $maxRetries = $this->gptRetryTimes();
  10610. $interval = $this->gptRetryInterval();
  10611. $attempt = 0;
  10612. while (true) {
  10613. try {
  10614. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10615. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10616. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10617. 'json' => $post_data,
  10618. 'headers' => $headers
  10619. ]);
  10620. $response = $result->getBody()->getContents();
  10621. $response_arr = json_decode($response, true);
  10622. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10623. $fullContent = '';
  10624. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10625. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10626. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10627. }
  10628. return [
  10629. 'fullContent' => $fullContent,
  10630. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10631. 'usage' => $usage
  10632. ];
  10633. } catch (\Exception $e) {
  10634. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10635. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10636. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10637. throw $e;
  10638. }
  10639. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10640. 'retry' => $attempt + 1,
  10641. 'max_retries' => $maxRetries,
  10642. 'error' => $e->getMessage()
  10643. ]);
  10644. sleep($interval);
  10645. $attempt++;
  10646. }
  10647. }
  10648. }
  10649. private function splitContent($content) {
  10650. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10651. $chapters = [];
  10652. // 匹配章节标题格式:
  10653. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10654. // 2. 格式支持:
  10655. // - **第一集**
  10656. // - 第一集:
  10657. // - ###第1章 重生
  10658. // - ##第2章 相救
  10659. // - 第三章 共处一室
  10660. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10661. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10662. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10663. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10664. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10665. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10666. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10667. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10668. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10669. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10670. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10671. // 用正则找出所有章节标题的位置
  10672. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10673. $titleCount = count($matches[0]);
  10674. for ($i = 0; $i < $titleCount; $i++) {
  10675. // 获取当前章节标题
  10676. $titleLine = trim($matches[0][$i][0]);
  10677. // 去除标题开头的特殊符号
  10678. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10679. // 去除标题结尾的冒号和特殊符号
  10680. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10681. $cleanTitle = trim($cleanTitle);
  10682. // 获取当前标题的结束位置
  10683. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10684. // 获取下一个章节标题的开始位置(如果存在)
  10685. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10686. // 提取章节内容(从标题结束到下一个标题开始)
  10687. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10688. // 清理内容:去除前后空白和分隔线
  10689. $chapterContent = trim($chapterContent);
  10690. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10691. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10692. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10693. $chapters[] = [
  10694. 'title' => $cleanTitle,
  10695. 'content' => $chapterContent
  10696. ];
  10697. }
  10698. }
  10699. } else {
  10700. // 如果没有匹配到章节,返回整个内容
  10701. $chapters[] = [
  10702. 'title' => '',
  10703. 'content' => $content
  10704. ];
  10705. }
  10706. return $chapters;
  10707. }
  10708. public function getContentByBid($bid) {
  10709. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10710. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10711. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10712. $content = '';
  10713. foreach ($chapters as $chapter) {
  10714. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10715. }
  10716. return $content;
  10717. }
  10718. public function getContentByScriptId($script_id) {
  10719. $content = '';
  10720. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10721. if ($contents) {
  10722. $content = implode(PHP_EOL, $contents);
  10723. }else {
  10724. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10725. }
  10726. return $content;
  10727. }
  10728. /**
  10729. * 根据文件类型提取文本内容
  10730. *
  10731. * @param mixed $file 文件对象或文件路径
  10732. * @return string
  10733. */
  10734. public function extractFileContent($file) {
  10735. // 获取文件路径和扩展名
  10736. if (is_string($file)) {
  10737. $filePath = $file;
  10738. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10739. } else {
  10740. // Laravel UploadedFile 对象
  10741. $filePath = $file->getRealPath();
  10742. $extension = strtolower($file->getClientOriginalExtension());
  10743. }
  10744. $content = '';
  10745. switch ($extension) {
  10746. case 'txt':
  10747. $content = $this->extractTxtContent($filePath);
  10748. break;
  10749. case 'pdf':
  10750. $content = $this->extractPdfContent($filePath);
  10751. break;
  10752. case 'doc':
  10753. case 'docx':
  10754. $content = $this->extractWordContent($filePath);
  10755. break;
  10756. // case 'jpg':
  10757. // case 'jpeg':
  10758. // case 'png':
  10759. // case 'gif':
  10760. // case 'bmp':
  10761. // case 'webp':
  10762. // $content = $this->extractImageContent($filePath);
  10763. // break;
  10764. default:
  10765. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10766. }
  10767. return $content;
  10768. }
  10769. /**
  10770. * 提取 TXT 文件内容
  10771. */
  10772. private function extractTxtContent($filePath) {
  10773. if (!file_exists($filePath)) {
  10774. Utils::throwError('20003:文件不存在');
  10775. }
  10776. $content = file_get_contents($filePath);
  10777. // 尝试检测并转换编码
  10778. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10779. if ($encoding && $encoding !== 'UTF-8') {
  10780. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10781. }
  10782. return trim($content);
  10783. }
  10784. /**
  10785. * 提取 PDF 文件内容
  10786. */
  10787. private function extractPdfContent($filePath) {
  10788. if (!file_exists($filePath)) {
  10789. Utils::throwError('20003:文件不存在');
  10790. }
  10791. try {
  10792. $parser = new PdfParser();
  10793. $pdf = $parser->parseFile($filePath);
  10794. $content = $pdf->getText();
  10795. return trim($content);
  10796. } catch (\Exception $e) {
  10797. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10798. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10799. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10800. }
  10801. }
  10802. /**
  10803. * 提取 Word 文件内容(支持 doc 和 docx)
  10804. */
  10805. private function extractWordContent($filePath) {
  10806. if (!file_exists($filePath)) {
  10807. Utils::throwError('20003:文件不存在');
  10808. }
  10809. try {
  10810. $phpWord = WordIOFactory::load($filePath);
  10811. $content = '';
  10812. foreach ($phpWord->getSections() as $section) {
  10813. foreach ($section->getElements() as $element) {
  10814. $content .= $this->extractWordElementText($element);
  10815. }
  10816. }
  10817. return trim($content);
  10818. } catch (\Exception $e) {
  10819. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10820. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10821. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10822. }
  10823. }
  10824. /**
  10825. * 递归提取 Word 元素中的文本
  10826. */
  10827. private function extractWordElementText($element) {
  10828. $text = '';
  10829. if (method_exists($element, 'getText')) {
  10830. $text .= $element->getText() . "\n";
  10831. } elseif (method_exists($element, 'getElements')) {
  10832. foreach ($element->getElements() as $childElement) {
  10833. $text .= $this->extractWordElementText($childElement);
  10834. }
  10835. }
  10836. return $text;
  10837. }
  10838. /**
  10839. * 提取图片内容(使用火山引擎 OCR)
  10840. */
  10841. private function extractImageContent($filePath) {
  10842. if (!file_exists($filePath)) {
  10843. Utils::throwError('20003:文件不存在');
  10844. }
  10845. try {
  10846. // 读取图片并转换为 base64
  10847. $imageData = file_get_contents($filePath);
  10848. $base64Image = base64_encode($imageData);
  10849. // 调用火山引擎 OCR 服务
  10850. $content = $this->callVolcEngineOCR($base64Image);
  10851. return trim($content);
  10852. } catch (\Exception $e) {
  10853. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10854. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10855. Utils::throwError('20003:图片识别失败');
  10856. }
  10857. }
  10858. /**
  10859. * 调用火山引擎 OCR 服务识别图片文字
  10860. *
  10861. * @param string $base64Image base64 编码的图片数据
  10862. * @return string 识别的文字内容
  10863. */
  10864. private function callVolcEngineOCR($base64Image) {
  10865. $method = 'POST';
  10866. $service = 'cv';
  10867. $host = 'visual.volcengineapi.com';
  10868. $region = env('VOLC_REGION', 'cn-north-1');
  10869. $access_key = env('VOLC_AK');
  10870. $secret_key = env('VOLC_SK');
  10871. $action = 'OCRNormal';
  10872. $version = '2020-08-26';
  10873. if (!$access_key || !$secret_key) {
  10874. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10875. }
  10876. // 请求体
  10877. $body = json_encode([
  10878. 'image_base64' => $base64Image
  10879. ]);
  10880. // 生成签名
  10881. $headers = $this->getVolcEngineSignHeaders(
  10882. $method, $service, $host, $region,
  10883. "Action={$action}&Version={$version}",
  10884. $access_key, $secret_key, $body
  10885. );
  10886. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10887. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10888. 'headers' => $headers,
  10889. 'body' => $body
  10890. ]);
  10891. $response_arr = json_decode($response->getBody()->getContents(), true);
  10892. // 提取识别的文字
  10893. $textLines = [];
  10894. if (isset($response_arr['data']['line_texts'])) {
  10895. $textLines = $response_arr['data']['line_texts'];
  10896. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10897. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10898. if (isset($info['text'])) {
  10899. $textLines[] = $info['text'];
  10900. }
  10901. }
  10902. }
  10903. if (empty($textLines)) {
  10904. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10905. return '';
  10906. }
  10907. return implode("\n", $textLines);
  10908. }
  10909. /**
  10910. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10911. */
  10912. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10913. $contentType = 'application/json';
  10914. $accept = 'application/json';
  10915. // 获取当前UTC时间
  10916. $t = new DateTime('now', new DateTimeZone('UTC'));
  10917. $xDate = $t->format('Ymd\THis\Z');
  10918. $dateStamp = $t->format('Ymd');
  10919. // 计算 body 的 sha256 哈希
  10920. $payloadHash = hash('sha256', $body);
  10921. // 1. 拼接规范请求串
  10922. $canonicalUri = '/';
  10923. $canonicalQueryString = $queryString;
  10924. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10925. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10926. $canonicalRequest = implode("\n", [
  10927. $method,
  10928. $canonicalUri,
  10929. $canonicalQueryString,
  10930. $canonicalHeaders,
  10931. $signedHeaders,
  10932. $payloadHash
  10933. ]);
  10934. // 2. 拼接待签名字符串
  10935. $algorithm = 'HMAC-SHA256';
  10936. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10937. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10938. $stringToSign = implode("\n", [
  10939. $algorithm,
  10940. $xDate,
  10941. $credentialScope,
  10942. $hashedCanonicalRequest
  10943. ]);
  10944. // 3. 计算签名
  10945. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10946. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10947. // 4. 添加签名到请求头
  10948. $authorizationHeader = sprintf(
  10949. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10950. $algorithm,
  10951. $access_key,
  10952. $credentialScope,
  10953. $signedHeaders,
  10954. $signature
  10955. );
  10956. return [
  10957. 'Accept' => $accept,
  10958. 'Content-Type' => $contentType,
  10959. 'Host' => $host,
  10960. 'X-Date' => $xDate,
  10961. 'X-Content-Sha256'=> $payloadHash,
  10962. 'Authorization' => $authorizationHeader
  10963. ];
  10964. }
  10965. public function generateScriptWords($cid, $model = 'r1') {
  10966. ini_set('max_execution_time', 0);
  10967. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10968. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10969. // 模型兼容性处理和思考模式设置
  10970. $thinkingMode = 'disabled';
  10971. $reasoningEffort = 'high';
  10972. if ($model == 'r1') {
  10973. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10974. $thinkingMode = 'enabled';
  10975. } else {
  10976. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10977. $thinkingMode = 'disabled';
  10978. }
  10979. $messages = [
  10980. [
  10981. 'role' => 'system',
  10982. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10983. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10984. 2.非对话部分请全部用旁白角色代替
  10985. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10986. ],
  10987. [
  10988. 'role' => 'user',
  10989. 'content' => $content
  10990. ]
  10991. ];
  10992. $post_data = [
  10993. 'model' => $model,
  10994. 'messages' => $messages,
  10995. // 'max_tokens' => 8192,
  10996. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10997. 'frequency_penalty' => 0,
  10998. 'presence_penalty' => 0,
  10999. 'thinking' => ['type' => $thinkingMode],
  11000. 'response_format' => [
  11001. 'type' => 'text'
  11002. ],
  11003. 'stream' => false
  11004. ];
  11005. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11006. // 根据模型类型选择调用方法
  11007. $fullContent = '';
  11008. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11009. // DeepSeek 官方模型使用 DeepSeek API
  11010. $chatResult = $this->chatOnly($post_data);
  11011. } else if (in_array($model, $this->gpt_text_models)) {
  11012. // GPT-5.4 模型使用 TokenRouter API
  11013. $chatResult = $this->gpt54ChatOnly($post_data);
  11014. } else {
  11015. // 其他模型使用火山引擎API
  11016. $chatResult = $this->volcEngineChatCompletion($post_data);
  11017. }
  11018. if (is_array($chatResult)) {
  11019. $fullContent = $chatResult['fullContent'];
  11020. }
  11021. return $fullContent;
  11022. }
  11023. /**
  11024. * 智能化解析集数信息
  11025. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11026. *
  11027. * @param string $prompt 用户输入的提示词
  11028. * @return int|null 解析出的集数,如果没有找到则返回null
  11029. */
  11030. private function extractEpisodeNumber($prompt)
  11031. {
  11032. if (empty($prompt)) {
  11033. return null;
  11034. }
  11035. // 定义各种可能的表达模式
  11036. $patterns = [
  11037. // 基本模式:改成N集、调整成N集、修改成N集
  11038. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11039. // 扩展模式:分成N集、拆分成N集、分割成N集
  11040. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11041. // 数量模式:N集、共N集、总共N集
  11042. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11043. // 制作模式:制作N集、生成N集、创建N集
  11044. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11045. // 计划模式:计划N集、预计N集、打算N集
  11046. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11047. // 需要模式:需要N集、要N集
  11048. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11049. // 中文数字模式:改成三集、调整成五集等
  11050. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11051. // 英文数字模式
  11052. '/(?: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',
  11053. ];
  11054. // 中文数字转阿拉伯数字的映射
  11055. $chineseNumbers = [
  11056. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11057. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11058. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11059. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11060. ];
  11061. // 逐个尝试匹配模式
  11062. foreach ($patterns as $pattern) {
  11063. if (preg_match($pattern, $prompt, $matches)) {
  11064. $number = trim($matches[1]);
  11065. // 如果是中文数字,转换为阿拉伯数字
  11066. if (isset($chineseNumbers[$number])) {
  11067. return $chineseNumbers[$number];
  11068. }
  11069. // 如果是阿拉伯数字,直接返回
  11070. if (is_numeric($number)) {
  11071. $episodeNum = intval($number);
  11072. // 合理性检查:集数应该在1-100之间
  11073. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11074. return $episodeNum;
  11075. }
  11076. }
  11077. }
  11078. }
  11079. return null;
  11080. }
  11081. /**
  11082. * 调用火山引擎对话(Chat) API
  11083. *
  11084. * @param array $params 包含以下参数:
  11085. * - model: 模型ID(必填)
  11086. * - messages: 消息列表(必填)
  11087. * - stream: 是否流式输出(可选,默认false)
  11088. * - max_tokens: 最大输出token数(可选)
  11089. * - temperature: 采样温度(可选,默认1)
  11090. * - top_p: 核采样概率(可选,默认0.7)
  11091. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11092. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11093. * - stop: 停止词(可选)
  11094. * - tools: 工具列表(可选)
  11095. * @return array|Generator 非流式返回数组,流式返回生成器
  11096. */
  11097. public function volcEngineChatCompletion(array $params)
  11098. {
  11099. $apiKey = env('VOLC_AI_API_KEY');
  11100. if (empty($apiKey)) {
  11101. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11102. }
  11103. // 构建请求参数
  11104. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11105. $requestData = [
  11106. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11107. 'messages' => $params['messages'] ?? [],
  11108. ];
  11109. if (!in_array($originalModel, $this->valid_text_models)) {
  11110. Utils::throwError('20003:该模型不支持!');
  11111. }
  11112. // 添加可选参数
  11113. if (isset($params['stream'])) {
  11114. $requestData['stream'] = $params['stream'];
  11115. }
  11116. if (isset($params['stream_options'])) {
  11117. $requestData['stream_options'] = $params['stream_options'];
  11118. }
  11119. if (isset($params['max_tokens'])) {
  11120. $requestData['max_tokens'] = $params['max_tokens'];
  11121. }else if (isset($params['max_completion_tokens'])) {
  11122. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11123. }else {
  11124. $requestData['max_completion_tokens'] = 100000;
  11125. }
  11126. if (isset($params['temperature'])) {
  11127. $requestData['temperature'] = $params['temperature'];
  11128. }
  11129. if (isset($params['top_p'])) {
  11130. $requestData['top_p'] = $params['top_p'];
  11131. }
  11132. if (isset($params['frequency_penalty'])) {
  11133. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11134. }
  11135. if (isset($params['presence_penalty'])) {
  11136. $requestData['presence_penalty'] = $params['presence_penalty'];
  11137. }
  11138. if (isset($params['stop'])) {
  11139. $requestData['stop'] = $params['stop'];
  11140. }
  11141. if (isset($params['tools'])) {
  11142. $requestData['tools'] = $params['tools'];
  11143. }
  11144. if (isset($params['tool_choice'])) {
  11145. $requestData['tool_choice'] = $params['tool_choice'];
  11146. }
  11147. if (isset($params['response_format'])) {
  11148. $requestData['response_format'] = $params['response_format'];
  11149. }
  11150. if (isset($params['thinking'])) {
  11151. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11152. if (is_array($params['thinking'])) {
  11153. $requestData['thinking'] = $params['thinking'];
  11154. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11155. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11156. }
  11157. } else {
  11158. $requestData['thinking'] = ['type' => $params['thinking']];
  11159. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11160. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11161. }
  11162. }
  11163. } else {
  11164. $requestData['thinking'] = ['type' => 'disabled'];
  11165. }
  11166. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11167. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11168. try {
  11169. // 判断是否为流式输出
  11170. $isStream = isset($params['stream']) && $params['stream'] === true;
  11171. if ($isStream) {
  11172. // 流式输出
  11173. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11174. } else {
  11175. // 非流式输出
  11176. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11177. 'headers' => [
  11178. 'Authorization' => 'Bearer ' . $apiKey,
  11179. 'Content-Type' => 'application/json',
  11180. ],
  11181. 'json' => $requestData
  11182. ]);
  11183. $responseData = json_decode($response->getBody(), true);
  11184. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11185. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11186. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11187. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11188. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11189. }
  11190. return [
  11191. 'fullContent' => $fullContent,
  11192. 'fullReasoningContent' => $fullReasoningContent,
  11193. 'usage' => $usage
  11194. ];
  11195. }
  11196. } catch (\Exception $e) {
  11197. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11198. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11199. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11200. }
  11201. }
  11202. /**
  11203. * 火山引擎对话API流式输出
  11204. *
  11205. * @param Client $client HTTP客户端
  11206. * @param string $apiKey API密钥
  11207. * @param array $requestData 请求数据
  11208. * @return Generator
  11209. */
  11210. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11211. {
  11212. try {
  11213. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11214. 'headers' => [
  11215. 'Authorization' => 'Bearer ' . $apiKey,
  11216. 'Content-Type' => 'application/json',
  11217. ],
  11218. 'json' => $requestData,
  11219. 'stream' => true
  11220. ]);
  11221. $body = $response->getBody();
  11222. $buffer = '';
  11223. $fullContent = '';
  11224. $fullReasoningContent = '';
  11225. $usage = [];
  11226. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11227. // 逐行读取流式响应
  11228. while (!$body->eof()) {
  11229. $chunk = $body->read(1024);
  11230. $buffer .= $chunk;
  11231. // 按行分割
  11232. $lines = explode("\n", $buffer);
  11233. $buffer = array_pop($lines);
  11234. foreach ($lines as $line) {
  11235. $line = trim($line);
  11236. if (empty($line)) {
  11237. continue;
  11238. }
  11239. // 检查是否是SSE数据行
  11240. if (strpos($line, 'data: ') !== 0) {
  11241. continue;
  11242. }
  11243. $data = substr($line, 6);
  11244. if ($data === '[DONE]') {
  11245. dLog('deepseek')->info('收到结束标记');
  11246. break 2;
  11247. }
  11248. try {
  11249. $json = json_decode($data, true);
  11250. if (json_last_error() !== JSON_ERROR_NONE) {
  11251. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11252. continue;
  11253. }
  11254. if (isset($json['choices'][0]['delta'])) {
  11255. $delta = $json['choices'][0]['delta'];
  11256. // 处理思维链内容
  11257. if (isset($delta['reasoning_content'])) {
  11258. $fullReasoningContent .= $delta['reasoning_content'];
  11259. yield [
  11260. 'type' => 'reasoning',
  11261. 'content' => $delta['reasoning_content'],
  11262. 'full_reasoning' => $fullReasoningContent
  11263. ];
  11264. }
  11265. // 处理回答内容
  11266. if (isset($delta['content'])) {
  11267. $fullContent .= $delta['content'];
  11268. yield [
  11269. 'type' => 'content',
  11270. 'content' => $delta['content'],
  11271. ];
  11272. }
  11273. }
  11274. // 获取使用统计信息
  11275. if (isset($json['usage'])) {
  11276. $usage = $json['usage'];
  11277. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11278. }
  11279. } catch (\Exception $e) {
  11280. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11281. continue;
  11282. }
  11283. }
  11284. }
  11285. dLog('deepseek')->info('流式读取完成', [
  11286. 'content_length' => strlen($fullContent),
  11287. 'reasoning_length' => strlen($fullReasoningContent)
  11288. ]);
  11289. yield [
  11290. 'type' => 'done',
  11291. 'full_content' => $fullContent,
  11292. 'full_reasoning' => $fullReasoningContent,
  11293. 'usage' => $usage
  11294. ];
  11295. } catch (\Exception $e) {
  11296. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11297. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11298. throw $e;
  11299. }
  11300. }
  11301. /**
  11302. * 检查并创建图片生成任务
  11303. *
  11304. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11305. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11306. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11307. * @param string $art_style 美术风格
  11308. * @return array 更新后的资源列表
  11309. */
  11310. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11311. {
  11312. // 确保参数为数组
  11313. $merged_items = is_array($merged_items) ? $merged_items : [];
  11314. $global_items = is_array($global_items) ? $global_items : [];
  11315. // 构建全局资源映射表,用于快速查找
  11316. $global_map = [];
  11317. foreach ($global_items as $item) {
  11318. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11319. if ($itemKey === '') {
  11320. continue;
  11321. }
  11322. $global_map[$itemKey] = $item;
  11323. }
  11324. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11325. foreach ($merged_items as &$item) {
  11326. $item_name = getProp($item, $nameKey);
  11327. $item_description = getProp($item, 'description');
  11328. // $item_url = getProp($item, 'url');
  11329. // // 如果已有图片URL,跳过
  11330. // if (!empty($item_url)) {
  11331. // continue;
  11332. // }
  11333. // 如果是旁白角色,跳过
  11334. if ($nameKey === 'role' && $item_name === '旁白') {
  11335. continue;
  11336. }
  11337. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11338. if ($itemKey === '') {
  11339. continue;
  11340. }
  11341. $need_create_task = false;
  11342. // 条件1:在全局资源中找不到匹配的名称
  11343. if (!isset($global_map[$itemKey])) {
  11344. $need_create_task = true;
  11345. } else {
  11346. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11347. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11348. $current_description = trim((string)$item_description);
  11349. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11350. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11351. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11352. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11353. $need_create_task = true;
  11354. }
  11355. }
  11356. // 如果需要创建任务,调用图片生成服务
  11357. if ($need_create_task) {
  11358. try {
  11359. // 优先使用 pic_prompt,如果没有则使用 description
  11360. $pic_prompt = getProp($item, 'pic_prompt');
  11361. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11362. // 添加美术风格前缀
  11363. if ($art_style) {
  11364. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11365. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11366. $description = "{$prefix}:{$description}";
  11367. }
  11368. $params = [
  11369. 'prompt' => $description,
  11370. 'ref_img_urls' => []
  11371. ];
  11372. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11373. $task_id = $task->id;
  11374. if ($task_id) {
  11375. $item['task_id'] = $task_id;
  11376. $item['task_status'] = 'processing';
  11377. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11378. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11379. }
  11380. } catch (\Exception $e) {
  11381. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11382. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11383. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11384. // 不抛出异常,继续处理其他资源
  11385. }
  11386. }
  11387. }
  11388. return $merged_items;
  11389. }
  11390. /**
  11391. * 同步新出现的主体和场景到全局
  11392. *
  11393. * @param int $anime_id 动漫ID
  11394. * @param array $merged_roles 合并后的角色列表
  11395. * @param array $merged_scenes 合并后的场景列表
  11396. * @param array $global_roles 全局角色列表
  11397. * @param array $global_scenes 全局场景列表
  11398. * @return void
  11399. */
  11400. private function syncNewResourcesToGlobal(
  11401. int $anime_id,
  11402. array $merged_roles,
  11403. array $merged_scenes,
  11404. array $global_roles,
  11405. array $global_scenes
  11406. ): void {
  11407. // 构建全局角色映射表
  11408. $global_role_map = [];
  11409. foreach ($global_roles as $role) {
  11410. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11411. if ($roleKey !== '') {
  11412. $global_role_map[$roleKey] = $role;
  11413. }
  11414. }
  11415. // 构建全局场景映射表
  11416. $global_scene_map = [];
  11417. foreach ($global_scenes as $scene) {
  11418. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11419. if ($sceneKey !== '') {
  11420. $global_scene_map[$sceneKey] = $scene;
  11421. }
  11422. }
  11423. $need_update = false;
  11424. $new_global_roles = $global_roles;
  11425. $new_global_scenes = $global_scenes;
  11426. // 检查并添加新角色到全局
  11427. foreach ($merged_roles as $role) {
  11428. $role_name = getProp($role, 'role');
  11429. // 跳过旁白
  11430. if ($role_name === '旁白') {
  11431. continue;
  11432. }
  11433. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11434. if ($roleKey === '') {
  11435. continue;
  11436. }
  11437. // 如果全局中不存在该角色,添加到全局
  11438. if (!isset($global_role_map[$roleKey])) {
  11439. $new_global_roles[] = [
  11440. 'role' => $role_name,
  11441. 'description' => getProp($role, 'description', ''),
  11442. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11443. 'voice_name' => getProp($role, 'voice_name', ''),
  11444. 'voice_type' => getProp($role, 'voice_type', ''),
  11445. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11446. 'url' => getProp($role, 'url', ''),
  11447. 'task_id' => getProp($role, 'task_id', ''),
  11448. 'task_status' => getProp($role, 'task_status', ''),
  11449. ];
  11450. $global_role_map[$roleKey] = true; // 标记已添加
  11451. $need_update = true;
  11452. dLog('deepseek')->info("新角色同步到全局", [
  11453. 'anime_id' => $anime_id,
  11454. 'role' => $role_name,
  11455. 'task_id' => getProp($role, 'task_id', ''),
  11456. ]);
  11457. }
  11458. // else {
  11459. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11460. // $global_role = $global_role_map[$roleKey];
  11461. // if (is_array($global_role)) {
  11462. // $updated = false;
  11463. // $update_fields = [];
  11464. // // 检查描述是否更新
  11465. // $current_description = trim((string)getProp($role, 'description'));
  11466. // $global_description = trim((string)getProp($global_role, 'description'));
  11467. // if ($current_description !== '' && $current_description !== $global_description) {
  11468. // $updated = true;
  11469. // $update_fields[] = 'description';
  11470. // }
  11471. // // 检查pic_prompt是否更新
  11472. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11473. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11474. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11475. // $updated = true;
  11476. // $update_fields[] = 'pic_prompt';
  11477. // }
  11478. // // 检查图片任务信息是否更新
  11479. // $current_task_id = getProp($role, 'task_id');
  11480. // $global_task_id = getProp($global_role, 'task_id');
  11481. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11482. // $updated = true;
  11483. // $update_fields[] = 'task_id';
  11484. // }
  11485. // // 如果有更新,同步到全局
  11486. // if ($updated) {
  11487. // foreach ($new_global_roles as &$global_role_item) {
  11488. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11489. // if ($global_role_key === $roleKey) {
  11490. // if (in_array('description', $update_fields)) {
  11491. // $global_role_item['description'] = $current_description;
  11492. // }
  11493. // if (in_array('pic_prompt', $update_fields)) {
  11494. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11495. // }
  11496. // if (in_array('task_id', $update_fields)) {
  11497. // $global_role_item['task_id'] = $current_task_id;
  11498. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11499. // $global_role_item['url'] = getProp($role, 'url', '');
  11500. // }
  11501. // break;
  11502. // }
  11503. // }
  11504. // $need_update = true;
  11505. // dLog('deepseek')->info("角色信息更新到全局", [
  11506. // 'anime_id' => $anime_id,
  11507. // 'role' => $role_name,
  11508. // 'update_fields' => implode(',', $update_fields),
  11509. // ]);
  11510. // }
  11511. // }
  11512. // }
  11513. }
  11514. // 检查并添加新场景到全局
  11515. foreach ($merged_scenes as $scene) {
  11516. $scene_name = getProp($scene, 'scene');
  11517. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11518. if ($sceneKey === '') {
  11519. continue;
  11520. }
  11521. // 如果全局中不存在该场景,添加到全局
  11522. if (!isset($global_scene_map[$sceneKey])) {
  11523. $new_global_scenes[] = [
  11524. 'scene' => $scene_name,
  11525. 'description' => getProp($scene, 'description', ''),
  11526. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11527. 'url' => getProp($scene, 'url', ''),
  11528. 'task_id' => getProp($scene, 'task_id', ''),
  11529. 'task_status' => getProp($scene, 'task_status', ''),
  11530. ];
  11531. $global_scene_map[$sceneKey] = true; // 标记已添加
  11532. $need_update = true;
  11533. dLog('deepseek')->info("新场景同步到全局", [
  11534. 'anime_id' => $anime_id,
  11535. 'scene' => $scene_name,
  11536. 'task_id' => getProp($scene, 'task_id', ''),
  11537. ]);
  11538. }
  11539. // else {
  11540. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11541. // $global_scene = $global_scene_map[$sceneKey];
  11542. // if (is_array($global_scene)) {
  11543. // $updated = false;
  11544. // $update_fields = [];
  11545. // // 检查描述是否更新
  11546. // $current_description = trim((string)getProp($scene, 'description'));
  11547. // $global_description = trim((string)getProp($global_scene, 'description'));
  11548. // if ($current_description !== '' && $current_description !== $global_description) {
  11549. // $updated = true;
  11550. // $update_fields[] = 'description';
  11551. // }
  11552. // // 检查pic_prompt是否更新
  11553. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11554. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11555. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11556. // $updated = true;
  11557. // $update_fields[] = 'pic_prompt';
  11558. // }
  11559. // // 检查图片任务信息是否更新
  11560. // $current_task_id = getProp($scene, 'task_id');
  11561. // $global_task_id = getProp($global_scene, 'task_id');
  11562. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11563. // $updated = true;
  11564. // $update_fields[] = 'task_id';
  11565. // }
  11566. // // 如果有更新,同步到全局
  11567. // if ($updated) {
  11568. // foreach ($new_global_scenes as &$global_scene_item) {
  11569. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11570. // if ($global_scene_key === $sceneKey) {
  11571. // if (in_array('description', $update_fields)) {
  11572. // $global_scene_item['description'] = $current_description;
  11573. // }
  11574. // if (in_array('pic_prompt', $update_fields)) {
  11575. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11576. // }
  11577. // if (in_array('task_id', $update_fields)) {
  11578. // $global_scene_item['task_id'] = $current_task_id;
  11579. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11580. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11581. // }
  11582. // break;
  11583. // }
  11584. // }
  11585. // $need_update = true;
  11586. // dLog('deepseek')->info("场景信息更新到全局", [
  11587. // 'anime_id' => $anime_id,
  11588. // 'scene' => $scene_name,
  11589. // 'update_fields' => implode(',', $update_fields),
  11590. // ]);
  11591. // }
  11592. // }
  11593. // }
  11594. }
  11595. // 如果有新增或更新,更新数据库
  11596. if ($need_update) {
  11597. $update_data = [
  11598. 'roles' => json_encode($new_global_roles, 256),
  11599. 'scenes' => json_encode($new_global_scenes, 256),
  11600. 'updated_at' => date('Y-m-d H:i:s'),
  11601. ];
  11602. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11603. if ($result !== false) {
  11604. dLog('deepseek')->info("全局角色和场景更新成功", [
  11605. 'anime_id' => $anime_id,
  11606. 'roles_count' => count($new_global_roles),
  11607. 'scenes_count' => count($new_global_scenes),
  11608. ]);
  11609. } else {
  11610. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11611. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11612. }
  11613. }
  11614. }
  11615. }