DeepSeekService.php 284 KB

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