app.ts 298 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607
  1. import { Component, signal, NgZone, ChangeDetectorRef, ViewEncapsulation } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { FormsModule } from '@angular/forms';
  4. import { RouterModule } from '@angular/router';
  5. import { TimeFormatPipe } from './pipes/time-format.pipe';
  6. import { NumberFormatPipe } from './pipes/number-format.pipe';
  7. import { FileSizePipe } from './pipes/file-size.pipe';
  8. import { DouyinService } from './services/douyin.service';
  9. import { JimengService } from './services/jimeng.service';
  10. import { LlmService } from './services/llm.service';
  11. import { PortraitPipelineService, PortraitPipelineResult } from './services/portrait-pipeline.service';
  12. import { DigitalHumanService, DigitalHumanRequest, DigitalHumanEvent } from './services/digital-human.service';
  13. import { DigitalHumanFormComponent, TimbreOption, PromptPreset } from './components/digital-human-form/digital-human-form.component';
  14. import { PortraitPrepareComponent, PortraitPrepareOutput } from './components/portrait-prepare/portrait-prepare.component';
  15. import { HttpClient, HttpErrorResponse } from '@angular/common/http';
  16. import { timeout, finalize } from 'rxjs/operators';
  17. import { of, Observable } from 'rxjs';
  18. import { PIPELINES, PipelineDef, getSidebarPipelines } from './pipelines/pipeline-registry';
  19. import { ImageToVideoComponent } from './pages/pipelines/image-to-video/image-to-video.component';
  20. import { ActionTransferComponent } from './pages/pipelines/action-transfer/action-transfer.component';
  21. import { AssetRemixComponent } from './pages/pipelines/asset-remix/asset-remix.component';
  22. import { TopicToVideoComponent } from './pages/pipelines/topic-to-video/topic-to-video.component';
  23. import { AppSidebarComponent } from './components/app-sidebar/app-sidebar.component';
  24. import { HomeComponent } from './pages/home/home.component';
  25. import { RecentTaskPillComponent, RecentTaskView } from './components/recent-task-pill/recent-task-pill.component';
  26. import { AppAssistantComponent } from './components/app-assistant/app-assistant.component';
  27. import { AssistantSuggestion } from './services/assistant.service';
  28. import { VoicePickerComponent, VoiceSelection } from './components/voice-picker/voice-picker.component';
  29. // 类型定义
  30. interface VideoInfo {
  31. aweme_id: string;
  32. desc: string;
  33. cover_url: string;
  34. cover_candidates?: string[];
  35. duration: number;
  36. create_time?: number;
  37. publishDate?: Date | null;
  38. author: {
  39. nickname: string;
  40. sec_uid: string;
  41. };
  42. statistics: {
  43. play_count: number;
  44. digg_count: number;
  45. comment_count: number;
  46. share_count: number;
  47. };
  48. text_extra?: string[];
  49. // 下载相关
  50. downloadProgress?: number;
  51. isDownloading?: boolean;
  52. downloadUrl?: string;
  53. }
  54. interface Task {
  55. id: string;
  56. keyword: string;
  57. status: 'pending' | 'processing' | 'completed' | 'failed' | 'timeout';
  58. step: 'search' | 'detail' | 'comments' | 'download' | 'transcribe' | 'generate' | 'complete'
  59. | 'vg-upload' | 'vg-analyze' | 'vg-script' | 'vg-image' | 'vg-voice' | 'vg-composite';
  60. progress: number;
  61. cost: number;
  62. created_at: Date;
  63. updated_at: Date;
  64. result_url?: string;
  65. error_message?: string;
  66. original_video_title?: string;
  67. duration?: string;
  68. // 任务类型:remix=AI重塑, video-generation=视频生成
  69. type?: 'remix' | 'video-generation';
  70. // 视频生成专用持久化数据
  71. vgData?: {
  72. videoId: string;
  73. sourceFileName: string;
  74. sourceVideoUrl: string;
  75. step: number;
  76. transcript: string;
  77. analysisText: string;
  78. script: string;
  79. scriptSegments: { id: string; narration: string; imagePrompt: string; imagePromptCn?: string; }[];
  80. imageResults: { id: string; prompt: string; imageUrl: string; status: 'pending' | 'generating' | 'done' | 'failed'; }[];
  81. audioUrls: { segId: string; audioUrl: string; }[];
  82. voiceMode: 'clone' | 'system';
  83. voiceSpeakerId: string;
  84. voiceTimbreId: string;
  85. finalVideoUrl: string;
  86. };
  87. }
  88. interface TaskStats {
  89. pending: number;
  90. processing: number;
  91. completed: number;
  92. failed: number;
  93. }
  94. interface VoiceProfile {
  95. id: string;
  96. name: string;
  97. creation_mode?: string;
  98. speaker_id: string;
  99. timbre_id?: string;
  100. sample_text: string;
  101. text_prompt?: string;
  102. source_audio_text?: string;
  103. source_audio_name?: string;
  104. source_audio_format?: string;
  105. language: number;
  106. status: number | null;
  107. status_label: string;
  108. demo_audio: string;
  109. available_training_times: number | null;
  110. image_prompt_name?: string;
  111. x_api_resource_id?: string;
  112. model_version?: string;
  113. icl_speaker_id?: string;
  114. occupied?: boolean;
  115. synthesized_audio_url?: string;
  116. synthesized_work_id?: string;
  117. last_synthesis_text?: string;
  118. last_synthesis_ssml?: string;
  119. last_synthesis_x_api_resource_id?: string;
  120. last_synthesis_model?: string;
  121. last_synthesis_format?: string;
  122. last_synthesis_sample_rate?: number;
  123. last_synthesis_speech_rate?: number;
  124. last_synthesis_loudness_rate?: number;
  125. last_synthesis_emotion?: string;
  126. last_synthesis_emotion_scale?: number;
  127. last_synthesis_enable_subtitle?: boolean;
  128. last_synthesis_silence_duration?: number;
  129. last_synthesis_enable_language_detector?: boolean;
  130. last_synthesis_disable_markdown_filter?: boolean;
  131. last_synthesis_disable_emoji_filter?: boolean;
  132. last_synthesis_explicit_language?: string;
  133. latest_audio_url?: string;
  134. draft_synthesis_text?: string;
  135. draft_synthesis_ssml?: string;
  136. draft_synthesis_x_api_resource_id?: string;
  137. draft_synthesis_model?: string;
  138. draft_synthesis_format?: string;
  139. draft_synthesis_sample_rate?: number;
  140. draft_synthesis_speech_rate?: number;
  141. draft_synthesis_loudness_rate?: number;
  142. draft_synthesis_emotion?: string;
  143. draft_synthesis_emotion_scale?: number;
  144. draft_synthesis_enable_subtitle?: boolean;
  145. draft_synthesis_silence_duration?: number;
  146. draft_synthesis_enable_language_detector?: boolean;
  147. draft_synthesis_disable_markdown_filter?: boolean;
  148. draft_synthesis_disable_emoji_filter?: boolean;
  149. draft_synthesis_explicit_language?: string;
  150. is_synthesizing?: boolean;
  151. message?: string;
  152. request_id?: string;
  153. created_at: Date;
  154. updated_at?: Date;
  155. }
  156. interface GeneratedResult {
  157. id: string;
  158. type: 'video' | 'image';
  159. url: string;
  160. title: string;
  161. created_at: Date;
  162. quality: string;
  163. duration: string;
  164. cost: number;
  165. remixId?: string;
  166. videoId?: string;
  167. voiceProfileId?: string;
  168. voiceProfileName?: string;
  169. audioSourceLabel?: string;
  170. segments?: { id: string; videoUrl: string; prompt: string; status: string }[];
  171. /** P0+: 所属生成模式(来自 pipeline-registry,如 'digital_human' / 'image_to_video' 等) */
  172. pipelineId?: string;
  173. }
  174. interface HistoryRecord {
  175. id: string;
  176. original_video_title?: string;
  177. keyword: string;
  178. status: 'completed' | 'failed';
  179. cost: number;
  180. created_at: Date;
  181. duration?: string;
  182. remixId?: string;
  183. videoId?: string;
  184. styleName?: string;
  185. segmentCount?: number;
  186. successCount?: number;
  187. resultUrl?: string;
  188. quality?: string;
  189. voiceProfileId?: string;
  190. voiceProfileName?: string;
  191. audioSourceLabel?: string;
  192. /** P0+: 所属生成模式 id(与 pipeline-registry.PIPELINES[*].id 对应) */
  193. pipelineId?: string;
  194. }
  195. interface ManagedVideo {
  196. id: string;
  197. title: string;
  198. filename: string;
  199. filepath: string;
  200. size: number;
  201. duration: number;
  202. created_at: Date;
  203. modified_at: Date;
  204. category: string;
  205. tags: string[];
  206. description: string;
  207. thumbnail?: string;
  208. source: 'downloaded' | 'generated' | 'uploaded';
  209. metadata: {
  210. resolution: string;
  211. format: string;
  212. bitrate?: number;
  213. };
  214. // Whisper 转录文件路径
  215. whisper?: {
  216. transcript?: string;
  217. srt?: string;
  218. storyboard?: string;
  219. beautified?: string;
  220. };
  221. // AI重塑相关字段
  222. isRemixing?: boolean;
  223. remixProgress?: number;
  224. remixStyle?: string;
  225. originalVideoId?: string;
  226. remixVersions?: RemixVersion[];
  227. }
  228. interface RemixVersion {
  229. id: string;
  230. style: string;
  231. created_at: Date;
  232. file_path: string;
  233. thumbnail: string;
  234. description: string;
  235. parameters: RemixParameters;
  236. }
  237. interface RemixParameters {
  238. style: string;
  239. intensity: number;
  240. preserve_audio: boolean;
  241. quality: 'standard' | 'high' | 'ultra';
  242. effects: string[];
  243. }
  244. interface VideoCategory {
  245. id: string;
  246. name: string;
  247. color: string;
  248. count: number;
  249. }
  250. interface StoryboardSegment {
  251. id: string;
  252. act: string;
  253. narration: string;
  254. prompt: string;
  255. duration: string;
  256. videoUrl?: string;
  257. workId?: string;
  258. status: 'pending' | 'generating' | 'completed' | 'failed';
  259. error?: string;
  260. }
  261. interface RemixFlowStep {
  262. step: number;
  263. label: string;
  264. }
  265. interface MonitorWork {
  266. id: string;
  267. desc: string;
  268. coverUrl: string;
  269. coverCandidates: string[];
  270. duration: number;
  271. createTime?: Date;
  272. type: 'video' | 'image';
  273. statistics: {
  274. play_count: number;
  275. digg_count: number;
  276. comment_count: number;
  277. share_count: number;
  278. };
  279. isDownloading?: boolean;
  280. downloadProgress?: number;
  281. }
  282. interface MonitorAuthor {
  283. id: string;
  284. uid: string;
  285. secUserId: string;
  286. nickname: string;
  287. uniqueId: string;
  288. shortId: string;
  289. signature: string;
  290. ipLocation: string;
  291. verifiedText: string;
  292. avatarUrl: string;
  293. avatarCandidates: string[];
  294. coverUrl: string;
  295. coverCandidates: string[];
  296. followerCount: number;
  297. followingCount: number;
  298. totalFavorited: number;
  299. awemeCount: number;
  300. works: MonitorWork[];
  301. worksCursor: string;
  302. hasMoreWorks: boolean;
  303. loadingWorks: boolean;
  304. }
  305. @Component({
  306. selector: 'app-root',
  307. imports: [
  308. CommonModule,
  309. FormsModule,
  310. RouterModule,
  311. TimeFormatPipe,
  312. NumberFormatPipe,
  313. FileSizePipe,
  314. DigitalHumanFormComponent,
  315. PortraitPrepareComponent,
  316. ImageToVideoComponent,
  317. ActionTransferComponent,
  318. AssetRemixComponent,
  319. TopicToVideoComponent,
  320. AppSidebarComponent,
  321. HomeComponent,
  322. RecentTaskPillComponent,
  323. AppAssistantComponent,
  324. VoicePickerComponent
  325. ],
  326. templateUrl: './app.html',
  327. styleUrl: './app.css',
  328. // 关键:app.css 包含全局 dh-* / pl-* / pipeline-* 等设计系统类,
  329. // 必须设为 None 才能让其作用到 standalone 子组件(图生视频/动作迁移/
  330. // 素材合成/主题生视频)。否则 Angular 默认 Emulated 会给所有选择器
  331. // 添加 [_ngcontent-xxx] 属性后缀,导致子组件 DOM 无法匹配,UI 失样。
  332. encapsulation: ViewEncapsulation.None
  333. })
  334. export class App {
  335. protected readonly title = signal('抖音AI视频生成系统');
  336. // 当前激活的标签页
  337. currentTab: 'home' | 'search' | 'monitor' | 'tasks' | 'history' | 'results' | 'videos' | 'voice-synthesis' | 'pipelines' | 'digital-human' | 'video-generation' | 'image-to-video' | 'action-transfer' | 'asset-remix' | 'topic-to-video' = 'home';
  338. /** Pipeline 注册中心数据,模板中通过 *ngFor 动态渲染 */
  339. readonly pipelines = PIPELINES;
  340. readonly sidebarPipelines = getSidebarPipelines();
  341. private readonly TAB_STORAGE_KEY = 'tiktok.currentTab';
  342. // 主题模式(默认浅色)
  343. themeMode: 'day' | 'night' = 'day';
  344. private readonly THEME_STORAGE_KEY = 'tiktok.themeMode';
  345. private readonly TIMBRE_LIST_STORAGE_KEY = 'tiktok.vsClonedTimbreList';
  346. private readonly MONITOR_AUTHORS_STORAGE_KEY = 'tiktok.monitorAuthors';
  347. private readonly MONITOR_SELECTED_AUTHOR_STORAGE_KEY = 'tiktok.monitorSelectedAuthorId';
  348. // 搜索相关属性
  349. searchKeyword: string = '';
  350. sortType: string = '0';
  351. publishTime: string = '0';
  352. filterDuration: string = '0';
  353. isSearching: boolean = false;
  354. searchResults: VideoInfo[] = [];
  355. filteredSearchResults: VideoInfo[] = [];
  356. hasMore: boolean = false;
  357. monitorUniqueIdInput: string = '';
  358. monitorAuthors: MonitorAuthor[] = [];
  359. selectedMonitorAuthorId: string = '';
  360. isAddingMonitorAuthor: boolean = false;
  361. monitorAddError: string = '';
  362. private readonly voiceApiToken: string = 'Bearer r:f0333969e312a40e4703e8fe4ed1c600';
  363. private readonly voiceTtsBaseUrl: string = 'https://server.fmode.cn/api/volcengine/tts';
  364. private readonly localVoiceTtsBaseUrl: string = '/backend/api/volcengine/tts';
  365. voiceProfiles: VoiceProfile[] = [];
  366. isCreatingVoiceProfile: boolean = false;
  367. voiceDesignError: string = '';
  368. voiceCreateMode: 'clone' | 'design' | 'synthesize' = 'clone';
  369. voiceSourceAudioFile: File | null = null;
  370. voiceSourceAudioName: string = '';
  371. voiceDesignImageFile: File | null = null;
  372. voiceDesignImageName: string = '';
  373. preferredVoiceProfileId: string = '';
  374. readonly fallbackVoiceSpeakerIdOptions = ['S_1g3vlU702', 'S_OLZKhZWZ1', 'S_PLZKhZWZ1', 'S_QLZKhZWZ1', 'S_ULZKhZWZ1', 'S_TLZKhZWZ1', 'S_SLZKhZWZ1', 'S_RWDjSzXZ1'];
  375. voiceSpeakerIdOptions: string[] = [...this.fallbackVoiceSpeakerIdOptions];
  376. voiceForm = {
  377. displayName: '',
  378. speakerId: 'S_1g3vlU702',
  379. textPrompt: '',
  380. audioText: '',
  381. sampleText: '',
  382. synthesisText: '',
  383. language: 0
  384. };
  385. voiceSynthesisForm = {
  386. profileId: '',
  387. speakerId: '',
  388. text: '',
  389. ssml: '',
  390. xApiResourceId: '',
  391. model: '',
  392. format: 'mp3',
  393. sampleRate: 24000,
  394. speechRate: 0,
  395. loudnessRate: 0,
  396. emotion: '',
  397. emotionScale: 4,
  398. enableSubtitle: false,
  399. silenceDuration: 0,
  400. enableLanguageDetector: false,
  401. disableMarkdownFilter: false,
  402. disableEmojiFilter: false,
  403. explicitLanguage: ''
  404. };
  405. isDirectVoiceSynthesizing: boolean = false;
  406. directVoiceSynthesisAudioUrl: string = '';
  407. directVoiceSynthesisWorkId: string = '';
  408. directVoiceSynthesisSpeakerId: string = '';
  409. // 语音合成标签页状态
  410. vsTtsMode: 'clone' | 'synthesize' = 'clone';
  411. vsCloneForm = {
  412. name: '',
  413. speakerId: 'S_ULZKhZWZ1',
  414. audioText: '',
  415. language: 0,
  416. demoText: '青山依旧在,几度夕阳红。'
  417. };
  418. vsCloneAudioFile: File | null = null;
  419. vsCloneAudioName: string = '';
  420. vsCloneAudioUrl: string = '';
  421. vsCloneUploading: boolean = false;
  422. vsCloneLoading: boolean = false;
  423. vsCloneError: string = '';
  424. vsCloneResult: any = null;
  425. vsSynthForm = {
  426. timbreId: '',
  427. text: '白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢,古今多少事,都付笑谈中。',
  428. isStream: false,
  429. format: 'mp3',
  430. sampleRate: 24000,
  431. speechRate: 0,
  432. loudnessRate: 0,
  433. /** 当前选中音色来源:'cloned' = 用户复刻;'official' = 官方音色库 */
  434. voiceSource: 'cloned' as 'cloned' | 'official',
  435. /** 仅 voiceSource='official' 时使用,对应火山 voice_type */
  436. voiceType: '',
  437. /** 当前选中音色的显示名(UI 用) */
  438. voiceName: ''
  439. };
  440. /** 音色选择弹窗开关 */
  441. voicePickerOpen: boolean = false;
  442. /** 传给弹窗用于回显高亮的当前选择 */
  443. get currentVoiceSelection(): VoiceSelection | null {
  444. const f = this.vsSynthForm;
  445. if (f.voiceSource === 'official' && f.voiceType) {
  446. return { source: 'official', name: f.voiceName, id: f.voiceType, voiceType: f.voiceType };
  447. }
  448. if (f.voiceSource === 'cloned' && f.timbreId) {
  449. return { source: 'cloned', name: f.voiceName || f.timbreId, id: f.timbreId, timbreId: f.timbreId };
  450. }
  451. return null;
  452. }
  453. openVoicePicker(): void {
  454. this.voicePickerOpen = true;
  455. }
  456. closeVoicePicker(): void {
  457. this.voicePickerOpen = false;
  458. }
  459. onVoicePicked(sel: VoiceSelection): void {
  460. this.vsSynthForm.voiceSource = sel.source;
  461. this.vsSynthForm.voiceName = sel.name;
  462. if (sel.source === 'official') {
  463. this.vsSynthForm.voiceType = sel.voiceType || sel.id;
  464. this.vsSynthForm.timbreId = '';
  465. } else {
  466. this.vsSynthForm.timbreId = sel.timbreId || sel.id;
  467. this.vsSynthForm.voiceType = '';
  468. }
  469. this.vsSynthError = '';
  470. this.voicePickerOpen = false;
  471. this.refreshView();
  472. }
  473. vsSynthLoading: boolean = false;
  474. vsSynthError: string = '';
  475. vsSynthAudioUrl: string = '';
  476. vsSynthWorkId: string = '';
  477. vsClonedTimbreList: { objectId: string; name: string; speakerId: string }[] = [];
  478. // 数字人合成独立页面状态
  479. dhStep: 'form' | 'generating' | 'done' = 'form';
  480. dhImageFile: File | null = null;
  481. dhImageName: string = '';
  482. dhImagePreviewUrl: string = '';
  483. dhImageAssetUrl: string = '';
  484. dhAudioSource: 'tts' | 'upload' = 'tts';
  485. dhTtsTimbreId: string = '';
  486. dhTtsText: string = '';
  487. dhUploadAudioFile: File | null = null;
  488. dhUploadAudioName: string = '';
  489. dhUploadAudioUrl: string = '';
  490. dhUploadingAudio: boolean = false;
  491. dhPrompt: string = '';
  492. // dh tab:形象准备产物(来自 <app-portrait-prepare>),存在时优先于原图
  493. dhPreparedPortraitUrl: string = '';
  494. dhPreparedFullBodyUrl: string = '';
  495. dhPreparedBenchmarkSummary: string = '';
  496. // 数字人补充提示词预设
  497. dhPromptPresets: { label: string; value: string }[] = [
  498. { label: '专业播报', value: '以新闻主播的语气朗读,吐字清晰、节奏稳定、表情自信端正。' },
  499. { label: '亲切自然', value: '用朋友聊天的语气,亲切自然、面带微笑,语速适中略带轻松感。' },
  500. { label: '科技感', value: '冷静理性的科技感口吻,节奏明快、抑扬有度,强调数据与关键词。' },
  501. { label: '热情带货', value: '充满活力的带货主播风格,语速略快、情绪饱满,重点处加重音强调。' },
  502. { label: '温柔治愈', value: '温柔轻缓的语气,气息柔和、节奏放慢,适合情感与生活类内容。' },
  503. { label: '正式商务', value: '商务正式风格,语调克制、用词严谨,仪态端庄,适合企业宣传场景。' },
  504. ];
  505. dhFastMode: boolean = false;
  506. dhResolution: '720p' | '1080p' = '1080p';
  507. dhError: string = '';
  508. dhLoading: boolean = false;
  509. dhStatusText: string = '';
  510. dhProgress: number = 0;
  511. dhResultVideoUrl: string = '';
  512. dhSynthesizing: boolean = false;
  513. // 数字人合成页:AI 对话助手(用于让用户与 AI 对话调整口播稿风格 / 优化提示词)
  514. dhChatMessages: Array<{
  515. role: 'user' | 'assistant';
  516. content: string; // 给用户看的文本(assistant 端为 explanation;user 端为输入原文)
  517. suggestedTts?: string; // assistant 建议的新口播文本
  518. suggestedPrompt?: string; // assistant 建议的新补充提示词
  519. appliedTts?: boolean;
  520. appliedPrompt?: boolean;
  521. }> = [];
  522. dhChatInput: string = '';
  523. dhChatLoading: boolean = false;
  524. dhChatError: string = '';
  525. // 任务管理相关属性
  526. activeTasks: Task[] = [];
  527. taskStats: TaskStats = {
  528. pending: 0,
  529. processing: 0,
  530. completed: 0,
  531. failed: 0
  532. };
  533. // 历史记录相关属性
  534. historyRecords: HistoryRecord[] = [];
  535. historyFilter = {
  536. status: ''
  537. };
  538. // 生成结果相关属性
  539. generatedResults: GeneratedResult[] = [];
  540. // 视频管理相关属性
  541. managedVideos: ManagedVideo[] = [];
  542. videoCategories: VideoCategory[] = [];
  543. selectedVideos: Set<string> = new Set();
  544. videoFilter = {
  545. category: '',
  546. source: '',
  547. searchTerm: ''
  548. };
  549. isSelectionMode: boolean = false;
  550. // 视频上传
  551. showUploadModal: boolean = false;
  552. uploadTitle: string = '';
  553. uploadDescription: string = '';
  554. uploadTags: string = '';
  555. isUploading: boolean = false;
  556. uploadProgress: number = 0;
  557. uploadError: string = '';
  558. uploadFile: File | null = null;
  559. uploadFileName: string = '';
  560. // 视频预览模态框
  561. showPreviewModal: boolean = false;
  562. previewVideoUrl: string = '';
  563. previewDownloadUrl: string = '';
  564. previewVideoTitle: string = '';
  565. previewVideoInfo: any = null;
  566. previewSourceVideo: VideoInfo | null = null;
  567. // 搜索游标(分页)
  568. searchCursor: number = 0;
  569. private searchId: string = '';
  570. private searchBacktrace: string = '';
  571. // 视频文件基础路径
  572. private readonly VIDEO_BASE_PATH = '/video';
  573. // AI重塑模式选择弹窗(视频管理页 → 选择 标准AI重塑 / 数字人生成)
  574. showRemixModeChooser: boolean = false;
  575. remixModeChooserVideo: ManagedVideo | null = null;
  576. // ===== 数字人合成页:参考视频(与视频生成页 vg* 完全隔离的独立状态) =====
  577. dhRefFile: File | null = null;
  578. dhRefFileName: string = '';
  579. dhRefFileSize: number = 0;
  580. dhRefVideoUrl: string = '';
  581. dhRefVideoId: string = '';
  582. dhRefUploading: boolean = false;
  583. dhRefUploadProgress: number = 0;
  584. dhRefAnalyzing: boolean = false;
  585. dhRefAnalysisText: string = '';
  586. dhRefTranscript: string = '';
  587. dhRefError: string = '';
  588. dhRefRewriting: boolean = false;
  589. dhRefRewriteError: string = '';
  590. // 当通过「AI 重塑 → 数字人生成」入口进入时,标记需要在分析完成后自动重塑
  591. dhRefAutoRewrite: boolean = false;
  592. // AI重塑模态框 — 多步骤流程
  593. showRemixModal: boolean = false;
  594. remixTargetVideo: ManagedVideo | null = null;
  595. remixStep: number = 1; // 1提取文字稿 2AI美化 3分镜脚本 4生成参数 5生成中 6结果
  596. remixTranscript: string = '';
  597. remixBeautifiedTranscript: string = '';
  598. remixStoryboard: StoryboardSegment[] = [];
  599. remixStyle: string = 'anime';
  600. remixQuality: '720p' | '1080p' | 'pro' = '1080p';
  601. remixFrames: number = 121;
  602. remixAspectRatio: '16:9' | '4:3' | '1:1' | '3:4' | '9:16' | '21:9' = '16:9';
  603. remixStatusText: string = '';
  604. isRemixSubmitting: boolean = false;
  605. remixResults: { total: number; success: number; failed: number } = { total: 0, success: 0, failed: 0 };
  606. remixStitchStatus: 'idle' | 'stitching' | 'polling' | 'done' | 'failed' = 'idle';
  607. remixStitchUrl: string = '';
  608. remixStitchError: string = '';
  609. remixFinalVideoUrl: string = '';
  610. remixMode: 'standard' | 'digital-human' = 'standard';
  611. remixDigitalHumanImageFile: File | null = null;
  612. remixDigitalHumanImageName: string = '';
  613. remixDigitalHumanImagePreviewUrl: string = '';
  614. remixDigitalHumanImageAssetUrl: string = '';
  615. remixDigitalHumanPrompt: string = '';
  616. remixDigitalHumanFastMode: boolean = false;
  617. remixDigitalHumanResolution: '720p' | '1080p' = '1080p';
  618. remixDigitalHumanError: string = '';
  619. remixDigitalHumanAudioSource: 'original' | 'tts' = 'tts';
  620. remixDigitalHumanTtsText: string = '';
  621. remixDigitalHumanTtsTimbreId: string = '';
  622. remixDigitalHumanTtsSynthesizing: boolean = false;
  623. // ===== 数字人形象准备(自拍优化 / 对标重塑)=====
  624. // raw=直接使用原图;normalize=AI 提取正面全身图;benchmark=对标账号重塑
  625. remixPortraitPrepareMode: 'raw' | 'normalize' | 'benchmark' = 'raw';
  626. remixBenchmarkImageFile: File | null = null;
  627. remixBenchmarkImageName: string = '';
  628. remixBenchmarkImagePreviewUrl: string = '';
  629. remixPortraitPipelineRunning: boolean = false;
  630. remixPortraitPipelineStatus: string = '';
  631. remixPortraitPipelineProgress: number = 0;
  632. remixPortraitPipelineError: string = '';
  633. // pipeline 输出,若存在则数字人生成会优先使用
  634. remixGeneratedPortraitUrl: string = '';
  635. remixGeneratedFullBodyUrl: string = '';
  636. remixGeneratedBenchmarkSummary: string = '';
  637. // ===== 视频生成工作流 =====
  638. vgStep: number = 1; // 1上传视频 2视频解析 3脚本生成 4配图生成 5配音 6数字人生成
  639. readonly vgStepLabels = ['上传视频', '视频解析', '脚本生成', '配图生成', '语音配音', '视频合成'];
  640. readonly vgStepSubtitles = [
  641. '选择需要拆解分析的视频源文件',
  642. 'AI 自动转录与内容理解',
  643. 'AI 生成分镜旁白与画面提示词',
  644. '为每个分镜生成 AI 配图',
  645. '逐段合成旁白音频',
  646. '汇总素材并合成最终视频'
  647. ];
  648. // 用户手动展开的「已完成」步骤集合(active 步骤始终展开,locked 步骤始终折叠)
  649. vgUserExpandedSteps: Set<number> = new Set<number>();
  650. vgSourceFile: File | null = null;
  651. vgSourceFileName: string = '';
  652. vgSourceVideoUrl: string = '';
  653. vgUploading: boolean = false;
  654. vgUploadProgress: number = 0;
  655. vgVideoId: string = '';
  656. // Step 2: 视频解析
  657. vgAnalyzing: boolean = false;
  658. vgAnalysisText: string = '';
  659. vgTranscript: string = '';
  660. // Step 3: 脚本生成
  661. vgGeneratingScript: boolean = false;
  662. vgScript: string = '';
  663. vgScriptSegments: { id: string; narration: string; imagePrompt: string; imagePromptCn?: string; }[] = [];
  664. // Step 4: 配图生成
  665. vgGeneratingImages: boolean = false;
  666. vgImageResults: { id: string; prompt: string; imageUrl: string; status: 'pending' | 'generating' | 'done' | 'failed'; }[] = [];
  667. vgImageProgress: number = 0;
  668. // Step 5: 语音配音
  669. vgVoiceMode: 'clone' | 'system' = 'system';
  670. vgVoiceTimbreId: string = '';
  671. vgVoiceSpeakerId: string = 'zh_female_shuangkuai-am_16k';
  672. vgSynthesizing: boolean = false;
  673. vgAudioUrls: { segId: string; audioUrl: string; }[] = [];
  674. // Step 6: 视频合成
  675. vgCompositing: boolean = false;
  676. vgCompositingProgress: number = 0;
  677. vgFinalVideoUrl: string = '';
  678. vgError: string = '';
  679. vgTaskId: string = ''; // 关联任务管理中的任务ID
  680. // Whisper 文字稿生成
  681. isWhisperRunning: boolean = false;
  682. whisperStatusText: string = '';
  683. showManualTranscriptInput: boolean = false;
  684. // 当前 AI 重塑关联的任务
  685. currentRemixTaskId: string = '';
  686. currentRemixId: string = ''; // 当前重塑会话ID
  687. private taskSaveReady: Promise<void> = Promise.resolve();
  688. // 历史详情模态框
  689. showHistoryDetailModal: boolean = false;
  690. historyDetailRecord: HistoryRecord | null = null;
  691. historyDetailSegments: { id: string; videoUrl: string; prompt: string; status: string; narration?: string }[] = [];
  692. historyDetailPrimaryVideoUrl: string = '';
  693. historyDetailLoading: boolean = false;
  694. // Toast 通知
  695. toastMessage: string = '';
  696. toastType: 'success' | 'info' | 'warn' | 'error' = 'info';
  697. toastVisible: boolean = false;
  698. private toastTimer: any = null;
  699. readonly remixStepLabels = ['提取文字稿', 'AI美化', '分镜脚本', '生成参数', '视频生成', '结果汇总'];
  700. readonly digitalHumanStepLabels = ['模式选择', '生成参数', '视频生成', '结果汇总'];
  701. // 重塑风格选项
  702. readonly remixStyleOptions = [
  703. { id: 'anime', name: '动漫风格', prompt: 'anime style, Japanese animation, vibrant colors, cel shading' },
  704. { id: 'oil-painting', name: '油画风格', prompt: 'oil painting style, thick brushstrokes, rich textures, classical art' },
  705. { id: 'watercolor', name: '水彩风格', prompt: 'watercolor painting style, soft colors, fluid brushwork, artistic' },
  706. { id: 'cyberpunk', name: '赛博朋克', prompt: 'cyberpunk style, neon lights, futuristic city, high tech low life, dark atmosphere' },
  707. { id: 'cinematic', name: '电影质感', prompt: 'cinematic style, dramatic lighting, shallow depth of field, movie grade color grading' },
  708. { id: '3d-render', name: '3D渲染', prompt: '3D rendered style, realistic materials, ray tracing, studio lighting' },
  709. { id: 'ink-wash', name: '水墨风格', prompt: 'Chinese ink wash painting style, minimalist, elegant brushwork, traditional art' },
  710. { id: 'vintage', name: '复古风格', prompt: 'vintage retro style, film grain, warm tones, nostalgic atmosphere, 1970s aesthetic' }
  711. ];
  712. constructor(private douyinService: DouyinService, private jimengService: JimengService, private llmService: LlmService, private portraitPipeline: PortraitPipelineService, private digitalHumanService: DigitalHumanService, private http: HttpClient, private ngZone: NgZone, private cdr: ChangeDetectorRef) {
  713. this.initializeDefaults();
  714. this.restoreTheme();
  715. this.restoreCurrentTab();
  716. this.restoreClonedTimbreList();
  717. this.restorePersistedMonitorState();
  718. this.refreshIncompleteMonitorAuthors();
  719. this.loadVideoManifest();
  720. this.loadPersistedData();
  721. }
  722. // 初始化默认值(非持久化数据)
  723. private initializeDefaults(): void {
  724. this.searchResults = [];
  725. this.filteredSearchResults = [];
  726. this.monitorUniqueIdInput = '';
  727. this.monitorAuthors = [];
  728. this.selectedMonitorAuthorId = '';
  729. this.monitorAddError = '';
  730. this.voiceProfiles = [];
  731. this.voiceDesignError = '';
  732. this.voiceCreateMode = 'clone';
  733. this.voiceSourceAudioFile = null;
  734. this.voiceSourceAudioName = '';
  735. this.voiceDesignImageFile = null;
  736. this.voiceDesignImageName = '';
  737. this.voiceSpeakerIdOptions = [...this.fallbackVoiceSpeakerIdOptions];
  738. this.voiceForm = this.buildDefaultVoiceForm();
  739. this.voiceSynthesisForm = this.buildDefaultVoiceSynthesisForm();
  740. this.taskStats = { pending: 0, processing: 0, completed: 0, failed: 0 };
  741. // 视频分类
  742. this.videoCategories = [
  743. { id: 'downloaded', name: '已下载', color: '#2196F3', count: 0 },
  744. { id: 'generated', name: 'AI生成', color: '#4CAF50', count: 0 },
  745. { id: 'uploaded', name: '已上传', color: '#FF9800', count: 0 }
  746. ];
  747. this.managedVideos = [];
  748. }
  749. private buildDefaultVoiceForm(): typeof this.voiceForm {
  750. return {
  751. displayName: '',
  752. speakerId: this.voiceSpeakerIdOptions[0] || this.fallbackVoiceSpeakerIdOptions[0] || '',
  753. textPrompt: '',
  754. audioText: '',
  755. sampleText: '',
  756. synthesisText: '',
  757. language: 0
  758. };
  759. }
  760. private buildDefaultVoiceSynthesisForm(profileId = ''): typeof this.voiceSynthesisForm {
  761. return {
  762. profileId,
  763. speakerId: '',
  764. text: '',
  765. ssml: '',
  766. xApiResourceId: '',
  767. model: '',
  768. format: 'mp3',
  769. sampleRate: 24000,
  770. speechRate: 0,
  771. loudnessRate: 0,
  772. emotion: '',
  773. emotionScale: 4,
  774. enableSubtitle: false,
  775. silenceDuration: 0,
  776. enableLanguageDetector: false,
  777. disableMarkdownFilter: false,
  778. disableEmojiFilter: false,
  779. explicitLanguage: ''
  780. };
  781. }
  782. private buildVoiceSynthesisFormFromProfile(profile: VoiceProfile | null | undefined): typeof this.voiceSynthesisForm {
  783. if (!profile) {
  784. return this.buildDefaultVoiceSynthesisForm();
  785. }
  786. return {
  787. profileId: profile.id,
  788. speakerId: String(profile.icl_speaker_id || profile.speaker_id || ''),
  789. text: String(profile.draft_synthesis_text || profile.last_synthesis_text || ''),
  790. ssml: String(profile.draft_synthesis_ssml || ''),
  791. xApiResourceId: String(profile.draft_synthesis_x_api_resource_id || profile.x_api_resource_id || ''),
  792. model: String(profile.draft_synthesis_model || ''),
  793. format: this.normalizeVoiceSynthesisFormat(profile.draft_synthesis_format),
  794. sampleRate: this.normalizeVoiceSynthesisSampleRate(profile.draft_synthesis_sample_rate),
  795. speechRate: this.clampVoiceSynthesisRate(profile.draft_synthesis_speech_rate, 0),
  796. loudnessRate: this.clampVoiceSynthesisRate(profile.draft_synthesis_loudness_rate, 0),
  797. emotion: String(profile.draft_synthesis_emotion || ''),
  798. emotionScale: this.clampVoiceSynthesisEmotionScale(profile.draft_synthesis_emotion_scale, 4),
  799. enableSubtitle: !!profile.draft_synthesis_enable_subtitle,
  800. silenceDuration: this.clampVoiceSynthesisSilenceDuration(profile.draft_synthesis_silence_duration, 0),
  801. enableLanguageDetector: !!profile.draft_synthesis_enable_language_detector,
  802. disableMarkdownFilter: !!profile.draft_synthesis_disable_markdown_filter,
  803. disableEmojiFilter: !!profile.draft_synthesis_disable_emoji_filter,
  804. explicitLanguage: String(profile.draft_synthesis_explicit_language || '')
  805. };
  806. }
  807. private syncVoiceSynthesisFormSelection(): void {
  808. const availableProfiles = this.getSynthesisVoiceProfiles();
  809. const selectedProfile = availableProfiles.find((profile) => profile.id === this.voiceSynthesisForm.profileId) || null;
  810. if (selectedProfile) {
  811. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(selectedProfile);
  812. return;
  813. }
  814. if (String(this.voiceSynthesisForm.speakerId || '').trim()) {
  815. this.voiceSynthesisForm = {
  816. ...this.voiceSynthesisForm,
  817. profileId: ''
  818. };
  819. return;
  820. }
  821. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(availableProfiles[0] || null);
  822. }
  823. private normalizeVoiceSynthesisFormat(value: any): string {
  824. const format = String(value || '').trim().toLowerCase();
  825. return ['mp3', 'ogg_opus', 'pcm'].includes(format) ? format : 'mp3';
  826. }
  827. private normalizeVoiceSynthesisSampleRate(value: any): number {
  828. const sampleRate = Number(value);
  829. return [8000, 16000, 22050, 24000, 32000, 44100, 48000].includes(sampleRate) ? sampleRate : 24000;
  830. }
  831. private clampVoiceSynthesisRate(value: any, fallback = 0): number {
  832. const numericValue = Number(value);
  833. if (!Number.isFinite(numericValue)) {
  834. return fallback;
  835. }
  836. return Math.min(100, Math.max(-50, numericValue));
  837. }
  838. private clampVoiceSynthesisEmotionScale(value: any, fallback = 4): number {
  839. const numericValue = Number(value);
  840. if (!Number.isFinite(numericValue)) {
  841. return fallback;
  842. }
  843. return Math.min(5, Math.max(1, Math.round(numericValue)));
  844. }
  845. private clampVoiceSynthesisSilenceDuration(value: any, fallback = 0): number {
  846. const numericValue = Number(value);
  847. if (!Number.isFinite(numericValue)) {
  848. return fallback;
  849. }
  850. return Math.min(30000, Math.max(0, Math.round(numericValue)));
  851. }
  852. private inferVoiceSourceAudioFormat(file: File): string {
  853. const mimeType = String(file?.type || '').toLowerCase();
  854. const fileName = String(file?.name || '').toLowerCase();
  855. if (mimeType.includes('wav') || fileName.endsWith('.wav')) {
  856. return 'wav';
  857. }
  858. if (mimeType.includes('m4a') || mimeType.includes('mp4') || fileName.endsWith('.m4a')) {
  859. return 'm4a';
  860. }
  861. if (mimeType.includes('aac') || fileName.endsWith('.aac')) {
  862. return 'aac';
  863. }
  864. if (mimeType.includes('flac') || fileName.endsWith('.flac')) {
  865. return 'flac';
  866. }
  867. if (mimeType.includes('opus') || fileName.endsWith('.opus')) {
  868. return 'opus';
  869. }
  870. if (mimeType.includes('ogg') || fileName.endsWith('.ogg')) {
  871. return 'ogg';
  872. }
  873. if (mimeType.includes('pcm') || fileName.endsWith('.pcm')) {
  874. return 'pcm';
  875. }
  876. return 'mp3';
  877. }
  878. private readFileAsBase64(file: File): Promise<string> {
  879. return new Promise((resolve, reject) => {
  880. const reader = new FileReader();
  881. reader.onload = () => {
  882. const result = String(reader.result || '');
  883. const base64 = result.includes(',') ? result.split(',').pop() || '' : result;
  884. if (!base64) {
  885. reject(new Error('音频文件读取失败'));
  886. return;
  887. }
  888. resolve(base64);
  889. };
  890. reader.onerror = () => reject(reader.error || new Error('音频文件读取失败'));
  891. reader.readAsDataURL(file);
  892. });
  893. }
  894. private buildVoiceSynthesisDraft(profile: any): Partial<VoiceProfile> {
  895. return {
  896. draft_synthesis_text: String(profile?.last_synthesis_text || ''),
  897. draft_synthesis_ssml: String(profile?.last_synthesis_ssml || ''),
  898. draft_synthesis_x_api_resource_id: String(profile?.last_synthesis_x_api_resource_id || profile?.x_api_resource_id || ''),
  899. draft_synthesis_model: String(profile?.last_synthesis_model || ''),
  900. draft_synthesis_format: this.normalizeVoiceSynthesisFormat(profile?.last_synthesis_format),
  901. draft_synthesis_sample_rate: this.normalizeVoiceSynthesisSampleRate(profile?.last_synthesis_sample_rate),
  902. draft_synthesis_speech_rate: this.clampVoiceSynthesisRate(profile?.last_synthesis_speech_rate, 0),
  903. draft_synthesis_loudness_rate: this.clampVoiceSynthesisRate(profile?.last_synthesis_loudness_rate, 0),
  904. draft_synthesis_emotion: String(profile?.last_synthesis_emotion || ''),
  905. draft_synthesis_emotion_scale: this.clampVoiceSynthesisEmotionScale(profile?.last_synthesis_emotion_scale, 4),
  906. draft_synthesis_enable_subtitle: !!profile?.last_synthesis_enable_subtitle,
  907. draft_synthesis_silence_duration: this.clampVoiceSynthesisSilenceDuration(profile?.last_synthesis_silence_duration, 0),
  908. draft_synthesis_enable_language_detector: !!profile?.last_synthesis_enable_language_detector,
  909. draft_synthesis_disable_markdown_filter: !!profile?.last_synthesis_disable_markdown_filter,
  910. draft_synthesis_disable_emoji_filter: !!profile?.last_synthesis_disable_emoji_filter,
  911. draft_synthesis_explicit_language: String(profile?.last_synthesis_explicit_language || '')
  912. };
  913. }
  914. private restoreCurrentTab(): void {
  915. try {
  916. const savedTab = localStorage.getItem(this.TAB_STORAGE_KEY);
  917. const allowed = ['home','search','monitor','tasks','history','results','videos','voice-synthesis','pipelines','digital-human','video-generation','image-to-video','action-transfer','asset-remix','topic-to-video'];
  918. if (savedTab && allowed.includes(savedTab)) {
  919. this.currentTab = savedTab as any;
  920. }
  921. } catch {}
  922. }
  923. private restoreTheme(): void {
  924. try {
  925. const saved = localStorage.getItem(this.THEME_STORAGE_KEY);
  926. if (saved === 'day' || saved === 'night') {
  927. this.themeMode = saved;
  928. }
  929. } catch {}
  930. }
  931. toggleTheme(): void {
  932. this.themeMode = this.themeMode === 'day' ? 'night' : 'day';
  933. try {
  934. localStorage.setItem(this.THEME_STORAGE_KEY, this.themeMode);
  935. } catch {}
  936. }
  937. private restoreClonedTimbreList(): void {
  938. try {
  939. const saved = localStorage.getItem(this.TIMBRE_LIST_STORAGE_KEY);
  940. if (saved) {
  941. const parsed = JSON.parse(saved);
  942. if (Array.isArray(parsed)) {
  943. this.vsClonedTimbreList = parsed.filter(
  944. (t: any) => t && typeof t.objectId === 'string' && t.objectId
  945. );
  946. }
  947. }
  948. } catch {}
  949. }
  950. private saveClonedTimbreList(): void {
  951. try {
  952. localStorage.setItem(this.TIMBRE_LIST_STORAGE_KEY, JSON.stringify(this.vsClonedTimbreList));
  953. } catch {}
  954. }
  955. setCurrentTab(tab: 'home' | 'search' | 'monitor' | 'tasks' | 'history' | 'results' | 'videos' | 'voice-synthesis' | 'pipelines' | 'digital-human' | 'video-generation' | 'image-to-video' | 'action-transfer' | 'asset-remix' | 'topic-to-video'): void {
  956. this.currentTab = tab;
  957. try {
  958. localStorage.setItem(this.TAB_STORAGE_KEY, tab);
  959. } catch {}
  960. }
  961. /** 右下浮动 mini-pill:当前正在跑的任务(取 activeTasks 中第一个 processing/pending) */
  962. get currentRunningTask(): RecentTaskView | null {
  963. const running = (this.activeTasks || []).find(
  964. (t) => t && (t.status === 'processing' || t.status === 'pending'),
  965. );
  966. if (!running) return null;
  967. return {
  968. id: running.id,
  969. keyword: running.keyword,
  970. status: running.status,
  971. step: running.step,
  972. progress: Math.max(0, Math.min(100, running.progress ?? 0)),
  973. type: running.type,
  974. };
  975. }
  976. /** assistant 浮窗是否展开(由组件回传);展开时 pill 让位到面板上方 */
  977. assistantExpanded = false;
  978. /** 首屏内联对话页激活(由 app-home 通过 inlineChatChange 输出):pill / FAB 都隐藏 */
  979. homeChatActive = false;
  980. /**
  981. * pill 隐藏条件:
  982. * 1. 已经在 tasks 页 —— 重复
  983. * 2. 浮窗展开 —— 被遮挡
  984. * 3. 首屏全宽对话页激活 —— 主区已是对话
  985. */
  986. get pillHidden(): boolean {
  987. return this.currentTab === 'tasks' || this.assistantExpanded || this.homeChatActive;
  988. }
  989. /** 助手内回复中的「直达 X 模式」按钮被点击 */
  990. onAssistantSuggestion(s: AssistantSuggestion): void {
  991. if (!s?.tab) return;
  992. // 复用首屏跳转通道:含 payload 时同样走 sessionStorage 预填
  993. this.onHomeNavigate({ tab: s.tab, payload: s.payload });
  994. }
  995. /** 首屏组件输出:可能带 payload(如预填的主题) */
  996. onHomeNavigate(ev: { tab: string; payload?: any }): void {
  997. this.setCurrentTab(ev.tab as any);
  998. // 主题预填:暂存到 sessionStorage,topic-to-video 组件初始化时自取
  999. if (ev.payload?.topic && ev.tab === 'topic-to-video') {
  1000. try {
  1001. sessionStorage.setItem('t2v.prefillTopic', ev.payload.topic);
  1002. } catch {}
  1003. }
  1004. }
  1005. private restorePersistedMonitorState(): void {
  1006. try {
  1007. const savedAuthors = localStorage.getItem(this.MONITOR_AUTHORS_STORAGE_KEY);
  1008. const savedSelectedAuthorStorageKey = localStorage.getItem(this.MONITOR_SELECTED_AUTHOR_STORAGE_KEY) || '';
  1009. if (savedAuthors) {
  1010. const parsedAuthors = JSON.parse(savedAuthors);
  1011. if (Array.isArray(parsedAuthors)) {
  1012. this.monitorAuthors = parsedAuthors.map((author: any) => this.deserializeMonitorAuthor(author));
  1013. }
  1014. }
  1015. this.selectedMonitorAuthorId = this.monitorAuthors.some(author => author.id === savedSelectedAuthorStorageKey)
  1016. ? savedSelectedAuthorStorageKey
  1017. : '';
  1018. } catch {
  1019. this.monitorAuthors = [];
  1020. this.selectedMonitorAuthorId = '';
  1021. }
  1022. }
  1023. private persistMonitorState(): void {
  1024. try {
  1025. localStorage.setItem(this.MONITOR_AUTHORS_STORAGE_KEY, JSON.stringify(this.monitorAuthors.map(author => this.serializeMonitorAuthor(author))));
  1026. localStorage.setItem(this.MONITOR_SELECTED_AUTHOR_STORAGE_KEY, this.selectedMonitorAuthorId || '');
  1027. } catch {}
  1028. }
  1029. // 从后端加载持久化数据(任务、历史、结果)
  1030. private loadPersistedData(): void {
  1031. // 加载任务
  1032. this.http.get<any[]>('/backend/api/tasks').subscribe({
  1033. next: (tasks) => {
  1034. this.activeTasks = tasks.map(t => ({ ...t, created_at: new Date(t.created_at), updated_at: new Date(t.updated_at) }));
  1035. this.updateTaskStats();
  1036. console.log(`📋 已加载 ${tasks.length} 个任务`);
  1037. // 同步:将 processing 但实际已完成的任务修正
  1038. this.syncTaskStatesFromRemixes();
  1039. this.refreshView();
  1040. },
  1041. error: () => {
  1042. console.warn('⚠️ 无法从后端加载任务,使用空列表');
  1043. this.activeTasks = [];
  1044. this.refreshView();
  1045. }
  1046. });
  1047. // 加载历史
  1048. this.http.get<any[]>('/backend/api/history').subscribe({
  1049. next: (records) => {
  1050. this.historyRecords = records.map(r => ({ ...r, created_at: new Date(r.created_at) }));
  1051. console.log(`📜 已加载 ${records.length} 条历史记录`);
  1052. this.refreshView();
  1053. },
  1054. error: () => {
  1055. console.warn('⚠️ 无法从后端加载历史,使用空列表');
  1056. this.historyRecords = [];
  1057. this.refreshView();
  1058. }
  1059. });
  1060. // 加载结果
  1061. this.http.get<any[]>('/backend/api/results').subscribe({
  1062. next: (results) => {
  1063. this.generatedResults = results.map(r => ({ ...r, created_at: new Date(r.created_at) }));
  1064. console.log(`🎬 已加载 ${results.length} 个生成结果`);
  1065. this.refreshView();
  1066. },
  1067. error: () => {
  1068. console.warn('⚠️ 无法从后端加载结果,使用空列表');
  1069. this.generatedResults = [];
  1070. this.refreshView();
  1071. }
  1072. });
  1073. }
  1074. // 从 remix 数据同步修正任务状态(处理页面刷新后任务状态不一致)
  1075. private syncTaskStatesFromRemixes(): void {
  1076. this.http.get<Record<string, any[]>>('/backend/api/remixes').subscribe({
  1077. next: (allRemixes) => {
  1078. const remixByTaskId = new Map<string, any>();
  1079. for (const remixes of Object.values(allRemixes)) {
  1080. for (const r of remixes) {
  1081. if (r.taskId) remixByTaskId.set(r.taskId, r);
  1082. }
  1083. }
  1084. let changed = false;
  1085. for (const task of this.activeTasks) {
  1086. if (task.status === 'processing') {
  1087. const remix = remixByTaskId.get(task.id);
  1088. if (remix) {
  1089. if (remix.status === 'completed' || remix.status === 'failed') {
  1090. task.status = remix.status;
  1091. task.step = remix.status === 'completed' ? 'complete' : 'generate';
  1092. task.progress = 100;
  1093. const successCount = remix.segments?.filter((s: any) => s.status === 'completed').length || 0;
  1094. const totalCount = remix.segments?.length || 0;
  1095. task.error_message = remix.status === 'failed' ? `${successCount}/${totalCount} 片段成功` : undefined;
  1096. task.result_url = remix.segments?.find((s: any) => s.videoUrl)?.videoUrl;
  1097. task.updated_at = new Date(remix.updated_at || remix.created_at);
  1098. this.updateTask(task);
  1099. changed = true;
  1100. } else if (remix.status === 'generating') {
  1101. const successCount = remix.segments?.filter((s: any) => s.status === 'completed').length || 0;
  1102. const failedCount = remix.segments?.filter((s: any) => s.status === 'failed').length || 0;
  1103. const totalCount = remix.segments?.length || 0;
  1104. const doneCount = successCount + failedCount;
  1105. task.progress = Math.round((doneCount / totalCount) * 80);
  1106. task.updated_at = new Date(remix.updated_at || remix.created_at);
  1107. this.updateTask(task);
  1108. changed = true;
  1109. }
  1110. }
  1111. }
  1112. }
  1113. // 超过1小时仍为 processing 且无匹配 remix 的任务标记为超时
  1114. const oneHourAgo = Date.now() - 60 * 60 * 1000;
  1115. for (const task of this.activeTasks) {
  1116. if (task.status === 'processing' && !remixByTaskId.has(task.id)) {
  1117. if (new Date(task.updated_at).getTime() < oneHourAgo) {
  1118. task.status = 'timeout';
  1119. task.error_message = '任务超时(无匹配生成记录)';
  1120. task.updated_at = new Date();
  1121. this.updateTask(task);
  1122. changed = true;
  1123. }
  1124. }
  1125. }
  1126. if (changed) this.updateTaskStats();
  1127. this.refreshView();
  1128. },
  1129. error: () => {
  1130. this.refreshView();
  1131. }
  1132. });
  1133. }
  1134. // 任务筛选(点击顶部统计卡可缩小到对应状态)
  1135. tasksFilter: '' | 'pending' | 'processing' | 'completed' | 'failed' = '';
  1136. getFilteredTasks(): Task[] {
  1137. if (!this.tasksFilter) return this.activeTasks;
  1138. return this.activeTasks.filter(t => t.status === this.tasksFilter);
  1139. }
  1140. toggleTasksFilter(status: '' | 'pending' | 'processing' | 'completed' | 'failed'): void {
  1141. this.tasksFilter = this.tasksFilter === status ? '' : status;
  1142. this.refreshView();
  1143. }
  1144. // 计算任务统计
  1145. private updateTaskStats(): void {
  1146. this.taskStats = {
  1147. pending: this.activeTasks.filter(t => t.status === 'pending').length,
  1148. processing: this.activeTasks.filter(t => t.status === 'processing').length,
  1149. completed: this.activeTasks.filter(t => t.status === 'completed').length,
  1150. failed: this.activeTasks.filter(t => t.status === 'failed' || t.status === 'timeout').length
  1151. };
  1152. }
  1153. // ==================== 持久化保存方法 ====================
  1154. // 保存任务到后端(返回 Promise,确保 POST 完成后再允许 PUT)
  1155. saveTask(task: Task): void {
  1156. this.taskSaveReady = new Promise<void>((resolve) => {
  1157. this.http.post<any>('/backend/api/tasks', task).subscribe({
  1158. next: (res) => {
  1159. if (res?.task?.id) task.id = res.task.id;
  1160. this.updateTaskStats();
  1161. console.log('💾 任务已保存:', task.id);
  1162. resolve();
  1163. },
  1164. error: (err) => {
  1165. console.warn('⚠️ 任务保存失败:', err);
  1166. resolve(); // 即使失败也 resolve,避免阻塞后续更新
  1167. }
  1168. });
  1169. });
  1170. }
  1171. // 更新任务到后端(等待 POST 完成后再 PUT)
  1172. updateTask(task: Task): void {
  1173. this.taskSaveReady.then(() => {
  1174. this.http.put<any>(`/backend/api/tasks/${task.id}`, task).subscribe({
  1175. next: () => {
  1176. this.updateTaskStats();
  1177. },
  1178. error: (err) => console.warn('⚠️ 任务更新失败:', err)
  1179. });
  1180. });
  1181. }
  1182. // 删除任务(先做本地乐观更新,再持久化;持久化失败也保留本地删除并提示)
  1183. removeTask(taskId: string): void {
  1184. if (!confirm('确定要删除该任务吗?此操作不可恢复。')) return;
  1185. if (!taskId) {
  1186. // ID 为空的脏数据,直接从本地移除
  1187. this.activeTasks = this.activeTasks.filter(t => !!t.id);
  1188. this.updateTaskStats();
  1189. this.refreshView();
  1190. this.showToast('🗑️ 已清除无效任务', 'info');
  1191. return;
  1192. }
  1193. // 乐观删除:立即从本地列表移除,UI 立刻更新
  1194. this.activeTasks = this.activeTasks.filter(t => t.id !== taskId);
  1195. this.canceledTaskIds.add(taskId);
  1196. this.updateTaskStats();
  1197. this.refreshView();
  1198. this.http.delete<any>(`/backend/api/tasks/${taskId}`).subscribe({
  1199. next: () => {
  1200. console.log('🗑️ 任务已删除:', taskId);
  1201. this.showToast('🗑️ 任务已删除', 'success');
  1202. },
  1203. error: (err) => {
  1204. console.warn('⚠️ 任务删除失败:', err);
  1205. this.showToast('⚠️ 后端删除失败,已从列表中移除', 'warn');
  1206. }
  1207. });
  1208. }
  1209. // 保存历史记录到后端
  1210. saveHistoryRecord(record: Partial<HistoryRecord>): void {
  1211. this.http.post<any>('/backend/api/history', record).subscribe({
  1212. next: (res) => {
  1213. if (res?.record) {
  1214. this.historyRecords.unshift({ ...res.record, created_at: new Date(res.record.created_at) });
  1215. }
  1216. console.log('💾 历史记录已保存');
  1217. },
  1218. error: (err) => console.warn('⚠️ 历史保存失败:', err)
  1219. });
  1220. }
  1221. // 删除历史记录
  1222. removeHistoryRecord(recordId: string): void {
  1223. this.http.delete<any>(`/backend/api/history/${recordId}`).subscribe({
  1224. next: () => {
  1225. this.historyRecords = this.historyRecords.filter(r => r.id !== recordId);
  1226. console.log('🗑️ 历史记录已删除:', recordId);
  1227. },
  1228. error: (err) => console.warn('⚠️ 历史删除失败:', err)
  1229. });
  1230. }
  1231. getFilteredHistoryRecords(): HistoryRecord[] {
  1232. return this.historyRecords.filter(record => {
  1233. return !this.historyFilter.status || record.status === this.historyFilter.status;
  1234. });
  1235. }
  1236. // 把标题中嵌入的 #标签 解析出来,主标题与标签分开渲染
  1237. parseHistoryRecordTitle(record: HistoryRecord): { title: string; tags: string[] } {
  1238. const raw = (record.original_video_title || record.keyword || '').trim();
  1239. if (!raw) return { title: '未命名记录', tags: [] };
  1240. const tags: string[] = [];
  1241. const cleaned = raw.replace(/#([^\s#]+)/g, (_, tag) => { tags.push(tag); return ''; }).replace(/\s+/g, ' ').trim();
  1242. return { title: cleaned || raw, tags };
  1243. }
  1244. getHistoryStatusCount(status: string): number {
  1245. if (!status) return this.historyRecords.length;
  1246. return this.historyRecords.filter(r => r.status === status).length;
  1247. }
  1248. // 保存生成结果到后端
  1249. saveResult(result: Partial<GeneratedResult>): void {
  1250. this.http.post<any>('/backend/api/results', result).subscribe({
  1251. next: (res) => {
  1252. if (res?.result) {
  1253. this.generatedResults.unshift({ ...res.result, created_at: new Date(res.result.created_at) });
  1254. }
  1255. console.log('💾 结果已保存');
  1256. },
  1257. error: (err) => console.warn('⚠️ 结果保存失败:', err)
  1258. });
  1259. }
  1260. // 删除生成结果
  1261. removeResult(resultId: string): void {
  1262. this.http.delete<any>(`/backend/api/results/${resultId}`).subscribe({
  1263. next: () => {
  1264. this.generatedResults = this.generatedResults.filter(r => r.id !== resultId);
  1265. console.log('🗑️ 结果已删除:', resultId);
  1266. },
  1267. error: (err) => console.warn('⚠️ 结果删除失败:', err)
  1268. });
  1269. }
  1270. // Toast 通知
  1271. showToast(message: string, type: 'success' | 'info' | 'warn' | 'error' = 'info', duration: number = 4000): void {
  1272. if (this.toastTimer) clearTimeout(this.toastTimer);
  1273. this.toastMessage = message;
  1274. this.toastType = type;
  1275. this.toastVisible = true;
  1276. this.toastTimer = setTimeout(() => {
  1277. this.toastVisible = false;
  1278. }, duration);
  1279. }
  1280. private refreshView(): void {
  1281. this.cdr.detectChanges();
  1282. }
  1283. // 查找并更新任务
  1284. private findRemixTask(): Task | undefined {
  1285. return this.activeTasks.find(t => t.id === this.currentRemixTaskId);
  1286. }
  1287. private updateRemixTaskProgress(step: Task['step'], progress: number, statusText?: string): void {
  1288. const task = this.findRemixTask();
  1289. if (!task) return;
  1290. task.step = step;
  1291. task.progress = Math.round(progress);
  1292. task.updated_at = new Date();
  1293. if (statusText) task.error_message = undefined;
  1294. this.updateTask(task);
  1295. }
  1296. private completeRemixTask(status: 'completed' | 'failed', resultUrl?: string, errorMsg?: string): void {
  1297. const task = this.findRemixTask();
  1298. if (!task) return;
  1299. task.status = status;
  1300. task.step = status === 'completed' ? 'complete' : task.step;
  1301. task.progress = 100;
  1302. task.result_url = resultUrl;
  1303. task.error_message = errorMsg;
  1304. task.updated_at = new Date();
  1305. this.updateTask(task);
  1306. this.updateTaskStats();
  1307. }
  1308. // ==================== Remix 会话持久化 ====================
  1309. // 保存当前重塑会话到后端(每次片段完成时调用)
  1310. private saveRemixSession(status: 'generating' | 'stitching' | 'completed' | 'failed'): void {
  1311. const video = this.remixTargetVideo;
  1312. if (!video || !this.currentRemixId) return;
  1313. const styleName = this.remixMode === 'digital-human'
  1314. ? '数字人生成'
  1315. : (this.remixStyleOptions.find(s => s.id === this.remixStyle)?.name || this.remixStyle);
  1316. const sessionData = {
  1317. remixId: this.currentRemixId,
  1318. videoId: video.id,
  1319. videoTitle: video.title,
  1320. mode: this.remixMode,
  1321. style: this.remixStyle,
  1322. styleName: styleName,
  1323. quality: this.remixMode === 'digital-human' ? this.remixDigitalHumanResolution : this.remixQuality,
  1324. frames: this.remixFrames,
  1325. aspectRatio: this.remixAspectRatio,
  1326. status: status,
  1327. taskId: this.currentRemixTaskId,
  1328. stitchUrl: this.remixStitchUrl || '',
  1329. digitalHumanAudioSource: this.remixMode === 'digital-human' ? this.remixDigitalHumanAudioSource : '',
  1330. digitalHumanVoiceProfileId: '',
  1331. digitalHumanVoiceProfileName: '',
  1332. results: { ...this.remixResults },
  1333. segments: this.remixStoryboard.map(s => ({
  1334. id: s.id,
  1335. act: s.act,
  1336. narration: s.narration,
  1337. prompt: s.prompt,
  1338. duration: s.duration,
  1339. status: s.status,
  1340. videoUrl: s.videoUrl || '',
  1341. workId: s.workId || '',
  1342. error: s.error || ''
  1343. }))
  1344. };
  1345. this.http.post<any>(`/backend/api/remixes/${video.id}`, sessionData).subscribe({
  1346. next: () => console.log(`💾 Remix 会话已保存: ${this.currentRemixId} [${status}]`),
  1347. error: (err) => console.warn('⚠️ Remix 保存失败:', err)
  1348. });
  1349. }
  1350. // 加载某视频的所有重塑记录
  1351. loadVideoRemixes(videoId: string): void {
  1352. this.http.get<any[]>(`/backend/api/remixes/${videoId}`).subscribe({
  1353. next: (remixes) => {
  1354. const video = this.managedVideos.find(v => v.id === videoId);
  1355. if (video && remixes.length > 0) {
  1356. video.remixVersions = remixes.map(r => ({
  1357. id: r.remixId,
  1358. style: r.styleName || r.style,
  1359. created_at: new Date(r.created_at),
  1360. file_path: r.stitchUrl || r.segments?.find((s: any) => s.videoUrl)?.videoUrl || '',
  1361. thumbnail: 'assets/default-remix-thumb.jpg',
  1362. description: `${r.styleName} · ${r.segments?.length || 0}段 · ${r.status === 'completed' ? '已完成' : r.status === 'generating' ? '生成中' : '失败'}`,
  1363. parameters: {
  1364. style: r.style,
  1365. intensity: 0.8,
  1366. preserve_audio: true,
  1367. quality: r.quality === 'pro' ? 'ultra' : 'high',
  1368. effects: [r.style]
  1369. }
  1370. }));
  1371. console.log(`📂 已加载 ${video.title} 的 ${remixes.length} 条重塑记录`);
  1372. }
  1373. },
  1374. error: () => {}
  1375. });
  1376. }
  1377. // 批量加载所有视频的重塑记录
  1378. private loadAllRemixes(): void {
  1379. this.http.get<Record<string, any[]>>('/backend/api/remixes').subscribe({
  1380. next: (allRemixes) => {
  1381. let total = 0;
  1382. for (const [videoId, remixes] of Object.entries(allRemixes)) {
  1383. const video = this.managedVideos.find(v => v.id === videoId);
  1384. if (video && remixes.length > 0) {
  1385. video.remixVersions = remixes.map(r => ({
  1386. id: r.remixId,
  1387. style: r.styleName || r.style,
  1388. created_at: new Date(r.created_at),
  1389. file_path: r.stitchUrl || r.segments?.find((s: any) => s.videoUrl)?.videoUrl || '',
  1390. thumbnail: 'assets/default-remix-thumb.jpg',
  1391. description: `${r.styleName} · ${r.segments?.length || 0}段 · ${r.status === 'completed' ? '已完成' : r.status === 'generating' ? '生成中' : '失败'}`,
  1392. parameters: {
  1393. style: r.style,
  1394. intensity: 0.8,
  1395. preserve_audio: true,
  1396. quality: r.quality === 'pro' ? 'ultra' : 'high',
  1397. effects: [r.style]
  1398. }
  1399. }));
  1400. total += remixes.length;
  1401. }
  1402. }
  1403. if (total > 0) console.log(`📂 已加载 ${total} 条重塑记录`);
  1404. this.refreshView();
  1405. },
  1406. error: () => {
  1407. this.refreshView();
  1408. }
  1409. });
  1410. }
  1411. // 从 src/video/manifest.json 加载视频清单
  1412. private loadVideoManifest(): void {
  1413. this.http.get<any[]>(`/backend/api/manifest`).subscribe({
  1414. next: (manifest) => {
  1415. this.managedVideos = manifest.map((item: any) => ({
  1416. id: item.id,
  1417. title: item.title || item.filename,
  1418. filename: item.filename,
  1419. filepath: (item.filepath && /^https?:\/\//.test(item.filepath)) ? item.filepath : `/backend/api/video/${item.filename}`,
  1420. size: item.size || 0,
  1421. duration: item.duration || 0,
  1422. created_at: item.created_at ? new Date(item.created_at) : new Date(),
  1423. modified_at: item.modified_at ? new Date(item.modified_at) : new Date(),
  1424. category: item.category || 'downloaded',
  1425. tags: item.tags || [],
  1426. description: item.description || '',
  1427. thumbnail: item.thumbnail || '',
  1428. source: item.source || 'downloaded',
  1429. metadata: item.metadata || { resolution: '', format: 'mp4' },
  1430. whisper: item.whisper || undefined
  1431. }));
  1432. this.updateCategoryCounts();
  1433. console.log(`📁 已加载 ${this.managedVideos.length} 个视频`);
  1434. // 加载每个视频的重塑记录
  1435. this.loadAllRemixes();
  1436. this.refreshView();
  1437. },
  1438. error: (err) => {
  1439. console.warn('⚠️ 无法加载视频清单,使用空列表:', err);
  1440. this.managedVideos = [];
  1441. this.refreshView();
  1442. }
  1443. });
  1444. }
  1445. // 将下载的视频添加到管理列表
  1446. private addToManagedVideos(video: VideoInfo, filename: string): void {
  1447. const newVideo: ManagedVideo = {
  1448. id: `VID-${Date.now()}`,
  1449. title: video.desc || filename,
  1450. filename: filename,
  1451. filepath: `${this.VIDEO_BASE_PATH}/${filename}`,
  1452. size: 0,
  1453. duration: video.duration || 0,
  1454. created_at: new Date(),
  1455. modified_at: new Date(),
  1456. category: 'downloaded',
  1457. tags: video.text_extra || [],
  1458. description: video.desc || '',
  1459. thumbnail: video.cover_url || '',
  1460. source: 'downloaded',
  1461. metadata: {
  1462. resolution: '1920x1080',
  1463. format: 'mp4'
  1464. }
  1465. };
  1466. this.managedVideos.unshift(newVideo);
  1467. this.updateCategoryCounts();
  1468. console.log(`✅ 视频已添加到管理列表: ${filename}`);
  1469. }
  1470. addMonitorAuthor(): void {
  1471. const uniqueId = this.monitorUniqueIdInput.trim();
  1472. if (!uniqueId || this.isAddingMonitorAuthor) return;
  1473. const existingAuthor = this.monitorAuthors.find(author => author.uid === uniqueId || author.id === uniqueId || author.uniqueId === uniqueId || author.shortId === uniqueId);
  1474. if (existingAuthor) {
  1475. this.selectedMonitorAuthorId = existingAuthor.id;
  1476. this.persistMonitorState();
  1477. if (existingAuthor.followerCount === 0) {
  1478. this.refreshMonitorAuthorProfile(existingAuthor, false);
  1479. }
  1480. this.showToast(`⚠️ 博主「${existingAuthor.nickname}」已在监测列表中`, 'warn');
  1481. this.refreshView();
  1482. return;
  1483. }
  1484. this.isAddingMonitorAuthor = true;
  1485. this.monitorAddError = '';
  1486. this.buildCompleteMonitorAuthor(uniqueId, (author, usedFallback) => {
  1487. this.monitorAuthors = [author, ...this.monitorAuthors.filter(item => item.id !== author.id && item.uid !== author.uid)];
  1488. this.monitorUniqueIdInput = '';
  1489. this.isAddingMonitorAuthor = false;
  1490. this.persistMonitorState();
  1491. this.showToast(
  1492. usedFallback
  1493. ? `⚠️ 已添加博主「${author.nickname}」,但完整粉丝数据暂未取到`
  1494. : `✅ 已添加博主「${author.nickname}」`,
  1495. usedFallback ? 'warn' : 'success'
  1496. );
  1497. this.fetchMonitorAuthorWorks(author, false);
  1498. this.refreshView();
  1499. }, (message) => {
  1500. this.isAddingMonitorAuthor = false;
  1501. this.monitorAddError = message;
  1502. this.showToast(`❌ ${this.monitorAddError}`, 'error');
  1503. this.refreshView();
  1504. });
  1505. }
  1506. private buildCompleteMonitorAuthor(
  1507. uniqueId: string,
  1508. onSuccess: (author: MonitorAuthor, usedFallback: boolean) => void,
  1509. onError: (message: string) => void
  1510. ): void {
  1511. this.douyinService.getUserProfileByUniqueId(uniqueId).subscribe({
  1512. next: (res: any) => {
  1513. const basicProfile = this.douyinService.extractUserProfileData(res) || {};
  1514. const basicAuthor = this.mapMonitorAuthor(basicProfile, uniqueId);
  1515. if (!basicAuthor.secUserId) {
  1516. onError('未能从抖音号解析出 sec_user_id,暂时无法加载主页作品');
  1517. return;
  1518. }
  1519. this.douyinService.getUserProfileBySecUserId(basicAuthor.secUserId).subscribe({
  1520. next: (detailRes: any) => {
  1521. const detailProfile = this.douyinService.extractUserProfileData(detailRes) || {};
  1522. const author = this.mapMonitorAuthor({
  1523. ...basicProfile,
  1524. ...detailProfile,
  1525. sec_uid: detailProfile?.sec_uid || detailProfile?.sec_user_id || basicProfile?.sec_uid || basicProfile?.sec_user_id || basicAuthor.secUserId,
  1526. sec_user_id: detailProfile?.sec_user_id || detailProfile?.sec_uid || basicProfile?.sec_user_id || basicProfile?.sec_uid || basicAuthor.secUserId,
  1527. unique_id: detailProfile?.unique_id || basicProfile?.unique_id || uniqueId,
  1528. short_id: detailProfile?.short_id || basicProfile?.short_id || '',
  1529. douyin_id: detailProfile?.douyin_id || basicProfile?.douyin_id || ''
  1530. }, uniqueId);
  1531. onSuccess(author, false);
  1532. },
  1533. error: () => {
  1534. onSuccess(basicAuthor, true);
  1535. }
  1536. });
  1537. },
  1538. error: (error: any) => {
  1539. onError(this.getErrorText(error, '获取博主信息失败,请稍后重试'));
  1540. }
  1541. });
  1542. }
  1543. private refreshIncompleteMonitorAuthors(): void {
  1544. this.monitorAuthors
  1545. .filter(author => author.followerCount === 0)
  1546. .forEach(author => this.refreshMonitorAuthorProfile(author, true));
  1547. }
  1548. private refreshMonitorAuthorProfile(author: MonitorAuthor, silent: boolean): void {
  1549. const lookupId = (author.uniqueId || author.shortId || author.uid || '').trim();
  1550. if (!lookupId) {
  1551. return;
  1552. }
  1553. this.buildCompleteMonitorAuthor(lookupId, (nextAuthor, usedFallback) => {
  1554. const mergedAuthor: MonitorAuthor = {
  1555. ...author,
  1556. ...nextAuthor,
  1557. works: author.works,
  1558. worksCursor: author.worksCursor,
  1559. hasMoreWorks: author.hasMoreWorks,
  1560. loadingWorks: author.loadingWorks,
  1561. coverUrl: author.coverUrl || nextAuthor.coverUrl
  1562. };
  1563. this.monitorAuthors = this.monitorAuthors.map(item => (
  1564. item.id === author.id
  1565. || item.uid === author.uid
  1566. || (!!author.secUserId && item.secUserId === author.secUserId)
  1567. || (!!lookupId && (item.uniqueId === lookupId || item.shortId === lookupId || item.uid === lookupId))
  1568. ? mergedAuthor
  1569. : item
  1570. ));
  1571. if (this.selectedMonitorAuthorId === author.id) {
  1572. this.selectedMonitorAuthorId = mergedAuthor.id;
  1573. }
  1574. this.persistMonitorState();
  1575. if (!silent) {
  1576. this.showToast(
  1577. usedFallback
  1578. ? `⚠️ 博主「${mergedAuthor.nickname}」资料已刷新,但完整粉丝数据暂未取到`
  1579. : `✅ 博主「${mergedAuthor.nickname}」资料已刷新`,
  1580. usedFallback ? 'warn' : 'success'
  1581. );
  1582. }
  1583. this.refreshView();
  1584. }, (message) => {
  1585. if (!silent) {
  1586. this.showToast(`❌ ${message}`, 'error');
  1587. }
  1588. });
  1589. }
  1590. openMonitorAuthor(author: MonitorAuthor): void {
  1591. this.selectedMonitorAuthorId = author.id;
  1592. this.persistMonitorState();
  1593. if (author.followerCount === 0) {
  1594. this.refreshMonitorAuthorProfile(author, true);
  1595. }
  1596. if (!author.loadingWorks && author.works.length === 0) {
  1597. this.fetchMonitorAuthorWorks(author, false);
  1598. }
  1599. this.refreshView();
  1600. }
  1601. backToMonitorList(): void {
  1602. this.selectedMonitorAuthorId = '';
  1603. this.persistMonitorState();
  1604. this.refreshView();
  1605. }
  1606. removeMonitorAuthor(author: MonitorAuthor): void {
  1607. if (!confirm(`确定要删除博主「${author.nickname}」吗?`)) {
  1608. return;
  1609. }
  1610. this.monitorAuthors = this.monitorAuthors.filter(item => item.id !== author.id);
  1611. if (this.selectedMonitorAuthorId === author.id) {
  1612. this.selectedMonitorAuthorId = '';
  1613. }
  1614. this.persistMonitorState();
  1615. this.showToast(`🗑️ 已移除博主「${author.nickname}」`, 'success');
  1616. this.refreshView();
  1617. }
  1618. getSelectedMonitorAuthor(): MonitorAuthor | null {
  1619. return this.monitorAuthors.find(author => author.id === this.selectedMonitorAuthorId) || null;
  1620. }
  1621. getTotalMonitorWorksCount(): number {
  1622. return this.monitorAuthors.reduce((total, author) => total + author.works.length, 0);
  1623. }
  1624. reloadMonitorAuthorWorks(author: MonitorAuthor): void {
  1625. this.fetchMonitorAuthorWorks(author, false);
  1626. }
  1627. loadMoreMonitorWorks(author: MonitorAuthor): void {
  1628. if (!author.hasMoreWorks || author.loadingWorks) {
  1629. return;
  1630. }
  1631. this.fetchMonitorAuthorWorks(author, true);
  1632. }
  1633. handleMonitorAuthorAvatarError(author: MonitorAuthor): void {
  1634. const currentIndex = author.avatarCandidates.indexOf(author.avatarUrl);
  1635. const nextIndex = currentIndex >= 0 ? currentIndex + 1 : 0;
  1636. author.avatarUrl = author.avatarCandidates[nextIndex] || this.getMonitorAvatarFallback(author.nickname);
  1637. this.refreshView();
  1638. }
  1639. handleMonitorWorkCoverError(work: MonitorWork): void {
  1640. const currentIndex = work.coverCandidates.indexOf(work.coverUrl);
  1641. const nextIndex = currentIndex >= 0 ? currentIndex + 1 : 0;
  1642. work.coverUrl = work.coverCandidates[nextIndex] || this.getVideoCoverFallback();
  1643. this.refreshView();
  1644. }
  1645. previewMonitorWork(author: MonitorAuthor, work: MonitorWork): void {
  1646. if (work.type !== 'video') {
  1647. window.open(work.coverUrl, '_blank');
  1648. return;
  1649. }
  1650. this.viewVideoDetail(this.buildMonitorVideoInfo(author, work));
  1651. }
  1652. downloadMonitorWork(author: MonitorAuthor, work: MonitorWork): void {
  1653. if (work.type !== 'video' || work.isDownloading) return;
  1654. work.isDownloading = true;
  1655. work.downloadProgress = 0;
  1656. const video = this.buildMonitorVideoInfo(author, work);
  1657. this.douyinService.getVideoDetail(work.id).subscribe({
  1658. next: (res: any) => {
  1659. const detailData = this.douyinService.extractVideoDetailData(res) || {};
  1660. const downloadUrls = this.douyinService.extractVideoDownloadUrls(res);
  1661. const downloadUrl = downloadUrls[0] || '';
  1662. if (!downloadUrl) {
  1663. work.isDownloading = false;
  1664. work.downloadProgress = 0;
  1665. this.showToast('❌ 无法获取下载地址,请稍后重试', 'error');
  1666. this.refreshView();
  1667. return;
  1668. }
  1669. const filename = this.buildVideoFilename(video);
  1670. this.douyinService.startManagedDownload({
  1671. url: downloadUrl,
  1672. urls: downloadUrls,
  1673. filename,
  1674. title: work.desc || work.id,
  1675. description: detailData?.desc || work.desc || '',
  1676. tags: [],
  1677. thumbnail: work.coverUrl || '',
  1678. duration: work.duration || 0,
  1679. resolution: detailData?.video?.ratio || '',
  1680. awemeId: work.id,
  1681. authorName: author.nickname || ''
  1682. }).subscribe({
  1683. next: (taskRes: any) => {
  1684. if (!taskRes?.taskId) {
  1685. work.isDownloading = false;
  1686. work.downloadProgress = 0;
  1687. this.showToast('❌ 下载任务创建失败,请稍后重试', 'error');
  1688. return;
  1689. }
  1690. this.showToast(`📥 正在下载「${work.desc || work.id}」到视频库`, 'info');
  1691. this.pollMonitorWorkDownload(work, taskRes.taskId);
  1692. },
  1693. error: (error: any) => {
  1694. work.isDownloading = false;
  1695. work.downloadProgress = 0;
  1696. this.showToast(`❌ 创建下载任务失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  1697. this.refreshView();
  1698. }
  1699. });
  1700. },
  1701. error: (error: any) => {
  1702. work.isDownloading = false;
  1703. work.downloadProgress = 0;
  1704. this.showToast(`❌ 获取视频信息失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  1705. this.refreshView();
  1706. }
  1707. });
  1708. }
  1709. getMonitorHeroBackground(author: MonitorAuthor): string {
  1710. return author.coverUrl
  1711. ? `linear-gradient(90deg, rgba(11, 15, 25, 0.92), rgba(11, 15, 25, 0.55)), url(${author.coverUrl})`
  1712. : 'linear-gradient(135deg, #161a27, #232a3d)';
  1713. }
  1714. // 搜索视频
  1715. searchVideos(): void {
  1716. if (!this.searchKeyword.trim()) return;
  1717. this.isSearching = true;
  1718. this.searchCursor = 0;
  1719. this.searchId = '';
  1720. this.searchBacktrace = '';
  1721. this.searchResults = [];
  1722. this.filteredSearchResults = [];
  1723. this.douyinService.searchVideos(this.searchKeyword, '0', 0, '0', '0', '1')
  1724. .subscribe({
  1725. next: (res: any) => {
  1726. this.isSearching = false;
  1727. const parsed = this.parseSearchResponse(res);
  1728. this.searchResults = parsed.items
  1729. .map((item: any) => this.mapVideoItem(item))
  1730. .filter((item: VideoInfo) => !!item.aweme_id || !!item.desc || !!item.cover_url);
  1731. this.applySearchFilters();
  1732. this.hasMore = parsed.hasMore;
  1733. this.searchCursor = parsed.cursor;
  1734. this.searchId = parsed.searchId;
  1735. this.searchBacktrace = parsed.backtrace;
  1736. console.log('🔍 搜索结果解析:', { raw: res, parsed, mapped: this.searchResults });
  1737. this.refreshView();
  1738. if (this.filteredSearchResults.length === 0) {
  1739. alert('未找到相关视频,请尝试其他关键词');
  1740. }
  1741. },
  1742. error: (error: any) => {
  1743. console.error('搜索失败:', error);
  1744. this.isSearching = false;
  1745. let errorMessage = '搜索失败,请稍后重试';
  1746. if (error.status === 401) {
  1747. errorMessage = '认证失败,Token可能已失效';
  1748. } else if (error.status === 429) {
  1749. errorMessage = '请求过于频繁,请稍后重试';
  1750. } else if (error.status === 0) {
  1751. errorMessage = '网络连接失败,请检查网络设置';
  1752. }
  1753. alert(errorMessage);
  1754. }
  1755. });
  1756. }
  1757. // 映射API返回的视频数据
  1758. private mapVideoItem(item: any): VideoInfo {
  1759. const info = item?.aweme_info || item?.data?.aweme_info || item?.data?.challenge_info || item;
  1760. const coverCandidates = this.buildCoverCandidates(info);
  1761. const coverUrl = coverCandidates[0] || this.getVideoCoverFallback();
  1762. const duration = Math.floor((info.video?.duration || info.duration || 0) / ((info.video?.duration || info.duration || 0) > 1000 ? 1000 : 1));
  1763. const tags = Array.isArray(info.text_extra)
  1764. ? info.text_extra
  1765. .map((tag: any) => tag?.hashtag_name || tag?.cha_name || tag?.tag_name || tag?.hash_tag_name || tag)
  1766. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  1767. : Array.isArray(info.cha_list)
  1768. ? info.cha_list
  1769. .map((tag: any) => tag?.cha_name || tag?.hashtag_name || tag?.tag_name || tag)
  1770. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  1771. : (info.desc ? [info.desc] : []);
  1772. return {
  1773. aweme_id: info.aweme_id || info.group_id || info.cid || item.data_id || '',
  1774. desc: info.desc || info.cha_name || info.title || info.content || '',
  1775. cover_url: coverUrl,
  1776. cover_candidates: coverCandidates,
  1777. duration: duration,
  1778. create_time: info.create_time || item.create_time || 0,
  1779. publishDate: (info.create_time || item.create_time) ? new Date((info.create_time || item.create_time) * 1000) : null,
  1780. author: {
  1781. nickname: info.author?.nickname || info.nickname || '未知作者',
  1782. sec_uid: info.author?.sec_uid || info.author?.uid || ''
  1783. },
  1784. statistics: {
  1785. play_count: info.statistics?.play_count || info.view_count || 0,
  1786. digg_count: info.statistics?.digg_count || info.user_count || 0,
  1787. comment_count: info.statistics?.comment_count || 0,
  1788. share_count: info.statistics?.share_count || 0
  1789. },
  1790. text_extra: tags
  1791. };
  1792. }
  1793. private buildCoverCandidates(info: any): string[] {
  1794. const candidates = [
  1795. info.video?.origin_cover?.url_list?.[0],
  1796. info.video?.cover?.url_list?.[0],
  1797. info.video?.dynamic_cover?.url_list?.[0],
  1798. info.video?.animated_cover?.url_list?.[0],
  1799. info.author?.avatar_larger?.url_list?.[0],
  1800. info.author?.avatar_medium?.url_list?.[0],
  1801. info.author?.avatar_thumb?.url_list?.[0],
  1802. info.hashtag_profile,
  1803. info.cover_url
  1804. ];
  1805. return candidates.filter((url, index, list) => typeof url === 'string' && url.trim() && list.indexOf(url) === index);
  1806. }
  1807. handleVideoCoverError(video: VideoInfo): void {
  1808. const candidates = video.cover_candidates || [];
  1809. const currentIndex = candidates.indexOf(video.cover_url);
  1810. const nextIndex = currentIndex >= 0 ? currentIndex + 1 : 0;
  1811. const nextCover = candidates[nextIndex];
  1812. if (nextCover) {
  1813. video.cover_url = nextCover;
  1814. } else {
  1815. video.cover_url = this.getVideoCoverFallback();
  1816. }
  1817. this.refreshView();
  1818. }
  1819. private getVideoCoverFallback(): string {
  1820. return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="480" height="270" viewBox="0 0 480 270"><rect width="480" height="270" fill="#f3f4f6"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#9ca3af" font-size="20">封面加载失败</text></svg>');
  1821. }
  1822. private parseSearchResponse(res: any): { items: any[]; hasMore: boolean; cursor: number; searchId: string; backtrace: string } {
  1823. const normalizedResponse = this.parseJsonPayload(res);
  1824. const normalizedData = this.parseJsonPayload(normalizedResponse?.data);
  1825. const nestedData = this.parseJsonPayload(normalizedData?.data);
  1826. const businessConfig = this.parseJsonPayload(normalizedData?.business_config) || {};
  1827. const nextPage = this.parseJsonPayload(businessConfig?.next_page) || {};
  1828. const directData = Array.isArray(normalizedData) ? normalizedData : [];
  1829. const nestedArray = Array.isArray(nestedData) ? nestedData : [];
  1830. const businessData = Array.isArray(normalizedData?.business_data) ? normalizedData.business_data : [];
  1831. const items = directData.length > 0 ? directData : (nestedArray.length > 0 ? nestedArray : businessData);
  1832. const hasMore =
  1833. normalizedResponse?.has_more === 1 ||
  1834. normalizedData?.has_more === 1 ||
  1835. businessConfig?.has_more === 1 ||
  1836. false;
  1837. const cursor =
  1838. normalizedResponse?.cursor ??
  1839. normalizedData?.cursor ??
  1840. nextPage?.cursor ??
  1841. items.length;
  1842. const searchId =
  1843. normalizedResponse?.search_id ||
  1844. normalizedData?.search_id ||
  1845. nextPage?.search_id ||
  1846. nextPage?.search_request_id ||
  1847. '';
  1848. const backtrace =
  1849. normalizedResponse?.backtrace ||
  1850. normalizedData?.backtrace ||
  1851. nextPage?.backtrace ||
  1852. '';
  1853. return {
  1854. items,
  1855. hasMore,
  1856. cursor: typeof cursor === 'number' ? cursor : Number(cursor || items.length),
  1857. searchId,
  1858. backtrace
  1859. };
  1860. }
  1861. private parseJsonPayload(value: any): any {
  1862. let current = value;
  1863. while (typeof current === 'string') {
  1864. const trimmed = current.trim();
  1865. if (!trimmed || (!trimmed.startsWith('{') && !trimmed.startsWith('['))) {
  1866. break;
  1867. }
  1868. try {
  1869. current = JSON.parse(trimmed);
  1870. } catch {
  1871. break;
  1872. }
  1873. }
  1874. return current;
  1875. }
  1876. private normalizeMonitorLabelText(value: any): string {
  1877. const normalized = this.parseJsonPayload(value);
  1878. if (typeof normalized === 'string') {
  1879. const trimmed = normalized.trim();
  1880. if (!trimmed) {
  1881. return '';
  1882. }
  1883. const labelTextMatch = trimmed.match(/"label_text"\s*:\s*"([^"]+)"/);
  1884. if (labelTextMatch?.[1]) {
  1885. return labelTextMatch[1].trim();
  1886. }
  1887. return trimmed;
  1888. }
  1889. if (Array.isArray(normalized)) {
  1890. return normalized
  1891. .map(item => this.normalizeMonitorLabelText(item))
  1892. .find(item => !!item) || '';
  1893. }
  1894. if (normalized && typeof normalized === 'object') {
  1895. const candidateKeys = ['label_text', 'text', 'name', 'title', 'desc'];
  1896. for (const key of candidateKeys) {
  1897. const text = this.normalizeMonitorLabelText(normalized[key]);
  1898. if (text) {
  1899. return text;
  1900. }
  1901. }
  1902. }
  1903. return '';
  1904. }
  1905. getMonitorIpLocationText(author: MonitorAuthor | null | undefined): string {
  1906. const location = this.normalizeMonitorIpLocation(author?.ipLocation);
  1907. return location ? `IP 属地:${location}` : 'IP 属地未抓取';
  1908. }
  1909. private normalizeMonitorIpLocation(value: any): string {
  1910. const normalized = this.normalizeMonitorLabelText(value);
  1911. if (!normalized) {
  1912. return '';
  1913. }
  1914. return normalized.replace(/^IP\s*属地\s*[::]?\s*/i, '').trim();
  1915. }
  1916. private pickMonitorCountValue(values: any[]): number {
  1917. for (const value of values) {
  1918. const parsed = this.parseMonitorCountValue(value);
  1919. if (parsed !== null) {
  1920. return parsed;
  1921. }
  1922. }
  1923. return 0;
  1924. }
  1925. private parseMonitorCountValue(value: any): number | null {
  1926. const normalized = this.parseJsonPayload(value);
  1927. if (typeof normalized === 'number') {
  1928. return Number.isFinite(normalized) ? normalized : null;
  1929. }
  1930. if (typeof normalized === 'string') {
  1931. const trimmed = normalized.trim();
  1932. if (!trimmed) {
  1933. return null;
  1934. }
  1935. const compact = trimmed.replace(/,/g, '').replace(/\s+/g, '');
  1936. const unitMatch = compact.match(/^([\d.]+)(亿|万|[kKmMwW])$/);
  1937. if (unitMatch) {
  1938. const base = Number(unitMatch[1]);
  1939. if (!Number.isFinite(base)) {
  1940. return null;
  1941. }
  1942. const unit = unitMatch[2].toLowerCase();
  1943. const multiplier = unit === '亿'
  1944. ? 100000000
  1945. : (unit === '万' || unit === 'w')
  1946. ? 10000
  1947. : unit === 'm'
  1948. ? 1000000
  1949. : 1000;
  1950. return Math.round(base * multiplier);
  1951. }
  1952. const directNumber = Number(compact);
  1953. return Number.isFinite(directNumber) ? directNumber : null;
  1954. }
  1955. if (normalized && typeof normalized === 'object') {
  1956. const candidateKeys = ['count', 'value', 'total', 'num'];
  1957. for (const key of candidateKeys) {
  1958. const parsed = this.parseMonitorCountValue(normalized[key]);
  1959. if (parsed !== null) {
  1960. return parsed;
  1961. }
  1962. }
  1963. }
  1964. return null;
  1965. }
  1966. onSearchFilterChange(): void {
  1967. this.applySearchFilters();
  1968. this.refreshView();
  1969. }
  1970. private applySearchFilters(): void {
  1971. let items = [...this.searchResults];
  1972. if (this.publishTime !== '0') {
  1973. const nowSeconds = Math.floor(Date.now() / 1000);
  1974. const limitSeconds = Number(this.publishTime) * 24 * 60 * 60;
  1975. items = items.filter((video) => !video.create_time || (nowSeconds - video.create_time) <= limitSeconds);
  1976. }
  1977. if (this.filterDuration !== '0') {
  1978. const [minMinutes, maxMinutes] = this.filterDuration.split('-').map(value => Number(value || 0));
  1979. items = items.filter((video) => {
  1980. const durationMinutes = (video.duration || 0) / 60;
  1981. return durationMinutes >= minMinutes && durationMinutes <= maxMinutes;
  1982. });
  1983. }
  1984. if (this.sortType === '1') {
  1985. items.sort((a, b) => (b.statistics?.digg_count || 0) - (a.statistics?.digg_count || 0));
  1986. } else if (this.sortType === '2') {
  1987. items.sort((a, b) => (b.create_time || 0) - (a.create_time || 0));
  1988. }
  1989. this.filteredSearchResults = items;
  1990. }
  1991. private fetchMonitorAuthorWorks(author: MonitorAuthor, append: boolean): void {
  1992. if (!author.secUserId || author.loadingWorks) {
  1993. return;
  1994. }
  1995. author.loadingWorks = true;
  1996. const cursor = append ? author.worksCursor : '0';
  1997. this.refreshView();
  1998. this.douyinService.getUserPostVideos(author.secUserId, cursor).subscribe({
  1999. next: (res: any) => {
  2000. const parsed = this.douyinService.extractUserPostVideos(res);
  2001. const mappedWorks = parsed.items
  2002. .map((item: any) => this.mapMonitorWork(item))
  2003. .filter((item: MonitorWork) => !!item.id || !!item.desc || !!item.coverUrl);
  2004. author.works = append
  2005. ? [...author.works, ...mappedWorks.filter(item => !author.works.some(existing => existing.id === item.id))]
  2006. : mappedWorks;
  2007. author.worksCursor = parsed.cursor;
  2008. author.hasMoreWorks = parsed.hasMore;
  2009. author.loadingWorks = false;
  2010. author.coverUrl = author.coverUrl || author.works[0]?.coverUrl || author.avatarUrl;
  2011. this.persistMonitorState();
  2012. this.refreshView();
  2013. },
  2014. error: (error: any) => {
  2015. author.loadingWorks = false;
  2016. this.showToast(`❌ ${this.getErrorText(error, '加载博主作品失败,请稍后重试')}`, 'error');
  2017. this.refreshView();
  2018. }
  2019. });
  2020. }
  2021. private mapMonitorAuthor(profile: any, uid: string): MonitorAuthor {
  2022. const avatarCandidates = this.pickUniqueStringValues([
  2023. profile?.avatar_larger?.url_list,
  2024. profile?.avatar_medium?.url_list,
  2025. profile?.avatar_thumb?.url_list,
  2026. profile?.avatar_168x168?.url_list,
  2027. profile?.avatar_url
  2028. ]);
  2029. const coverCandidates = this.pickUniqueStringValues([
  2030. profile?.cover_url,
  2031. profile?.cover_urls,
  2032. profile?.cover_thumb?.url_list,
  2033. profile?.video_cover?.url_list,
  2034. avatarCandidates
  2035. ]);
  2036. const nickname = profile?.nickname || profile?.display_name || `UID ${uid}`;
  2037. const verifiedText = [
  2038. profile?.custom_verify,
  2039. profile?.enterprise_verify_reason,
  2040. profile?.account_cert_info,
  2041. profile?.verification_info
  2042. ].map((item: any) => this.normalizeMonitorLabelText(item)).find((item: string) => !!item) || '';
  2043. const ipLocation = this.normalizeMonitorIpLocation(
  2044. [
  2045. profile?.ip_location,
  2046. profile?.ip_label,
  2047. profile?.ipLocation,
  2048. profile?.ip_info?.location,
  2049. profile?.ip_info?.ip_location,
  2050. profile?.ip_region,
  2051. profile?.location
  2052. ].find((item: any) => !!this.normalizeMonitorLabelText(item)) || ''
  2053. );
  2054. const followerCount = this.pickMonitorCountValue([
  2055. profile?.follower_count,
  2056. profile?.followerCount,
  2057. profile?.fans_count,
  2058. profile?.fansCount,
  2059. profile?.public_fans_count,
  2060. profile?.statistics?.follower_count,
  2061. profile?.statistics?.fans_count,
  2062. profile?.author_stats?.follower_count,
  2063. profile?.author_stats?.fans_count,
  2064. profile?.user_stats?.follower_count,
  2065. profile?.user_stats?.fans_count,
  2066. profile?.user_statistics?.follower_count,
  2067. profile?.user_statistics?.fans_count,
  2068. profile?.stats?.follower_count,
  2069. profile?.stats?.fans_count
  2070. ]);
  2071. const followingCount = this.pickMonitorCountValue([
  2072. profile?.following_count,
  2073. profile?.followingCount,
  2074. profile?.statistics?.following_count,
  2075. profile?.author_stats?.following_count,
  2076. profile?.user_stats?.following_count,
  2077. profile?.user_statistics?.following_count,
  2078. profile?.stats?.following_count
  2079. ]);
  2080. const totalFavorited = this.pickMonitorCountValue([
  2081. profile?.total_favorited,
  2082. profile?.favoriting_count,
  2083. profile?.totalFavorited,
  2084. profile?.liked_count,
  2085. profile?.statistics?.total_favorited,
  2086. profile?.statistics?.favoriting_count,
  2087. profile?.author_stats?.total_favorited,
  2088. profile?.user_stats?.total_favorited,
  2089. profile?.user_statistics?.total_favorited,
  2090. profile?.stats?.total_favorited
  2091. ]);
  2092. const awemeCount = this.pickMonitorCountValue([
  2093. profile?.aweme_count,
  2094. profile?.video_count,
  2095. profile?.awemeCount,
  2096. profile?.statistics?.aweme_count,
  2097. profile?.statistics?.video_count,
  2098. profile?.author_stats?.aweme_count,
  2099. profile?.user_stats?.aweme_count,
  2100. profile?.user_statistics?.aweme_count,
  2101. profile?.stats?.aweme_count
  2102. ]);
  2103. return {
  2104. id: String(profile?.uid || uid),
  2105. uid: String(uid),
  2106. secUserId: String(profile?.sec_uid || profile?.sec_user_id || profile?.secUid || ''),
  2107. nickname,
  2108. uniqueId: String(profile?.unique_id || profile?.short_id || profile?.douyin_id || ''),
  2109. shortId: String(profile?.short_id || profile?.douyin_id || ''),
  2110. signature: profile?.signature || profile?.bio_description || '',
  2111. ipLocation,
  2112. verifiedText,
  2113. avatarUrl: avatarCandidates[0] || this.getMonitorAvatarFallback(nickname),
  2114. avatarCandidates,
  2115. coverUrl: coverCandidates[0] || '',
  2116. coverCandidates,
  2117. followerCount,
  2118. followingCount,
  2119. totalFavorited,
  2120. awemeCount,
  2121. works: [],
  2122. worksCursor: '0',
  2123. hasMoreWorks: false,
  2124. loadingWorks: false
  2125. };
  2126. }
  2127. private mapMonitorWork(item: any): MonitorWork {
  2128. const coverCandidates = this.pickUniqueStringValues([
  2129. item?.video?.origin_cover?.url_list,
  2130. item?.video?.cover?.url_list,
  2131. item?.video?.dynamic_cover?.url_list,
  2132. item?.cover?.url_list,
  2133. item?.images?.map((image: any) => image?.url_list?.[0] || image?.download_url_list?.[0]),
  2134. item?.image_infos?.map((image: any) => image?.label_large?.url_list?.[0] || image?.label_thumb?.url_list?.[0]),
  2135. item?.cover_url
  2136. ]);
  2137. const rawDuration = Number(item?.video?.duration || item?.duration || 0);
  2138. const createTimestamp = Number(item?.create_time || 0);
  2139. const statistics = item?.statistics || item?.statis || {};
  2140. const hasImageGroup = (Array.isArray(item?.images) && item.images.length > 0) || (Array.isArray(item?.image_infos) && item.image_infos.length > 0);
  2141. return {
  2142. id: String(item?.aweme_id || item?.group_id || item?.item_id || `${Date.now()}-${Math.random()}`),
  2143. desc: item?.desc || item?.title || '未命名作品',
  2144. coverUrl: coverCandidates[0] || this.getVideoCoverFallback(),
  2145. coverCandidates,
  2146. duration: Math.floor(rawDuration / (rawDuration > 1000 ? 1000 : 1)),
  2147. createTime: createTimestamp ? new Date(createTimestamp > 1000000000000 ? createTimestamp : createTimestamp * 1000) : undefined,
  2148. type: hasImageGroup ? 'image' : 'video',
  2149. statistics: {
  2150. play_count: Number(statistics?.play_count || statistics?.playCount || 0),
  2151. digg_count: Number(statistics?.digg_count || 0),
  2152. comment_count: Number(statistics?.comment_count || 0),
  2153. share_count: Number(statistics?.share_count || 0)
  2154. }
  2155. };
  2156. }
  2157. private pickUniqueStringValues(values: any[]): string[] {
  2158. const uniqueValues: string[] = [];
  2159. const collect = (value: any) => {
  2160. if (Array.isArray(value)) {
  2161. value.forEach(collect);
  2162. return;
  2163. }
  2164. if (typeof value === 'string' && value.trim() && !uniqueValues.includes(value)) {
  2165. uniqueValues.push(value);
  2166. }
  2167. };
  2168. values.forEach(collect);
  2169. return uniqueValues;
  2170. }
  2171. private getMonitorAvatarFallback(name: string): string {
  2172. const label = (name || '博主').trim().slice(0, 2) || '博主';
  2173. return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160" viewBox="0 0 160 160"><rect width="160" height="160" rx="80" fill="#ff0050"/><text x="50%" y="54%" text-anchor="middle" dominant-baseline="middle" fill="#ffffff" font-size="48" font-family="Arial, sans-serif">${label}</text></svg>`);
  2174. }
  2175. private getErrorText(error: any, fallback: string): string {
  2176. return error?.error?.error || error?.error?.msg || error?.message || fallback;
  2177. }
  2178. private async extractHttpBlobErrorMessage(error: any, fallback: string): Promise<string> {
  2179. if (error instanceof HttpErrorResponse && error.error instanceof Blob) {
  2180. try {
  2181. const text = await error.error.text();
  2182. if (text) {
  2183. const parsed = JSON.parse(text);
  2184. return parsed?.error || parsed?.message || fallback;
  2185. }
  2186. } catch {
  2187. return fallback;
  2188. }
  2189. }
  2190. return error?.error?.error || error?.error?.message || error?.message || fallback;
  2191. }
  2192. private serializeMonitorAuthor(author: MonitorAuthor): any {
  2193. return {
  2194. ...author,
  2195. loadingWorks: false,
  2196. works: author.works.map(work => ({
  2197. ...work,
  2198. createTime: work.createTime ? work.createTime.toISOString() : null,
  2199. isDownloading: false,
  2200. downloadProgress: 0
  2201. }))
  2202. };
  2203. }
  2204. private deserializeMonitorAuthor(author: any): MonitorAuthor {
  2205. return {
  2206. id: String(author?.id || ''),
  2207. uid: String(author?.uid || ''),
  2208. secUserId: String(author?.secUserId || ''),
  2209. nickname: String(author?.nickname || ''),
  2210. uniqueId: String(author?.uniqueId || ''),
  2211. shortId: String(author?.shortId || ''),
  2212. signature: String(author?.signature || ''),
  2213. ipLocation: String(author?.ipLocation || ''),
  2214. verifiedText: this.normalizeMonitorLabelText(author?.verifiedText),
  2215. avatarUrl: String(author?.avatarUrl || this.getMonitorAvatarFallback(author?.nickname || '博主')),
  2216. avatarCandidates: Array.isArray(author?.avatarCandidates) ? author.avatarCandidates : [],
  2217. coverUrl: String(author?.coverUrl || ''),
  2218. coverCandidates: Array.isArray(author?.coverCandidates) ? author.coverCandidates : [],
  2219. followerCount: Number(author?.followerCount || 0),
  2220. followingCount: Number(author?.followingCount || 0),
  2221. totalFavorited: Number(author?.totalFavorited || 0),
  2222. awemeCount: Number(author?.awemeCount || 0),
  2223. works: Array.isArray(author?.works)
  2224. ? author.works.map((work: any) => ({
  2225. id: String(work?.id || ''),
  2226. desc: String(work?.desc || ''),
  2227. coverUrl: String(work?.coverUrl || this.getVideoCoverFallback()),
  2228. coverCandidates: Array.isArray(work?.coverCandidates) ? work.coverCandidates : [],
  2229. duration: Number(work?.duration || 0),
  2230. createTime: work?.createTime ? new Date(work.createTime) : undefined,
  2231. type: work?.type === 'image' ? 'image' : 'video',
  2232. statistics: {
  2233. play_count: Number(work?.statistics?.play_count || 0),
  2234. digg_count: Number(work?.statistics?.digg_count || 0),
  2235. comment_count: Number(work?.statistics?.comment_count || 0),
  2236. share_count: Number(work?.statistics?.share_count || 0)
  2237. },
  2238. isDownloading: false,
  2239. downloadProgress: 0
  2240. }))
  2241. : [],
  2242. worksCursor: String(author?.worksCursor || '0'),
  2243. hasMoreWorks: !!author?.hasMoreWorks,
  2244. loadingWorks: false
  2245. };
  2246. }
  2247. // 加载更多搜索结果
  2248. loadMore(): void {
  2249. if (!this.hasMore || this.isSearching) return;
  2250. this.isSearching = true;
  2251. this.douyinService.searchVideos(
  2252. this.searchKeyword, '0', this.searchCursor, '0',
  2253. '0', '1', this.searchId, this.searchBacktrace
  2254. ).subscribe({
  2255. next: (res: any) => {
  2256. this.isSearching = false;
  2257. const parsed = this.parseSearchResponse(res);
  2258. const newItems = parsed.items
  2259. .map((item: any) => this.mapVideoItem(item))
  2260. .filter((item: VideoInfo) => !!item.aweme_id || !!item.desc || !!item.cover_url);
  2261. this.searchResults.push(...newItems);
  2262. this.applySearchFilters();
  2263. this.hasMore = parsed.hasMore;
  2264. this.searchCursor = parsed.cursor;
  2265. this.searchId = parsed.searchId || this.searchId;
  2266. this.searchBacktrace = parsed.backtrace || this.searchBacktrace;
  2267. this.refreshView();
  2268. },
  2269. error: (error: any) => {
  2270. console.error('加载更多失败:', error);
  2271. this.isSearching = false;
  2272. let errorMessage = '加载更多失败,请稍后重试';
  2273. if (error.status === 401) {
  2274. errorMessage = '认证失败,Token可能已失效';
  2275. } else if (error.status === 429) {
  2276. errorMessage = '请求过于频繁,请稍后重试';
  2277. } else if (error.status === 0) {
  2278. errorMessage = '网络连接失败,请检查网络设置';
  2279. }
  2280. alert(errorMessage);
  2281. }
  2282. });
  2283. }
  2284. // 查看视频详情
  2285. viewVideoDetail(video: VideoInfo): void {
  2286. this.openSearchVideoPreview(video, null, '', true);
  2287. this.douyinService.getVideoDetail(video.aweme_id).subscribe({
  2288. next: (res: any) => {
  2289. const detailData = this.douyinService.extractVideoDetailData(res) || {};
  2290. this.openSearchVideoPreview(video, detailData, this.douyinService.extractVideoPreviewUrl(res) || '', false);
  2291. },
  2292. error: (error: any) => {
  2293. console.error('获取视频详情失败:', error);
  2294. this.openSearchVideoPreview(video, null, '', false);
  2295. this.showToast('⚠️ 获取实时详情失败,已展示基础信息', 'warn');
  2296. }
  2297. });
  2298. }
  2299. private openSearchVideoPreview(video: VideoInfo, detailData: any, previewUrl: string, loading: boolean = false): void {
  2300. const info = detailData || {};
  2301. const tags = this.extractVideoTags(info, video.text_extra || []);
  2302. const rawDuration = info.video?.duration || info.duration || video.duration || 0;
  2303. const duration = Math.floor(rawDuration / (rawDuration > 1000 ? 1000 : 1));
  2304. const coverCandidates = detailData ? this.buildCoverCandidates(info) : [];
  2305. const poster = coverCandidates[0] || video.cover_url || this.getVideoCoverFallback();
  2306. const createTime = info.create_time ? new Date(info.create_time * 1000) : undefined;
  2307. const filename = this.buildVideoFilename(video);
  2308. this.previewVideoUrl = previewUrl ? this.buildVideoProxyUrl(previewUrl, filename) : '';
  2309. this.previewDownloadUrl = '';
  2310. this.previewVideoTitle = info.desc || video.desc || video.aweme_id;
  2311. this.previewSourceVideo = video;
  2312. this.previewVideoInfo = {
  2313. duration: duration || video.duration || 0,
  2314. resolution: info.video?.ratio || '',
  2315. format: 'mp4',
  2316. source: 'douyin',
  2317. description: info.desc || video.desc || '',
  2318. tags,
  2319. created_at: createTime,
  2320. poster,
  2321. authorName: info.author?.nickname || video.author.nickname || '',
  2322. playCount: info.statistics?.play_count ?? video.statistics.play_count,
  2323. diggCount: info.statistics?.digg_count ?? video.statistics.digg_count,
  2324. commentCount: info.statistics?.comment_count ?? video.statistics.comment_count,
  2325. shareCount: info.statistics?.share_count ?? video.statistics.share_count,
  2326. loading
  2327. };
  2328. this.showPreviewModal = true;
  2329. this.refreshView();
  2330. }
  2331. private extractVideoTags(info: any, fallbackTags: string[] = []): string[] {
  2332. const textExtraTags = Array.isArray(info?.text_extra)
  2333. ? info.text_extra
  2334. .map((tag: any) => tag?.hashtag_name || tag?.cha_name || tag?.tag_name || tag?.hash_tag_name || tag)
  2335. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  2336. : [];
  2337. const chaListTags = Array.isArray(info?.cha_list)
  2338. ? info.cha_list
  2339. .map((tag: any) => tag?.cha_name || tag?.hashtag_name || tag?.tag_name || tag)
  2340. .filter((tag: any) => typeof tag === 'string' && tag.trim())
  2341. : [];
  2342. return [...textExtraTags, ...chaListTags, ...fallbackTags].filter((tag, index, list) => !!tag && list.indexOf(tag) === index);
  2343. }
  2344. private buildVideoFilename(video: VideoInfo): string {
  2345. return `${video.author.nickname}_${video.desc || video.aweme_id}`
  2346. .replace(/[<>:"/\\|?*]/g, '_')
  2347. .substring(0, 60) + '.mp4';
  2348. }
  2349. private buildVideoProxyUrl(videoUrl: string, filename: string, download: boolean = false): string {
  2350. const params = new URLSearchParams({
  2351. url: videoUrl,
  2352. filename,
  2353. download: download ? '1' : '0'
  2354. });
  2355. return `/backend/api/video-proxy?${params.toString()}`;
  2356. }
  2357. // 下载抖音视频到本地
  2358. downloadVideo(video: VideoInfo): void {
  2359. if (video.isDownloading) return;
  2360. video.isDownloading = true;
  2361. video.downloadProgress = 0;
  2362. // 先获取视频详情拿到下载地址
  2363. this.douyinService.getVideoDetail(video.aweme_id).subscribe({
  2364. next: (res: any) => {
  2365. const detailData = this.douyinService.extractVideoDetailData(res) || {};
  2366. const downloadUrls = this.douyinService.extractVideoDownloadUrls(res);
  2367. const downloadUrl = downloadUrls[0] || '';
  2368. if (!downloadUrl) {
  2369. console.warn('未找到可用下载地址:', detailData);
  2370. video.isDownloading = false;
  2371. this.showToast('❌ 无法获取下载地址,请稍后重试', 'error');
  2372. return;
  2373. }
  2374. const filename = this.buildVideoFilename(video);
  2375. this.douyinService.startManagedDownload({
  2376. url: downloadUrl,
  2377. urls: downloadUrls,
  2378. filename,
  2379. title: video.desc || video.aweme_id,
  2380. description: detailData?.desc || video.desc || '',
  2381. tags: video.text_extra || [],
  2382. thumbnail: video.cover_url || '',
  2383. duration: video.duration || 0,
  2384. resolution: detailData?.video?.ratio || '',
  2385. awemeId: video.aweme_id,
  2386. authorName: video.author.nickname || ''
  2387. }).subscribe({
  2388. next: (taskRes: any) => {
  2389. if (!taskRes?.taskId) {
  2390. video.isDownloading = false;
  2391. video.downloadProgress = 0;
  2392. this.showToast('❌ 下载任务创建失败,请稍后重试', 'error');
  2393. return;
  2394. }
  2395. this.showToast(`📥 正在下载「${video.desc || video.aweme_id}」到视频库`, 'info');
  2396. this.pollManagedDownload(video, taskRes.taskId);
  2397. },
  2398. error: (error: any) => {
  2399. console.error('创建下载任务失败:', error);
  2400. video.isDownloading = false;
  2401. video.downloadProgress = 0;
  2402. this.showToast(`❌ 创建下载任务失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  2403. }
  2404. });
  2405. },
  2406. error: (error: any) => {
  2407. console.error('获取视频信息失败:', error);
  2408. video.isDownloading = false;
  2409. this.showToast(`❌ 获取视频信息失败:${error?.error?.error || error?.message || '请稍后重试'}`, 'error');
  2410. }
  2411. });
  2412. }
  2413. downloadPreviewVideo(): void {
  2414. if (!this.previewSourceVideo) {
  2415. return;
  2416. }
  2417. this.downloadVideo(this.previewSourceVideo);
  2418. }
  2419. private pollManagedDownload(video: VideoInfo, taskId: string, retryCount: number = 0): void {
  2420. this.douyinService.getManagedDownloadTask(taskId).subscribe({
  2421. next: (task: any) => {
  2422. video.downloadProgress = task?.progress || 0;
  2423. if (task?.status === 'completed') {
  2424. video.isDownloading = false;
  2425. video.downloadProgress = 100;
  2426. this.loadVideoManifest();
  2427. this.showToast(`✅ 视频「${video.desc || video.aweme_id}」已下载到本地视频库`, 'success');
  2428. this.refreshView();
  2429. return;
  2430. }
  2431. if (task?.status === 'failed') {
  2432. video.isDownloading = false;
  2433. video.downloadProgress = 0;
  2434. this.showToast(`❌ 下载失败:${task?.error || '请稍后重试'}`, 'error');
  2435. this.refreshView();
  2436. return;
  2437. }
  2438. this.refreshView();
  2439. setTimeout(() => this.pollManagedDownload(video, taskId), 1000);
  2440. },
  2441. error: (error: any) => {
  2442. console.error('查询下载任务失败:', error);
  2443. if (retryCount < 3) {
  2444. setTimeout(() => this.pollManagedDownload(video, taskId, retryCount + 1), 1500);
  2445. return;
  2446. }
  2447. video.isDownloading = false;
  2448. video.downloadProgress = 0;
  2449. this.showToast('❌ 下载状态查询失败,请稍后重试', 'error');
  2450. this.refreshView();
  2451. }
  2452. });
  2453. }
  2454. private pollMonitorWorkDownload(work: MonitorWork, taskId: string, retryCount: number = 0): void {
  2455. this.douyinService.getManagedDownloadTask(taskId).subscribe({
  2456. next: (task: any) => {
  2457. work.downloadProgress = task?.progress || 0;
  2458. if (task?.status === 'completed') {
  2459. work.isDownloading = false;
  2460. work.downloadProgress = 100;
  2461. this.loadVideoManifest();
  2462. this.showToast(`✅ 视频「${work.desc || work.id}」已下载到本地视频库`, 'success');
  2463. this.refreshView();
  2464. return;
  2465. }
  2466. if (task?.status === 'failed') {
  2467. work.isDownloading = false;
  2468. work.downloadProgress = 0;
  2469. this.showToast(`❌ 下载失败:${task?.error || '请稍后重试'}`, 'error');
  2470. this.refreshView();
  2471. return;
  2472. }
  2473. this.refreshView();
  2474. setTimeout(() => this.pollMonitorWorkDownload(work, taskId), 1000);
  2475. },
  2476. error: () => {
  2477. if (retryCount < 3) {
  2478. setTimeout(() => this.pollMonitorWorkDownload(work, taskId, retryCount + 1), 1500);
  2479. return;
  2480. }
  2481. work.isDownloading = false;
  2482. work.downloadProgress = 0;
  2483. this.showToast('❌ 下载状态查询失败,请稍后重试', 'error');
  2484. this.refreshView();
  2485. }
  2486. });
  2487. }
  2488. private buildMonitorVideoInfo(author: MonitorAuthor, work: MonitorWork): VideoInfo {
  2489. return {
  2490. aweme_id: work.id,
  2491. desc: work.desc,
  2492. cover_url: work.coverUrl,
  2493. cover_candidates: work.coverCandidates,
  2494. duration: work.duration,
  2495. create_time: work.createTime ? Math.floor(work.createTime.getTime() / 1000) : 0,
  2496. author: {
  2497. nickname: author.nickname,
  2498. sec_uid: author.secUserId
  2499. },
  2500. statistics: {
  2501. play_count: 0,
  2502. digg_count: work.statistics.digg_count,
  2503. comment_count: work.statistics.comment_count,
  2504. share_count: work.statistics.share_count
  2505. },
  2506. text_extra: [],
  2507. downloadProgress: work.downloadProgress,
  2508. isDownloading: work.isDownloading
  2509. };
  2510. }
  2511. // 开始AI生成
  2512. startAIGeneration(video: VideoInfo): void {
  2513. console.log('开始AI生成:', video);
  2514. // 创建新任务
  2515. const newTask: Task = {
  2516. id: `TASK-${Date.now()}`,
  2517. keyword: this.searchKeyword,
  2518. status: 'pending',
  2519. step: 'search',
  2520. progress: 0,
  2521. cost: 0,
  2522. created_at: new Date(),
  2523. updated_at: new Date(),
  2524. original_video_title: video.desc
  2525. };
  2526. this.activeTasks.unshift(newTask);
  2527. this.setCurrentTab('tasks');
  2528. // 模拟任务进度更新
  2529. this.simulateTaskProgress(newTask.id);
  2530. }
  2531. // 模拟任务进度
  2532. private simulateTaskProgress(taskId: string): void {
  2533. const task = this.activeTasks.find(t => t.id === taskId);
  2534. if (!task) return;
  2535. const steps: Task['step'][] = ['search', 'detail', 'download', 'transcribe', 'generate'];
  2536. let currentStepIndex = 0;
  2537. const interval = setInterval(() => {
  2538. if (currentStepIndex < steps.length) {
  2539. task.step = steps[currentStepIndex];
  2540. task.progress = Math.min((currentStepIndex + 1) * 20, 100);
  2541. task.status = currentStepIndex === steps.length - 1 ? 'completed' : 'processing';
  2542. task.updated_at = new Date();
  2543. currentStepIndex++;
  2544. } else {
  2545. task.status = 'completed';
  2546. task.progress = 100;
  2547. clearInterval(interval);
  2548. // 添加到生成结果
  2549. this.generatedResults.unshift({
  2550. id: `RESULT-${Date.now()}`,
  2551. type: 'video',
  2552. url: 'https://example.com/generated-video.mp4',
  2553. title: `AI重塑 - ${task.keyword}`,
  2554. created_at: new Date(),
  2555. quality: '1080P',
  2556. duration: '2分钟',
  2557. cost: 2.5
  2558. });
  2559. }
  2560. }, 2000);
  2561. }
  2562. // 获取任务状态颜色
  2563. getTaskStatusColor(status: string): string {
  2564. switch (status) {
  2565. case 'pending': return 'warn';
  2566. case 'processing': return 'accent';
  2567. case 'completed': return 'primary';
  2568. case 'failed': return 'warn';
  2569. default: return '';
  2570. }
  2571. }
  2572. // 获取任务状态文本
  2573. getTaskStatusText(status: string): string {
  2574. switch (status) {
  2575. case 'pending': return '等待中';
  2576. case 'processing': return '处理中';
  2577. case 'completed': return '已完成';
  2578. case 'failed': return '失败';
  2579. case 'timeout': return '超时';
  2580. default: return status;
  2581. }
  2582. }
  2583. // 获取任务步骤文本
  2584. getTaskStepText(step: string): string {
  2585. switch (step) {
  2586. case 'search': return '视频搜索';
  2587. case 'detail': return '详情获取';
  2588. case 'download': return '视频下载';
  2589. case 'transcribe': return '语音转文字';
  2590. case 'generate': return 'AI生成';
  2591. case 'complete': return '完成';
  2592. case 'vg-upload': return '上传视频';
  2593. case 'vg-analyze': return '视频解析';
  2594. case 'vg-script': return '脚本生成';
  2595. case 'vg-image': return '配图生成';
  2596. case 'vg-voice': return '语音配音';
  2597. case 'vg-composite': return '视频合成';
  2598. default: return step;
  2599. }
  2600. }
  2601. // 判断步骤是否完成
  2602. isStepCompleted(currentStep: string, targetStep: string): boolean {
  2603. const steps = ['search', 'detail', 'download', 'transcribe', 'generate'];
  2604. const currentIndex = steps.indexOf(currentStep);
  2605. const targetIndex = steps.indexOf(targetStep);
  2606. return currentIndex > targetIndex;
  2607. }
  2608. // 查看任务详情
  2609. viewTaskDetail(task: Task): void {
  2610. console.log('查看任务详情:', task);
  2611. }
  2612. // 已被用户取消的任务 ID 集合:用于中止后续 vg 流程更新进度时覆盖回 processing 状态
  2613. private canceledTaskIds: Set<string> = new Set<string>();
  2614. // 取消任务(实际生效:标记为 failed 并阻止后续 vg 进度回写;UI 立即刷新)
  2615. cancelTask(task: Task): void {
  2616. if (!task) return;
  2617. task.status = 'failed';
  2618. task.error_message = '用户已取消';
  2619. task.updated_at = new Date();
  2620. if (task.id) this.canceledTaskIds.add(task.id);
  2621. // 若取消的是当前进行中的视频生成任务,清空 vg 运行状态,防止继续触发新请求
  2622. if (task.type === 'video-generation' && this.vgTaskId === task.id) {
  2623. this.vgUploading = false;
  2624. this.vgAnalyzing = false;
  2625. this.vgGeneratingScript = false;
  2626. this.vgGeneratingImages = false;
  2627. this.vgSynthesizing = false;
  2628. this.vgCompositing = false;
  2629. this.vgError = '已取消';
  2630. }
  2631. this.updateTask(task);
  2632. this.updateTaskStats();
  2633. this.refreshView();
  2634. this.showToast('🛑 任务已取消', 'info');
  2635. }
  2636. // 获取状态颜色
  2637. getStatusColor(status: string): string {
  2638. switch (status) {
  2639. case 'completed': return 'primary';
  2640. case 'failed': return 'warn';
  2641. default: return '';
  2642. }
  2643. }
  2644. // 获取状态文本
  2645. getStatusText(status: string): string {
  2646. switch (status) {
  2647. case 'completed': return '已完成';
  2648. case 'failed': return '失败';
  2649. default: return status;
  2650. }
  2651. }
  2652. // 查看历史记录详情
  2653. viewHistoryDetail(record: HistoryRecord): void {
  2654. this.historyDetailRecord = record;
  2655. this.historyDetailSegments = [];
  2656. this.historyDetailPrimaryVideoUrl = this.findHistoryPrimaryVideoUrl(record);
  2657. this.historyDetailLoading = !!record.remixId;
  2658. this.showHistoryDetailModal = true;
  2659. this.refreshView();
  2660. const finalizeHistoryDetail = (remix: any = null) => {
  2661. this.historyDetailSegments = this.buildHistoryDetailSegments(record, remix);
  2662. this.historyDetailPrimaryVideoUrl = this.findHistoryPrimaryVideoUrl(record, remix);
  2663. this.historyDetailLoading = false;
  2664. this.refreshView();
  2665. };
  2666. if (record.remixId && record.videoId) {
  2667. // 从 remix 数据加载片段详情
  2668. this.http.get<any[]>(`/backend/api/remixes/${record.videoId}`).subscribe({
  2669. next: (remixes) => {
  2670. finalizeHistoryDetail(remixes.find(r => r.remixId === record.remixId));
  2671. },
  2672. error: () => {
  2673. finalizeHistoryDetail();
  2674. }
  2675. });
  2676. } else if (record.remixId) {
  2677. // 尝试从所有 remix 数据中查找
  2678. this.http.get<Record<string, any[]>>('/backend/api/remixes').subscribe({
  2679. next: (allRemixes) => {
  2680. let matchedRemix: any = null;
  2681. for (const remixes of Object.values(allRemixes)) {
  2682. const remix = remixes.find(r => r.remixId === record.remixId);
  2683. if (remix) {
  2684. matchedRemix = remix;
  2685. break;
  2686. }
  2687. }
  2688. finalizeHistoryDetail(matchedRemix);
  2689. },
  2690. error: () => {
  2691. finalizeHistoryDetail();
  2692. }
  2693. });
  2694. } else {
  2695. finalizeHistoryDetail();
  2696. }
  2697. }
  2698. closeHistoryDetail(): void {
  2699. this.showHistoryDetailModal = false;
  2700. this.historyDetailRecord = null;
  2701. this.historyDetailSegments = [];
  2702. this.historyDetailPrimaryVideoUrl = '';
  2703. this.historyDetailLoading = false;
  2704. }
  2705. private findGeneratedResultForHistory(record: HistoryRecord): GeneratedResult | undefined {
  2706. return this.generatedResults.find((result) => {
  2707. if (record.remixId && result.remixId === record.remixId) return true;
  2708. if (record.resultUrl && result.url === record.resultUrl) return true;
  2709. if (record.videoId && result.videoId === record.videoId && record.styleName) {
  2710. return result.title?.includes(record.styleName);
  2711. }
  2712. return false;
  2713. });
  2714. }
  2715. private findHistoryPrimaryVideoUrl(record: HistoryRecord, remix?: any): string {
  2716. const result = this.findGeneratedResultForHistory(record);
  2717. return record.resultUrl
  2718. || remix?.stitchUrl
  2719. || result?.url
  2720. || remix?.segments?.find((segment: any) => segment?.videoUrl)?.videoUrl
  2721. || result?.segments?.find((segment: any) => segment?.videoUrl)?.videoUrl
  2722. || '';
  2723. }
  2724. private buildHistoryDetailSegments(record: HistoryRecord, remix?: any): { id: string; videoUrl: string; prompt: string; status: string; narration?: string }[] {
  2725. const remixSegments = Array.isArray(remix?.segments) ? remix.segments : [];
  2726. const resultSegments = Array.isArray(this.findGeneratedResultForHistory(record)?.segments)
  2727. ? this.findGeneratedResultForHistory(record)?.segments || []
  2728. : [];
  2729. const sourceSegments = remixSegments.length > 0 ? remixSegments : resultSegments;
  2730. return sourceSegments.map((segment: any, index: number) => ({
  2731. id: segment?.id || `SEG-${index + 1}`,
  2732. videoUrl: segment?.videoUrl || '',
  2733. prompt: segment?.prompt || '',
  2734. status: segment?.status || 'completed',
  2735. narration: segment?.narration || segment?.prompt || ''
  2736. }));
  2737. }
  2738. // 重新生成任务
  2739. regenerateTask(record: HistoryRecord): void {
  2740. console.log('重新生成任务:', record);
  2741. this.searchKeyword = record.keyword;
  2742. this.setCurrentTab('search');
  2743. }
  2744. // 导出历史记录
  2745. exportHistory(): void {
  2746. const dataStr = JSON.stringify(this.historyRecords, null, 2);
  2747. const dataBlob = new Blob([dataStr], { type: 'application/json' });
  2748. const link = document.createElement('a');
  2749. link.href = URL.createObjectURL(dataBlob);
  2750. link.download = `history-${Date.now()}.json`;
  2751. link.click();
  2752. }
  2753. // 预览结果
  2754. previewResult(result: GeneratedResult): void {
  2755. if (result.type === 'video') {
  2756. this.previewVideoUrl = result.url;
  2757. this.previewDownloadUrl = result.url;
  2758. this.previewVideoTitle = result.title;
  2759. this.previewSourceVideo = null;
  2760. this.previewVideoInfo = {
  2761. quality: result.quality,
  2762. duration: result.duration,
  2763. cost: result.cost,
  2764. created_at: result.created_at
  2765. };
  2766. this.showPreviewModal = true;
  2767. } else {
  2768. window.open(result.url, '_blank');
  2769. }
  2770. }
  2771. // 下载结果
  2772. downloadResult(result: GeneratedResult): void {
  2773. console.log('下载结果:', result);
  2774. const link = document.createElement('a');
  2775. link.href = result.url;
  2776. link.download = `${result.title}.${result.type === 'video' ? 'mp4' : 'jpg'}`;
  2777. link.click();
  2778. }
  2779. // 分享结果
  2780. shareResult(result: GeneratedResult): void {
  2781. if (navigator.share) {
  2782. navigator.share({
  2783. title: result.title,
  2784. text: '查看这个由AI生成的精彩内容!',
  2785. url: result.url
  2786. });
  2787. } else {
  2788. navigator.clipboard.writeText(result.url).then(() => {
  2789. alert('链接已复制到剪贴板');
  2790. });
  2791. }
  2792. }
  2793. // 视频管理相关方法
  2794. // 获取过滤后的视频列表
  2795. getFilteredVideos(): ManagedVideo[] {
  2796. return this.managedVideos.filter(video => {
  2797. const matchesCategory = !this.videoFilter.category || video.category === this.videoFilter.category;
  2798. const matchesSource = !this.videoFilter.source || video.source === this.videoFilter.source;
  2799. const matchesSearch = !this.videoFilter.searchTerm ||
  2800. video.title.toLowerCase().includes(this.videoFilter.searchTerm.toLowerCase()) ||
  2801. video.description.toLowerCase().includes(this.videoFilter.searchTerm.toLowerCase()) ||
  2802. video.tags.some(tag => tag.toLowerCase().includes(this.videoFilter.searchTerm.toLowerCase()));
  2803. return matchesCategory && matchesSource && matchesSearch;
  2804. });
  2805. }
  2806. // 切换视频选择
  2807. toggleVideoSelection(videoId: string): void {
  2808. if (this.selectedVideos.has(videoId)) {
  2809. this.selectedVideos.delete(videoId);
  2810. } else {
  2811. this.selectedVideos.add(videoId);
  2812. }
  2813. }
  2814. // 获取视频可播放 URL(用于封面截帧等)
  2815. getVideoPlayUrl(video: ManagedVideo): string {
  2816. if (!video) return '';
  2817. // 远程 URL(生成的视频)
  2818. if (video.filepath && /^https?:\/\//.test(video.filepath)) return video.filepath;
  2819. // 本地文件
  2820. if (video.filepath) return video.filepath;
  2821. if (video.filename) return `/backend/api/video/${video.filename}`;
  2822. return '';
  2823. }
  2824. // 获取来源文本
  2825. getSourceText(source: string): string {
  2826. switch (source) {
  2827. case 'downloaded': return '下载';
  2828. case 'generated': return 'AI生成';
  2829. case 'uploaded': return '上传';
  2830. default: return source;
  2831. }
  2832. }
  2833. // 获取分类名称
  2834. getCategoryName(categoryId: string): string {
  2835. const category = this.videoCategories.find(cat => cat.id === categoryId);
  2836. return category ? category.name : '未分类';
  2837. }
  2838. // 获取分类颜色
  2839. getCategoryColor(categoryId: string): string {
  2840. const category = this.videoCategories.find(cat => cat.id === categoryId);
  2841. return category ? category.color : '#757575';
  2842. }
  2843. // 预览视频
  2844. previewVideo(video: ManagedVideo): void {
  2845. this.previewVideoUrl = video.filepath;
  2846. this.previewDownloadUrl = video.filepath;
  2847. this.previewVideoTitle = video.title;
  2848. this.previewSourceVideo = null;
  2849. this.previewVideoInfo = {
  2850. filename: video.filename,
  2851. size: video.size,
  2852. duration: video.duration,
  2853. resolution: video.metadata?.resolution || '',
  2854. format: video.metadata?.format || 'mp4',
  2855. source: video.source,
  2856. description: video.description,
  2857. tags: video.tags,
  2858. created_at: video.created_at
  2859. };
  2860. this.showPreviewModal = true;
  2861. }
  2862. // 关闭预览
  2863. closePreview(): void {
  2864. this.showPreviewModal = false;
  2865. this.previewVideoUrl = '';
  2866. this.previewDownloadUrl = '';
  2867. this.previewVideoTitle = '';
  2868. this.previewVideoInfo = null;
  2869. this.previewSourceVideo = null;
  2870. }
  2871. // 编辑视频
  2872. editVideo(video: ManagedVideo): void {
  2873. console.log('编辑视频:', video);
  2874. // 这里可以打开视频编辑模态框
  2875. const newTitle = prompt('编辑视频标题:', video.title);
  2876. if (newTitle && newTitle !== video.title) {
  2877. video.title = newTitle;
  2878. video.modified_at = new Date();
  2879. console.log('视频标题已更新');
  2880. }
  2881. }
  2882. // 删除单个视频
  2883. deleteVideo(video: ManagedVideo): void {
  2884. if (confirm(`确定要删除视频「${video.title}」吗?`)) {
  2885. this.http.delete<any>(`/backend/api/manifest/${video.id}`).subscribe({
  2886. next: () => {
  2887. this.managedVideos = this.managedVideos.filter(v => v.id !== video.id);
  2888. this.selectedVideos.delete(video.id);
  2889. this.updateCategoryCounts();
  2890. this.showToast(`🗑️ 视频「${video.title}」已删除`, 'success');
  2891. this.refreshView();
  2892. console.log('视频已删除:', video.title);
  2893. },
  2894. error: (err) => {
  2895. const message = err?.error?.error || '删除视频失败';
  2896. this.showToast(`❌ ${message}`, 'error');
  2897. console.warn('⚠️ 删除视频失败:', err);
  2898. this.refreshView();
  2899. }
  2900. });
  2901. }
  2902. }
  2903. // 批量删除视频
  2904. batchDelete(): void {
  2905. if (this.selectedVideos.size === 0) return;
  2906. if (confirm(`确定要删除选中的 ${this.selectedVideos.size} 个视频吗?`)) {
  2907. const selectedIds = Array.from(this.selectedVideos);
  2908. const selectedVideos = this.managedVideos.filter(v => this.selectedVideos.has(v.id));
  2909. let completed = 0;
  2910. let successCount = 0;
  2911. selectedVideos.forEach((video) => {
  2912. this.http.delete<any>(`/backend/api/manifest/${video.id}`).subscribe({
  2913. next: () => {
  2914. successCount += 1;
  2915. this.managedVideos = this.managedVideos.filter(v => v.id !== video.id);
  2916. this.selectedVideos.delete(video.id);
  2917. completed += 1;
  2918. if (completed === selectedIds.length) {
  2919. this.isSelectionMode = false;
  2920. this.selectedVideos.clear();
  2921. this.updateCategoryCounts();
  2922. this.showToast(`🗑️ 已删除 ${successCount} 个视频`, 'success');
  2923. this.refreshView();
  2924. console.log('批量视频已删除');
  2925. }
  2926. },
  2927. error: (err) => {
  2928. completed += 1;
  2929. console.warn(`⚠️ 删除视频失败: ${video.title}`, err);
  2930. if (completed === selectedIds.length) {
  2931. this.isSelectionMode = false;
  2932. this.selectedVideos.clear();
  2933. this.updateCategoryCounts();
  2934. if (successCount > 0) {
  2935. this.showToast(`⚠️ 部分删除成功,已删除 ${successCount}/${selectedIds.length} 个视频`, 'warn');
  2936. } else {
  2937. const message = err?.error?.error || '批量删除失败';
  2938. this.showToast(`❌ ${message}`, 'error');
  2939. }
  2940. this.refreshView();
  2941. }
  2942. }
  2943. });
  2944. });
  2945. }
  2946. }
  2947. // 批量导出视频
  2948. batchExport(): void {
  2949. if (this.selectedVideos.size === 0) return;
  2950. const selectedVideos = this.managedVideos.filter(v => this.selectedVideos.has(v.id));
  2951. console.log('批量导出视频:', selectedVideos.map(v => v.title));
  2952. alert(`正在导出 ${selectedVideos.length} 个视频...`);
  2953. }
  2954. // 批量分类
  2955. batchCategorize(): void {
  2956. if (this.selectedVideos.size === 0) return;
  2957. const categoryId = prompt(`选择分类:\n${this.videoCategories.map((cat, index) =>
  2958. `${index + 1}. ${cat.name}`).join('\n')}`);
  2959. if (categoryId) {
  2960. const categoryIndex = parseInt(categoryId) - 1;
  2961. if (categoryIndex >= 0 && categoryIndex < this.videoCategories.length) {
  2962. const selectedCategory = this.videoCategories[categoryIndex];
  2963. this.managedVideos.forEach(video => {
  2964. if (this.selectedVideos.has(video.id)) {
  2965. video.category = selectedCategory.id;
  2966. video.modified_at = new Date();
  2967. }
  2968. });
  2969. this.updateCategoryCounts();
  2970. this.selectedVideos.clear();
  2971. this.isSelectionMode = false;
  2972. console.log('批量分类完成');
  2973. }
  2974. }
  2975. }
  2976. // 更新分类计数
  2977. private updateCategoryCounts(): void {
  2978. this.videoCategories.forEach(category => {
  2979. category.count = this.managedVideos.filter(video => video.source === category.id || video.category === category.id).length;
  2980. });
  2981. }
  2982. // ==================== 视频上传 ====================
  2983. openUploadModal(): void {
  2984. this.showUploadModal = true;
  2985. this.uploadTitle = '';
  2986. this.uploadDescription = '';
  2987. this.uploadTags = '';
  2988. this.uploadFile = null;
  2989. this.uploadFileName = '';
  2990. this.uploadProgress = 0;
  2991. this.uploadError = '';
  2992. this.isUploading = false;
  2993. }
  2994. closeUploadModal(): void {
  2995. if (this.isUploading) return;
  2996. this.showUploadModal = false;
  2997. this.uploadFile = null;
  2998. this.uploadFileName = '';
  2999. }
  3000. onFileSelected(event: Event): void {
  3001. const input = event.target as HTMLInputElement;
  3002. if (input.files && input.files.length > 0) {
  3003. const file = input.files[0];
  3004. const allowedExts = ['.mp4', '.mov', '.avi', '.webm', '.mkv'];
  3005. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  3006. if (!allowedExts.includes(ext)) {
  3007. this.uploadError = '不支持的文件格式,仅支持: mp4, mov, avi, webm, mkv';
  3008. input.value = '';
  3009. return;
  3010. }
  3011. if (file.size > 500 * 1024 * 1024) {
  3012. this.uploadError = '文件大小超过限制(最大 500MB)';
  3013. input.value = '';
  3014. return;
  3015. }
  3016. this.uploadFile = file;
  3017. this.uploadFileName = file.name;
  3018. this.uploadError = '';
  3019. // 自动填充标题(去掉扩展名)
  3020. if (!this.uploadTitle) {
  3021. this.uploadTitle = file.name.replace(/\.[^.]+$/, '');
  3022. }
  3023. }
  3024. }
  3025. uploadVideo(): void {
  3026. if (!this.uploadFile || this.isUploading) return;
  3027. this.isUploading = true;
  3028. this.uploadProgress = 0;
  3029. this.uploadError = '';
  3030. const formData = new FormData();
  3031. formData.append('video', this.uploadFile);
  3032. formData.append('title', this.uploadTitle || this.uploadFile.name.replace(/\.[^.]+$/, ''));
  3033. formData.append('description', this.uploadDescription || '用户上传的视频');
  3034. if (this.uploadTags.trim()) {
  3035. const tagsArr = this.uploadTags.split(/[,,、\s]+/).filter(t => t.trim());
  3036. formData.append('tags', JSON.stringify(tagsArr));
  3037. }
  3038. const xhr = new XMLHttpRequest();
  3039. xhr.open('POST', '/backend/api/upload/video', true);
  3040. xhr.upload.onprogress = (e) => {
  3041. if (e.lengthComputable) {
  3042. this.ngZone.run(() => {
  3043. this.uploadProgress = Math.round((e.loaded / e.total) * 100);
  3044. this.refreshView();
  3045. });
  3046. }
  3047. };
  3048. xhr.onload = () => {
  3049. this.ngZone.run(() => {
  3050. this.isUploading = false;
  3051. if (xhr.status === 200) {
  3052. try {
  3053. const res = JSON.parse(xhr.responseText);
  3054. if (res.success && res.video) {
  3055. this.uploadProgress = 100;
  3056. const newVideo: ManagedVideo = {
  3057. id: res.video.id,
  3058. title: res.video.title,
  3059. filename: res.video.filename,
  3060. filepath: res.filepath || `/backend/api/video/${res.video.filename}`,
  3061. size: res.video.size,
  3062. duration: res.video.duration || 0,
  3063. created_at: new Date(),
  3064. modified_at: new Date(),
  3065. category: 'uploaded',
  3066. tags: res.video.tags || [],
  3067. description: res.video.description || '',
  3068. thumbnail: '',
  3069. source: 'uploaded',
  3070. metadata: res.video.metadata || { resolution: '未知', format: 'mp4' }
  3071. };
  3072. this.managedVideos.unshift(newVideo);
  3073. this.updateCategoryCounts();
  3074. this.showUploadModal = false;
  3075. this.uploadFile = null;
  3076. this.uploadFileName = '';
  3077. this.showToast(`✅ 视频「${newVideo.title}」上传成功!`, 'success');
  3078. console.log('📤 视频上传成功:', newVideo);
  3079. } else {
  3080. this.uploadError = res.error || '上传失败';
  3081. }
  3082. } catch {
  3083. this.uploadError = '解析响应失败';
  3084. }
  3085. } else {
  3086. try {
  3087. const errRes = JSON.parse(xhr.responseText);
  3088. this.uploadError = errRes.error || `上传失败 (${xhr.status})`;
  3089. } catch {
  3090. this.uploadError = `上传失败 (HTTP ${xhr.status})`;
  3091. }
  3092. }
  3093. this.refreshView();
  3094. });
  3095. };
  3096. xhr.onerror = () => {
  3097. this.ngZone.run(() => {
  3098. this.isUploading = false;
  3099. this.uploadError = '网络错误,请检查后端服务是否运行';
  3100. this.refreshView();
  3101. });
  3102. };
  3103. xhr.send(formData);
  3104. }
  3105. // ==================== AI重塑 — 多步骤流程 ====================
  3106. // Step 1: 打开AI重塑模态框
  3107. aiRemixVideo(video: ManagedVideo): void {
  3108. if (video.isRemixing) return;
  3109. this.remixTargetVideo = video;
  3110. this.remixStep = 1;
  3111. this.remixTranscript = '';
  3112. this.remixBeautifiedTranscript = '';
  3113. this.remixStoryboard = [];
  3114. this.remixStyle = 'anime';
  3115. this.remixQuality = '720p';
  3116. this.remixFrames = 121;
  3117. this.remixAspectRatio = '16:9';
  3118. this.remixStatusText = '';
  3119. this.isRemixSubmitting = false;
  3120. this.remixResults = { total: 0, success: 0, failed: 0 };
  3121. this.remixStitchStatus = 'idle';
  3122. this.remixStitchUrl = '';
  3123. this.remixStitchError = '';
  3124. this.remixFinalVideoUrl = '';
  3125. this.remixMode = 'standard';
  3126. this.resetDigitalHumanState();
  3127. this.isWhisperRunning = false;
  3128. this.whisperStatusText = '';
  3129. this.showManualTranscriptInput = false;
  3130. this.showRemixModal = true;
  3131. // 自动尝试加载Whisper处理后的文件
  3132. this.loadWhisperFiles(video);
  3133. }
  3134. // 关闭重塑模态框
  3135. closeRemixModal(): void {
  3136. if (this.isRemixSubmitting) return;
  3137. this.showRemixModal = false;
  3138. this.remixTargetVideo = null;
  3139. this.resetDigitalHumanState();
  3140. }
  3141. // ========== AI重塑模式选择弹窗 ==========
  3142. openRemixModeChooser(video: ManagedVideo): void {
  3143. if (!video || video.isRemixing) return;
  3144. this.remixModeChooserVideo = video;
  3145. this.showRemixModeChooser = true;
  3146. }
  3147. closeRemixModeChooser(): void {
  3148. this.showRemixModeChooser = false;
  3149. this.remixModeChooserVideo = null;
  3150. }
  3151. selectRemixMode(mode: 'standard' | 'digital-human'): void {
  3152. const video = this.remixModeChooserVideo;
  3153. this.showRemixModeChooser = false;
  3154. this.remixModeChooserVideo = null;
  3155. if (!video) return;
  3156. if (mode === 'digital-human') {
  3157. // 数字人生成:跳转到数字人合成页,并把该视频作为「参考视频」自动加载 + 分析
  3158. this.setCurrentTab('digital-human');
  3159. this.startDhRefFromManagedVideo(video);
  3160. return;
  3161. }
  3162. // 标准AI重塑:跳转到视频生成页,并将该视频作为已上传文件自动完成第一步
  3163. this.setCurrentTab('video-generation');
  3164. this.startVgFromManagedVideo(video);
  3165. }
  3166. private async startVgFromManagedVideo(video: ManagedVideo): Promise<void> {
  3167. try {
  3168. this.vgReset();
  3169. const playUrl = this.getVideoPlayUrl(video);
  3170. const displayName = video.title || video.filename || `video-${video.id}`;
  3171. // 优先把已存在的视频抓取为 File 对象,便于 ≤20MB 走 Gemini 直接识别
  3172. let file: File | null = null;
  3173. if (playUrl) {
  3174. try {
  3175. const resp = await fetch(playUrl);
  3176. if (resp.ok) {
  3177. const blob = await resp.blob();
  3178. const mime = blob.type || 'video/mp4';
  3179. const fileName = video.filename || `${displayName}.mp4`;
  3180. file = new File([blob], fileName, { type: mime });
  3181. }
  3182. } catch (err) {
  3183. console.warn('从已存在视频构造 File 失败,将走音频提取链路:', err);
  3184. }
  3185. }
  3186. this.vgSourceFile = file;
  3187. this.vgSourceFileName = displayName;
  3188. this.vgSourceVideoUrl = playUrl;
  3189. this.vgVideoId = video.id;
  3190. this.vgStep = 2;
  3191. this.vgUploading = false;
  3192. this.vgUploadProgress = 100;
  3193. this.vgError = '';
  3194. // 复用上传成功后的后续流程:建任务 + 启动解析
  3195. this.vgCreateTask();
  3196. this.vgUpdateTaskProgress('vg-analyze', 15);
  3197. this.vgStartAnalysis();
  3198. this.cdr.detectChanges();
  3199. } catch (err: any) {
  3200. console.error('启动标准AI重塑失败:', err);
  3201. this.showToast(`❌ 启动标准AI重塑失败:${err?.message || '请重试'}`, 'error');
  3202. }
  3203. }
  3204. // ========================================================================
  3205. // 数字人合成页:参考视频(独立的上传 + 分析流程,与 vg* 完全隔离)
  3206. // ========================================================================
  3207. // 选择本地参考视频文件
  3208. dhRefSelectFile(event: Event): void {
  3209. const input = event.target as HTMLInputElement;
  3210. const file = input?.files?.[0];
  3211. if (!file) return;
  3212. if (!file.type.startsWith('video/')) {
  3213. this.showToast('请选择视频文件', 'warn');
  3214. return;
  3215. }
  3216. this.dhRefRevokeUrl();
  3217. this.dhRefFile = file;
  3218. this.dhRefFileName = file.name;
  3219. this.dhRefFileSize = file.size;
  3220. this.dhRefVideoUrl = URL.createObjectURL(file);
  3221. this.dhRefVideoId = '';
  3222. this.dhRefError = '';
  3223. this.dhRefTranscript = '';
  3224. this.dhRefAnalysisText = '';
  3225. this.refreshView();
  3226. }
  3227. // 清除参考视频与重塑状态
  3228. dhRefClear(): void {
  3229. this.dhRefRevokeUrl();
  3230. this.dhRefFile = null;
  3231. this.dhRefFileName = '';
  3232. this.dhRefFileSize = 0;
  3233. this.dhRefVideoUrl = '';
  3234. this.dhRefVideoId = '';
  3235. this.dhRefUploading = false;
  3236. this.dhRefUploadProgress = 0;
  3237. this.dhRefAnalyzing = false;
  3238. this.dhRefAnalysisText = '';
  3239. this.dhRefTranscript = '';
  3240. this.dhRefError = '';
  3241. this.dhRefRewriting = false;
  3242. this.dhRefRewriteError = '';
  3243. this.dhRefAutoRewrite = false;
  3244. this.refreshView();
  3245. }
  3246. private dhRefRevokeUrl(): void {
  3247. if (this.dhRefVideoUrl && this.dhRefVideoUrl.startsWith('blob:')) {
  3248. try { URL.revokeObjectURL(this.dhRefVideoUrl); } catch {}
  3249. }
  3250. }
  3251. // 从视频管理页选中视频后进入:直接复用已存在的视频文件,跳过上传,自动开始分析 + 重塑
  3252. private async startDhRefFromManagedVideo(video: ManagedVideo): Promise<void> {
  3253. try {
  3254. this.dhRefClear();
  3255. this.dhRefAutoRewrite = true;
  3256. const playUrl = this.getVideoPlayUrl(video);
  3257. const displayName = video.title || video.filename || `video-${video.id}`;
  3258. // 优先把已存在视频抓为 File(≤20MB 可走 Gemini 直传)
  3259. let file: File | null = null;
  3260. if (playUrl) {
  3261. try {
  3262. const resp = await fetch(playUrl);
  3263. if (resp.ok) {
  3264. const blob = await resp.blob();
  3265. const mime = blob.type || 'video/mp4';
  3266. const fileName = video.filename || `${displayName}.mp4`;
  3267. file = new File([blob], fileName, { type: mime });
  3268. }
  3269. } catch (err) {
  3270. console.warn('⚠️ 数字人参考视频:从已存在视频构造 File 失败:', err);
  3271. }
  3272. }
  3273. this.dhRefFile = file;
  3274. this.dhRefFileName = displayName;
  3275. this.dhRefFileSize = file ? file.size : 0;
  3276. this.dhRefVideoUrl = playUrl || '';
  3277. this.dhRefVideoId = video.id;
  3278. this.dhRefError = '';
  3279. this.refreshView();
  3280. this.dhRefStartAnalysis();
  3281. } catch (err: any) {
  3282. console.error('启动数字人参考视频失败:', err);
  3283. this.showToast(`❌ 启动数字人参考视频失败:${err?.message || '请重试'}`, 'error');
  3284. }
  3285. }
  3286. // 上传本地参考视频,再触发分析
  3287. dhRefUploadAndAnalyze(): void {
  3288. if (!this.dhRefFile || this.dhRefUploading) return;
  3289. this.dhRefUploading = true;
  3290. this.dhRefUploadProgress = 0;
  3291. this.dhRefError = '';
  3292. this.refreshView();
  3293. const formData = new FormData();
  3294. formData.append('video', this.dhRefFile);
  3295. formData.append('title', `数字人参考视频 - ${new Date().toLocaleString('zh-CN')}`);
  3296. const xhr = new XMLHttpRequest();
  3297. xhr.open('POST', '/backend/api/upload/video');
  3298. xhr.upload.onprogress = (e) => {
  3299. if (e.lengthComputable) {
  3300. this.dhRefUploadProgress = Math.round((e.loaded / e.total) * 100);
  3301. this.cdr.detectChanges();
  3302. }
  3303. };
  3304. xhr.onload = () => {
  3305. this.ngZone.run(() => {
  3306. this.dhRefUploading = false;
  3307. if (xhr.status === 200) {
  3308. try {
  3309. const res = JSON.parse(xhr.responseText);
  3310. if (res?.success && res?.video?.id) {
  3311. this.dhRefVideoId = res.video.id;
  3312. this.dhRefStartAnalysis();
  3313. } else {
  3314. this.dhRefError = '上传返回异常';
  3315. }
  3316. } catch { this.dhRefError = '解析上传结果失败'; }
  3317. } else {
  3318. this.dhRefError = `上传失败 (${xhr.status})`;
  3319. }
  3320. this.cdr.detectChanges();
  3321. });
  3322. };
  3323. xhr.onerror = () => {
  3324. this.ngZone.run(() => {
  3325. this.dhRefUploading = false;
  3326. this.dhRefError = '网络错误,上传失败';
  3327. this.cdr.detectChanges();
  3328. });
  3329. };
  3330. xhr.send(formData);
  3331. }
  3332. // 启动分析:≤20MB 直传 Gemini,>20MB 提取音轨给 Gemini 音频识别,最后降级 Whisper
  3333. private dhRefStartAnalysis(): void {
  3334. this.dhRefAnalyzing = true;
  3335. this.dhRefTranscript = '';
  3336. this.dhRefAnalysisText = '';
  3337. this.refreshView();
  3338. const sizeMB = this.dhRefFile ? this.dhRefFile.size / 1024 / 1024 : 0;
  3339. if (this.dhRefFile && sizeMB <= 20) {
  3340. this.dhRefAnalysisText = `正在将视频 (${sizeMB.toFixed(1)}MB) 发送给 Gemini 进行视频理解...`;
  3341. this.refreshView();
  3342. this.dhRefRunGeminiVideo();
  3343. } else if (this.dhRefVideoId) {
  3344. this.dhRefAnalysisText = `视频 ${sizeMB.toFixed(1)}MB 超过 Gemini 视频限制,正在提取音轨...`;
  3345. this.refreshView();
  3346. this.dhRefRunAudioGemini();
  3347. } else {
  3348. this.dhRefAnalysisText = '使用 Whisper 语音识别...';
  3349. this.refreshView();
  3350. this.dhRefRunWhisperFallback();
  3351. }
  3352. }
  3353. private async dhRefRunGeminiVideo(): Promise<void> {
  3354. try {
  3355. const base64 = await this.llmService.fileToBase64(this.dhRefFile!);
  3356. const mimeType = this.dhRefFile!.type || 'video/mp4';
  3357. const prompt = this.buildAnalysisPrompt('video');
  3358. this.llmService.analyzeVideo(base64, mimeType, prompt, {
  3359. model: 'gemini-2.5-flash',
  3360. generationConfig: { maxOutputTokens: 8192 }
  3361. }).subscribe({
  3362. next: (result) => {
  3363. this.dhRefParseGeminiResult(result);
  3364. this.dhRefAnalyzing = false;
  3365. this.refreshView();
  3366. this.dhRefMaybeAutoRewrite();
  3367. },
  3368. error: (err) => {
  3369. console.warn('⚠️ Gemini 视频识别失败,降级 Whisper:', err);
  3370. this.dhRefAnalysisText = 'Gemini 识别失败,正在使用 Whisper 语音识别...';
  3371. this.refreshView();
  3372. this.dhRefRunWhisperFallback();
  3373. }
  3374. });
  3375. } catch (err) {
  3376. console.warn('⚠️ 视频文件读取失败:', err);
  3377. this.dhRefAnalysisText = '视频文件读取失败,正在使用 Whisper 语音识别...';
  3378. this.refreshView();
  3379. this.dhRefRunWhisperFallback();
  3380. }
  3381. }
  3382. private dhRefRunAudioGemini(): void {
  3383. this.http.post<any>('/backend/api/extract-audio-mp3', { videoId: this.dhRefVideoId }).subscribe({
  3384. next: (res) => {
  3385. if (res?.success && res?.audio?.base64) {
  3386. const audioSizeMB = res.audio.sizeMB || 0;
  3387. this.dhRefAnalysisText = `音轨提取完成 (${audioSizeMB.toFixed(1)}MB),正在 Gemini 音频识别...`;
  3388. this.refreshView();
  3389. if (audioSizeMB > 20) {
  3390. this.dhRefAnalysisText = '音频文件仍较大,改用 Whisper 识别...';
  3391. this.refreshView();
  3392. this.dhRefRunWhisperFallback();
  3393. return;
  3394. }
  3395. const prompt = this.buildAnalysisPrompt('audio');
  3396. this.llmService.analyzeAudio(res.audio.base64, res.audio.mimeType || 'audio/mp4', prompt, {
  3397. model: 'gemini-2.5-flash',
  3398. generationConfig: { maxOutputTokens: 8192 }
  3399. }).subscribe({
  3400. next: (result) => {
  3401. this.dhRefParseGeminiResult(result);
  3402. this.dhRefAnalyzing = false;
  3403. this.refreshView();
  3404. this.dhRefMaybeAutoRewrite();
  3405. },
  3406. error: (err) => {
  3407. console.warn('⚠️ Gemini 音频识别失败,降级 Whisper:', err);
  3408. this.dhRefAnalysisText = 'Gemini 音频识别失败,改用 Whisper...';
  3409. this.refreshView();
  3410. this.dhRefRunWhisperFallback();
  3411. }
  3412. });
  3413. } else {
  3414. this.dhRefRunWhisperFallback();
  3415. }
  3416. },
  3417. error: (err) => {
  3418. const detail = err?.error?.error || err?.message || `HTTP ${err?.status}`;
  3419. console.warn('⚠️ 音轨提取失败:', detail, err);
  3420. this.dhRefAnalysisText = `音轨提取失败 (${detail}),改用 Whisper...`;
  3421. this.refreshView();
  3422. this.dhRefRunWhisperFallback();
  3423. }
  3424. });
  3425. }
  3426. private dhRefRunWhisperFallback(): void {
  3427. if (!this.dhRefVideoId) {
  3428. this.dhRefAnalyzing = false;
  3429. this.dhRefAnalysisText = '无法降级到 Whisper:参考视频尚未上传到服务端';
  3430. this.refreshView();
  3431. return;
  3432. }
  3433. this.http.post<any>('/backend/api/whisper/transcribe', {
  3434. videoId: this.dhRefVideoId,
  3435. language: 'Chinese',
  3436. model: 'large'
  3437. }).subscribe({
  3438. next: (res) => {
  3439. if (res?.success && res?.transcript) {
  3440. this.dhRefTranscript = res.transcript;
  3441. this.dhRefAnalysisText = 'Whisper 转录完成,正在 AI 分析内容...';
  3442. this.dhRefAutoFillTts();
  3443. this.refreshView();
  3444. this.dhRefDoTextAnalysis();
  3445. } else {
  3446. this.dhRefAnalyzing = false;
  3447. this.dhRefAnalysisText = '语音识别完成但未返回文字稿,请手动输入';
  3448. this.refreshView();
  3449. }
  3450. },
  3451. error: (err) => {
  3452. this.dhRefAnalyzing = false;
  3453. this.dhRefAnalysisText = `Whisper 识别失败: ${err?.error?.error || err?.message || '未知错误'}。请手动输入文字稿。`;
  3454. this.refreshView();
  3455. }
  3456. });
  3457. }
  3458. private dhRefDoTextAnalysis(): void {
  3459. const systemPrompt = `你是一个专业的视频内容分析师。请基于以下视频转录文字稿,提取:
  3460. 1. 视频主题和核心观点
  3461. 2. 目标受众
  3462. 3. 内容风格
  3463. 4. 关键知识点(3-5条)
  3464. 5. 改进方向
  3465. 请用简洁中文回复。`;
  3466. this.llmService.askWithSystem(systemPrompt, this.dhRefTranscript, { model: 'gemini-2.5-flash', max_tokens: 1024 }).subscribe({
  3467. next: (analysis) => {
  3468. this.dhRefAnalysisText = analysis || '分析完成';
  3469. this.dhRefAnalyzing = false;
  3470. this.refreshView();
  3471. this.dhRefMaybeAutoRewrite();
  3472. },
  3473. error: () => {
  3474. this.dhRefAnalysisText = '(AI 文本分析暂不可用,已完成 Whisper 转录)';
  3475. this.dhRefAnalyzing = false;
  3476. this.refreshView();
  3477. this.dhRefMaybeAutoRewrite();
  3478. }
  3479. });
  3480. }
  3481. private dhRefParseGeminiResult(raw: string): void {
  3482. const m = raw.match(/---TRANSCRIPT_START---([\s\S]*?)---TRANSCRIPT_END---/);
  3483. if (m) {
  3484. this.dhRefTranscript = m[1].trim();
  3485. const analysisPart = raw.substring(0, raw.indexOf('---TRANSCRIPT_START---')).trim();
  3486. this.dhRefAnalysisText = analysisPart.replace(/^【内容分析】\s*/, '') || '分析完成';
  3487. } else {
  3488. this.dhRefAnalysisText = raw || '分析完成';
  3489. }
  3490. this.dhRefAutoFillTts();
  3491. }
  3492. /** 把参考视频识别得到的文字稿自动填入 Step 2 口播文本(不覆盖用户已手输的内容) */
  3493. private dhRefAutoFillTts(): void {
  3494. const transcript = (this.dhRefTranscript || '').trim();
  3495. if (!transcript) return;
  3496. // 仅在口播文本为空时自动填入;用户已输入则保留
  3497. if (!this.dhTtsText || !this.dhTtsText.trim()) {
  3498. this.dhTtsText = transcript.slice(0, 600);
  3499. }
  3500. }
  3501. /** 文字稿手动编辑时,同步反映到口播文本(前提:当前口播仍等于上一次同步值) */
  3502. dhRefSyncToTts(newTranscript: string): void {
  3503. const next = (newTranscript || '').slice(0, 600);
  3504. this.dhTtsText = next;
  3505. }
  3506. /** 应用补充提示词预设;二次点击同一个则取消 */
  3507. dhApplyPromptPreset(value: string): void {
  3508. if (this.dhPrompt === value) {
  3509. this.dhPrompt = '';
  3510. } else {
  3511. this.dhPrompt = value;
  3512. }
  3513. this.refreshView();
  3514. }
  3515. private buildAnalysisPrompt(kind: 'video' | 'audio'): string {
  3516. const taskOne = kind === 'video'
  3517. ? `从画面和音频两个维度分析:1.主题/核心观点 2.画面描述 3.目标受众 4.内容风格 5.亮点(3-5条) 6.视觉风格 7.改进建议`
  3518. : `从音频分析:1.主题/核心观点 2.目标受众 3.内容风格 4.亮点(3-5条) 5.改进建议`;
  3519. return `你是一个专业的内容分析师。请完成两个任务:
  3520. ===== 任务一:内容分析 =====
  3521. ${taskOne}
  3522. ===== 任务二:完整语音转录 =====
  3523. 请将所有语音内容逐字转录为中文,忠实还原、不遗漏、不改写、不总结,按自然段落分段。
  3524. 请严格按以下格式输出(用分隔线区分两部分):
  3525. 【内容分析】
  3526. (任务一结果)
  3527. ---TRANSCRIPT_START---
  3528. (任务二完整转录)
  3529. ---TRANSCRIPT_END---`;
  3530. }
  3531. // 视频分析完成后自动触发(仅在通过 AI重塑入口或显式标记时)
  3532. private dhRefMaybeAutoRewrite(): void {
  3533. if (!this.dhRefAutoRewrite) return;
  3534. if (!this.dhRefTranscript || !this.dhRefTranscript.trim()) return;
  3535. this.dhRefAutoRewrite = false; // 仅触发一次
  3536. this.dhRefRunRewrite();
  3537. }
  3538. // 把当前文字稿 + 内容分析交给 AI 重写为口播文本与补充提示词
  3539. dhRefRunRewrite(): void {
  3540. if (!this.dhRefTranscript || !this.dhRefTranscript.trim()) {
  3541. this.dhRefRewriteError = '暂无可重塑的视频文字稿';
  3542. this.refreshView();
  3543. return;
  3544. }
  3545. this.dhRefRewriting = true;
  3546. this.dhRefRewriteError = '';
  3547. this.refreshView();
  3548. const systemPrompt = `你是一位短视频数字人编剧。基于用户提供的【原始视频文字稿】和【内容分析】,请输出严格的 JSON:
  3549. {
  3550. "ttsScript": "重塑后的口播文本,第一人称、自然口语、节奏适合数字人朗读,控制在 200 字以内",
  3551. "dhPrompt": "数字人生成的补充提示词,描述人物动作 / 镜头语言 / 风格要求,控制在 80 字以内"
  3552. }
  3553. 只返回纯 JSON 对象,不要使用 markdown 代码块、不要添加解释或前后缀。注意:JSON 字符串内部禁止出现真实换行,必须使用 \\n 转义。`;
  3554. const userInput = `【原始文字稿】\n${this.dhRefTranscript}\n\n【内容分析】\n${this.dhRefAnalysisText || '(无)'}`;
  3555. this.llmService.askWithSystem(systemPrompt, userInput, { model: 'gemini-2.5-flash', max_tokens: 2048 }).subscribe({
  3556. next: (text) => {
  3557. this.dhRefRewriting = false;
  3558. const cleaned = (text || '').replace(/^\s*```(?:json)?\s*/i, '').replace(/\s*```\s*$/i, '').trim();
  3559. const parsed = this.parseRewriteJson(cleaned);
  3560. if (parsed) {
  3561. const tts = typeof parsed.ttsScript === 'string' ? parsed.ttsScript.trim() : '';
  3562. const prompt = typeof parsed.dhPrompt === 'string' ? parsed.dhPrompt.trim() : '';
  3563. if (tts) this.dhTtsText = tts.slice(0, 600);
  3564. if (prompt) this.dhPrompt = prompt.slice(0, 200);
  3565. if (tts || prompt) {
  3566. this.showToast('✅ 已自动填充口播文本与补充提示词', 'success');
  3567. } else {
  3568. this.dhRefRewriteError = 'AI 未返回有效字段,请手动整理';
  3569. }
  3570. } else {
  3571. console.warn('⚠️ 解析重塑结果失败,原始返回:', cleaned);
  3572. this.dhRefRewriteError = '解析重塑结果失败,已将原始文本填入口播文本,请手动整理';
  3573. this.dhTtsText = (text || '').slice(0, 600);
  3574. this.showToast('⚠️ 重塑结果解析失败,已退回原文', 'warn');
  3575. }
  3576. this.refreshView();
  3577. },
  3578. error: (err) => {
  3579. this.dhRefRewriting = false;
  3580. this.dhRefRewriteError = `AI 重塑失败:${this.getErrorText(err, '请重试')}`;
  3581. this.refreshView();
  3582. }
  3583. });
  3584. }
  3585. /** 容错解析 LLM 返回的 JSON:支持 fenced 代码块、未转义换行、字段正则兜底 */
  3586. private parseRewriteJson(raw: string): { ttsScript?: string; dhPrompt?: string } | null {
  3587. if (!raw) return null;
  3588. // 1) 严格解析
  3589. try { return JSON.parse(raw); } catch {}
  3590. // 2) 截取首个 { ... } 区段
  3591. const braceStart = raw.indexOf('{');
  3592. const braceEnd = raw.lastIndexOf('}');
  3593. let candidate = braceStart >= 0 && braceEnd > braceStart ? raw.slice(braceStart, braceEnd + 1) : raw;
  3594. // 3) 把字符串内部的裸换行/回车/制表符转义
  3595. const sanitized = this.escapeRawControlCharsInJsonStrings(candidate);
  3596. try { return JSON.parse(sanitized); } catch {}
  3597. // 4) 正则兜底,逐字段抽取(兼容 "tts": "..." 中含 \" 转义)
  3598. const fieldRegex = (key: string) => new RegExp(`"${key}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`, 'i');
  3599. const ttsMatch = candidate.match(fieldRegex('ttsScript'));
  3600. const promptMatch = candidate.match(fieldRegex('dhPrompt'));
  3601. if (ttsMatch || promptMatch) {
  3602. const unescape = (s: string) => s.replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
  3603. return {
  3604. ttsScript: ttsMatch ? unescape(ttsMatch[1]) : undefined,
  3605. dhPrompt: promptMatch ? unescape(promptMatch[1]) : undefined,
  3606. };
  3607. }
  3608. // 5) 截断兜底:若仅有 ttsScript 开头但被截断,抓到截断处为止
  3609. const truncatedTts = candidate.match(/"ttsScript"\s*:\s*"((?:\\.|[^"\\])*)$/i);
  3610. if (truncatedTts) {
  3611. return { ttsScript: truncatedTts[1].replace(/\\n/g, '\n').replace(/\\"/g, '"') };
  3612. }
  3613. return null;
  3614. }
  3615. /** 在 JSON 字符串字面量内部把裸 \n \r \t 替换为转义形式,括号外的不动 */
  3616. private escapeRawControlCharsInJsonStrings(input: string): string {
  3617. let out = '';
  3618. let inString = false;
  3619. let escape = false;
  3620. for (let i = 0; i < input.length; i++) {
  3621. const ch = input[i];
  3622. if (inString) {
  3623. if (escape) { out += ch; escape = false; continue; }
  3624. if (ch === '\\') { out += ch; escape = true; continue; }
  3625. if (ch === '"') { inString = false; out += ch; continue; }
  3626. if (ch === '\n') { out += '\\n'; continue; }
  3627. if (ch === '\r') { out += '\\r'; continue; }
  3628. if (ch === '\t') { out += '\\t'; continue; }
  3629. out += ch;
  3630. } else {
  3631. if (ch === '"') { inString = true; out += ch; continue; }
  3632. out += ch;
  3633. }
  3634. }
  3635. return out;
  3636. }
  3637. getActiveRemixSteps(): RemixFlowStep[] {
  3638. if (this.remixMode === 'digital-human') {
  3639. return [
  3640. { step: 1, label: this.digitalHumanStepLabels[0] },
  3641. { step: 4, label: this.digitalHumanStepLabels[1] },
  3642. { step: 5, label: this.digitalHumanStepLabels[2] },
  3643. { step: 6, label: this.digitalHumanStepLabels[3] }
  3644. ];
  3645. }
  3646. return this.remixStepLabels.map((label, index) => ({ step: index + 1, label }));
  3647. }
  3648. setRemixMode(mode: 'standard' | 'digital-human'): void {
  3649. this.remixMode = mode;
  3650. this.remixDigitalHumanError = '';
  3651. if (mode === 'standard' && this.remixStep === 4 && this.remixStoryboard.length === 0) {
  3652. this.remixStep = 1;
  3653. }
  3654. }
  3655. private hydrateVoiceProfile(profile: any): VoiceProfile {
  3656. const status = profile?.status === null || profile?.status === undefined || profile?.status === ''
  3657. ? null
  3658. : Number(profile.status);
  3659. const synthesizedAudioUrl = String(profile?.synthesized_audio_url || '');
  3660. const demoAudio = String(profile?.demo_audio || '');
  3661. const latestAudioUrl = String(profile?.latest_audio_url || synthesizedAudioUrl || demoAudio || '');
  3662. return {
  3663. ...profile,
  3664. creation_mode: String(profile?.creation_mode || (profile?.timbre_id ? 'clone' : 'design')),
  3665. speaker_id: String(profile?.speaker_id || ''),
  3666. timbre_id: String(profile?.timbre_id || profile?.timbreId || ''),
  3667. sample_text: String(profile?.sample_text || ''),
  3668. text_prompt: String(profile?.text_prompt || ''),
  3669. source_audio_text: String(profile?.source_audio_text || ''),
  3670. source_audio_name: String(profile?.source_audio_name || ''),
  3671. source_audio_format: String(profile?.source_audio_format || ''),
  3672. language: Number(profile?.language ?? 0),
  3673. status,
  3674. status_label: String(profile?.status_label || (demoAudio || synthesizedAudioUrl ? '可用' : '未知')),
  3675. demo_audio: demoAudio,
  3676. available_training_times: profile?.available_training_times === null || profile?.available_training_times === undefined
  3677. ? null
  3678. : Number(profile.available_training_times),
  3679. image_prompt_name: String(profile?.image_prompt_name || ''),
  3680. x_api_resource_id: String(profile?.x_api_resource_id || ''),
  3681. model_version: String(profile?.model_version || ''),
  3682. icl_speaker_id: String(profile?.icl_speaker_id || ''),
  3683. occupied: !!profile?.occupied,
  3684. synthesized_audio_url: synthesizedAudioUrl,
  3685. synthesized_work_id: String(profile?.synthesized_work_id || ''),
  3686. last_synthesis_text: String(profile?.last_synthesis_text || ''),
  3687. latest_audio_url: latestAudioUrl,
  3688. ...this.buildVoiceSynthesisDraft(profile),
  3689. is_synthesizing: false,
  3690. message: String(profile?.message || ''),
  3691. request_id: String(profile?.request_id || ''),
  3692. created_at: new Date(profile?.created_at || Date.now()),
  3693. updated_at: profile?.updated_at ? new Date(profile.updated_at) : undefined
  3694. };
  3695. }
  3696. private upsertLocalVoiceProfile(profile: VoiceProfile): void {
  3697. const nextProfiles = [...this.voiceProfiles];
  3698. const existingIndex = nextProfiles.findIndex((item) => (
  3699. item.id === profile.id
  3700. || (!!profile.timbre_id && item.timbre_id === profile.timbre_id)
  3701. ));
  3702. if (existingIndex >= 0) {
  3703. nextProfiles[existingIndex] = {
  3704. ...nextProfiles[existingIndex],
  3705. ...profile,
  3706. draft_synthesis_text: profile.draft_synthesis_text ?? nextProfiles[existingIndex].draft_synthesis_text,
  3707. draft_synthesis_ssml: profile.draft_synthesis_ssml ?? nextProfiles[existingIndex].draft_synthesis_ssml,
  3708. draft_synthesis_x_api_resource_id: profile.draft_synthesis_x_api_resource_id ?? nextProfiles[existingIndex].draft_synthesis_x_api_resource_id,
  3709. draft_synthesis_model: profile.draft_synthesis_model ?? nextProfiles[existingIndex].draft_synthesis_model,
  3710. draft_synthesis_format: profile.draft_synthesis_format ?? nextProfiles[existingIndex].draft_synthesis_format,
  3711. draft_synthesis_sample_rate: profile.draft_synthesis_sample_rate ?? nextProfiles[existingIndex].draft_synthesis_sample_rate,
  3712. draft_synthesis_speech_rate: profile.draft_synthesis_speech_rate ?? nextProfiles[existingIndex].draft_synthesis_speech_rate,
  3713. draft_synthesis_loudness_rate: profile.draft_synthesis_loudness_rate ?? nextProfiles[existingIndex].draft_synthesis_loudness_rate,
  3714. draft_synthesis_emotion: profile.draft_synthesis_emotion ?? nextProfiles[existingIndex].draft_synthesis_emotion,
  3715. draft_synthesis_emotion_scale: profile.draft_synthesis_emotion_scale ?? nextProfiles[existingIndex].draft_synthesis_emotion_scale,
  3716. draft_synthesis_enable_subtitle: profile.draft_synthesis_enable_subtitle ?? nextProfiles[existingIndex].draft_synthesis_enable_subtitle,
  3717. draft_synthesis_silence_duration: profile.draft_synthesis_silence_duration ?? nextProfiles[existingIndex].draft_synthesis_silence_duration,
  3718. draft_synthesis_enable_language_detector: profile.draft_synthesis_enable_language_detector ?? nextProfiles[existingIndex].draft_synthesis_enable_language_detector,
  3719. draft_synthesis_disable_markdown_filter: profile.draft_synthesis_disable_markdown_filter ?? nextProfiles[existingIndex].draft_synthesis_disable_markdown_filter,
  3720. draft_synthesis_disable_emoji_filter: profile.draft_synthesis_disable_emoji_filter ?? nextProfiles[existingIndex].draft_synthesis_disable_emoji_filter,
  3721. draft_synthesis_explicit_language: profile.draft_synthesis_explicit_language ?? nextProfiles[existingIndex].draft_synthesis_explicit_language,
  3722. is_synthesizing: false
  3723. };
  3724. this.voiceProfiles = nextProfiles;
  3725. if (this.voiceSynthesisForm.profileId === nextProfiles[existingIndex].id) {
  3726. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(nextProfiles[existingIndex]);
  3727. }
  3728. return;
  3729. }
  3730. this.voiceProfiles = [{ ...profile, is_synthesizing: false }, ...nextProfiles];
  3731. if (!this.voiceSynthesisForm.profileId && !String(this.voiceSynthesisForm.speakerId || '').trim() && this.canSynthesizeVoiceProfile(profile)) {
  3732. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(profile);
  3733. }
  3734. }
  3735. private getVoiceCloneModelMeta(modelSource: any): { demoAudio: string; iclSpeakerId: string; xApiResourceId: string; modelVersion: string } {
  3736. const model = Array.isArray(modelSource) ? (modelSource.find((item) => !!item) || {}) : (modelSource || {});
  3737. const rawResourceId = Array.isArray(model?.x_api_resource_id)
  3738. ? model.x_api_resource_id.find((item: any) => String(item || '').trim()) || ''
  3739. : model?.x_api_resource_id;
  3740. return {
  3741. demoAudio: String(model?.demo_audio || '').trim(),
  3742. iclSpeakerId: String(model?.icl_speaker_id || '').trim(),
  3743. xApiResourceId: String(rawResourceId || '').trim(),
  3744. modelVersion: String(model?.version || model?.model_version || '').trim()
  3745. };
  3746. }
  3747. private buildVoiceProfileFromCloneApiResponse(response: any, fallback: {
  3748. displayName: string;
  3749. speakerId: string;
  3750. sampleText: string;
  3751. audioText: string;
  3752. sourceAudioName: string;
  3753. sourceAudioFormat: string;
  3754. language: number;
  3755. }): VoiceProfile | null {
  3756. const timbre = response?.data?.timbre;
  3757. if (!timbre || typeof timbre !== 'object') {
  3758. return null;
  3759. }
  3760. const modelMeta = this.getVoiceCloneModelMeta(timbre?.models);
  3761. return this.hydrateVoiceProfile({
  3762. id: String(timbre?.objectId || `voice-${Date.now()}`),
  3763. name: String(timbre?.name || fallback.displayName || '未命名音色'),
  3764. creation_mode: 'clone',
  3765. speaker_id: String(timbre?.speaker_id || fallback.speakerId || ''),
  3766. timbre_id: String(timbre?.objectId || ''),
  3767. sample_text: fallback.sampleText,
  3768. source_audio_text: fallback.audioText,
  3769. source_audio_name: fallback.sourceAudioName,
  3770. source_audio_format: fallback.sourceAudioFormat,
  3771. language: fallback.language,
  3772. status: timbre?.status === null || timbre?.status === undefined || timbre?.status === '' ? null : Number(timbre.status),
  3773. status_label: String(response?.data?.tip || (modelMeta.demoAudio ? '可用' : '未知')),
  3774. demo_audio: modelMeta.demoAudio,
  3775. occupied: !!timbre?.occupied,
  3776. x_api_resource_id: modelMeta.xApiResourceId,
  3777. model_version: modelMeta.modelVersion,
  3778. icl_speaker_id: modelMeta.iclSpeakerId,
  3779. latest_audio_url: modelMeta.demoAudio,
  3780. message: String(response?.data?.tip || ''),
  3781. created_at: timbre?.createdAt || new Date().toISOString(),
  3782. updated_at: timbre?.updatedAt || new Date().toISOString()
  3783. });
  3784. }
  3785. private applySynthesisResponseToProfile(profile: VoiceProfile, response: any, payload: {
  3786. text: string;
  3787. ssml: string;
  3788. xApiResourceId: string;
  3789. model: string;
  3790. format: string;
  3791. sampleRate: number;
  3792. speechRate: number;
  3793. loudnessRate: number;
  3794. emotion: string;
  3795. emotionScale: number;
  3796. enableSubtitle: boolean;
  3797. silenceDuration: number;
  3798. enableLanguageDetector: boolean;
  3799. disableMarkdownFilter: boolean;
  3800. disableEmojiFilter: boolean;
  3801. explicitLanguage: string;
  3802. }): VoiceProfile {
  3803. const audioUrl = String(response?.data?.audioUrl || '').trim();
  3804. const workId = String(response?.data?.workId || '').trim();
  3805. return this.hydrateVoiceProfile({
  3806. ...profile,
  3807. synthesized_audio_url: audioUrl || profile.synthesized_audio_url || '',
  3808. synthesized_work_id: workId || profile.synthesized_work_id || '',
  3809. latest_audio_url: audioUrl || profile.latest_audio_url || profile.demo_audio || '',
  3810. last_synthesis_text: payload.text,
  3811. last_synthesis_ssml: payload.ssml,
  3812. last_synthesis_x_api_resource_id: payload.xApiResourceId || profile.x_api_resource_id || '',
  3813. last_synthesis_model: payload.model,
  3814. last_synthesis_format: payload.format,
  3815. last_synthesis_sample_rate: payload.sampleRate,
  3816. last_synthesis_speech_rate: payload.speechRate,
  3817. last_synthesis_loudness_rate: payload.loudnessRate,
  3818. last_synthesis_emotion: payload.emotion,
  3819. last_synthesis_emotion_scale: payload.emotionScale,
  3820. last_synthesis_enable_subtitle: payload.enableSubtitle,
  3821. last_synthesis_silence_duration: payload.silenceDuration,
  3822. last_synthesis_enable_language_detector: payload.enableLanguageDetector,
  3823. last_synthesis_disable_markdown_filter: payload.disableMarkdownFilter,
  3824. last_synthesis_disable_emoji_filter: payload.disableEmojiFilter,
  3825. last_synthesis_explicit_language: payload.explicitLanguage,
  3826. updated_at: new Date().toISOString()
  3827. });
  3828. }
  3829. private syncVoiceProfileToBackend(profile: VoiceProfile | null | undefined): void {
  3830. if (!profile?.id) {
  3831. return;
  3832. }
  3833. this.http.post<any>('/backend/api/voice-profiles/sync', {
  3834. ...profile,
  3835. created_at: profile.created_at instanceof Date ? profile.created_at.toISOString() : profile.created_at,
  3836. updated_at: profile.updated_at instanceof Date ? profile.updated_at.toISOString() : profile.updated_at
  3837. }).subscribe({
  3838. next: (res) => {
  3839. if (res?.profile) {
  3840. this.upsertLocalVoiceProfile(this.hydrateVoiceProfile(res.profile));
  3841. this.refreshView();
  3842. }
  3843. },
  3844. error: (err) => {
  3845. console.warn('⚠️ 音色记录本地同步失败:', err);
  3846. }
  3847. });
  3848. }
  3849. private isVoiceSpeakerIdentifier(value: string): boolean {
  3850. const normalizedValue = String(value || '').trim();
  3851. return /^(S_|ICL_|icl_|saturn_|dit_)/.test(normalizedValue);
  3852. }
  3853. onVoiceSourceAudioSelected(event: Event): void {
  3854. const input = event.target as HTMLInputElement;
  3855. if (!input.files || input.files.length === 0) {
  3856. return;
  3857. }
  3858. const file = input.files[0];
  3859. const ext = (file.name.match(/\.[^.]+$/)?.[0] || '').toLowerCase();
  3860. const allowedTypes = ['audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/x-wav', 'audio/mp4', 'audio/x-m4a', 'audio/aac', 'audio/flac', 'audio/ogg', 'audio/opus', 'application/octet-stream'];
  3861. const allowedExts = ['.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.opus', '.pcm'];
  3862. if ((!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) || file.size <= 0) {
  3863. this.voiceDesignError = '音频样本仅支持 mp3、wav、m4a、aac、flac、ogg、opus、pcm 格式';
  3864. input.value = '';
  3865. this.refreshView();
  3866. return;
  3867. }
  3868. if (file.size > 20 * 1024 * 1024) {
  3869. this.voiceDesignError = '音频样本大小不能超过 20MB';
  3870. input.value = '';
  3871. this.refreshView();
  3872. return;
  3873. }
  3874. this.voiceSourceAudioFile = file;
  3875. this.voiceSourceAudioName = file.name;
  3876. this.voiceDesignError = '';
  3877. input.value = '';
  3878. this.refreshView();
  3879. }
  3880. clearVoiceSourceAudio(): void {
  3881. this.voiceSourceAudioFile = null;
  3882. this.voiceSourceAudioName = '';
  3883. this.refreshView();
  3884. }
  3885. onVoiceDesignImageSelected(event: Event): void {
  3886. const input = event.target as HTMLInputElement;
  3887. if (!input.files || input.files.length === 0) {
  3888. return;
  3889. }
  3890. const file = input.files[0];
  3891. if (!String(file.type || '').startsWith('image/') || file.size <= 0) {
  3892. this.voiceDesignError = '图片提示仅支持常见图片格式';
  3893. input.value = '';
  3894. this.refreshView();
  3895. return;
  3896. }
  3897. if (file.size > 10 * 1024 * 1024) {
  3898. this.voiceDesignError = '图片提示大小不能超过 10MB';
  3899. input.value = '';
  3900. this.refreshView();
  3901. return;
  3902. }
  3903. this.voiceDesignImageFile = file;
  3904. this.voiceDesignImageName = file.name;
  3905. this.voiceDesignError = '';
  3906. input.value = '';
  3907. this.refreshView();
  3908. }
  3909. clearVoiceDesignImage(): void {
  3910. this.voiceDesignImageFile = null;
  3911. this.voiceDesignImageName = '';
  3912. this.refreshView();
  3913. }
  3914. setVoiceCreateMode(mode: 'clone' | 'design' | 'synthesize'): void {
  3915. if (this.voiceCreateMode === mode) {
  3916. return;
  3917. }
  3918. this.voiceCreateMode = mode;
  3919. this.voiceDesignError = '';
  3920. if (mode === 'synthesize') {
  3921. this.syncVoiceSynthesisFormSelection();
  3922. }
  3923. this.refreshView();
  3924. }
  3925. private resetVoiceCreateForm(): void {
  3926. this.voiceForm = this.buildDefaultVoiceForm();
  3927. this.voiceSourceAudioFile = null;
  3928. this.voiceSourceAudioName = '';
  3929. this.voiceDesignImageFile = null;
  3930. this.voiceDesignImageName = '';
  3931. }
  3932. getVoiceProfileAudioUrl(profile: VoiceProfile | null | undefined): string {
  3933. if (!profile) {
  3934. return '';
  3935. }
  3936. return String(profile.latest_audio_url || profile.synthesized_audio_url || profile.demo_audio || '').trim();
  3937. }
  3938. canSynthesizeVoiceProfile(profile: VoiceProfile | null | undefined): boolean {
  3939. if (!profile) {
  3940. return false;
  3941. }
  3942. return !!String(profile.icl_speaker_id || profile.speaker_id || '').trim();
  3943. }
  3944. getSynthesisVoiceProfiles(): VoiceProfile[] {
  3945. return this.voiceProfiles.filter((profile) => this.canSynthesizeVoiceProfile(profile));
  3946. }
  3947. getSelectedVoiceSynthesisProfile(): VoiceProfile | null {
  3948. return this.getSynthesisVoiceProfiles().find((profile) => profile.id === this.voiceSynthesisForm.profileId) || null;
  3949. }
  3950. selectVoiceSynthesisProfile(profileId: string): void {
  3951. if (!profileId) {
  3952. this.voiceSynthesisForm = {
  3953. ...this.voiceSynthesisForm,
  3954. profileId: ''
  3955. };
  3956. this.refreshView();
  3957. return;
  3958. }
  3959. const nextProfile = this.voiceProfiles.find((profile) => profile.id === profileId) || null;
  3960. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(nextProfile);
  3961. this.refreshView();
  3962. }
  3963. openVoiceSynthesisWorkbench(profile: VoiceProfile): void {
  3964. if (!this.canSynthesizeVoiceProfile(profile)) {
  3965. this.showToast('❌ 当前音色缺少可用于语音合成的 speaker 标识', 'error');
  3966. return;
  3967. }
  3968. this.voiceCreateMode = 'synthesize';
  3969. this.voiceDesignError = '';
  3970. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(profile);
  3971. this.refreshView();
  3972. }
  3973. getVoiceProfileAudioLabel(profile: VoiceProfile | null | undefined): string {
  3974. if (!profile) {
  3975. return '暂无可用音频';
  3976. }
  3977. const audioUrl = this.getVoiceProfileAudioUrl(profile);
  3978. if (!audioUrl) {
  3979. return '暂无可用音频';
  3980. }
  3981. if (audioUrl === String(profile.synthesized_audio_url || '')) {
  3982. return '文本合成音频';
  3983. }
  3984. if (audioUrl === String(profile.demo_audio || '')) {
  3985. return '试听音频';
  3986. }
  3987. return '音色音频';
  3988. }
  3989. createVoiceProfile(): void {
  3990. if (this.isCreatingVoiceProfile) {
  3991. return;
  3992. }
  3993. if (this.voiceCreateMode === 'synthesize') {
  3994. this.submitVoiceSynthesisForm();
  3995. return;
  3996. }
  3997. if (this.voiceCreateMode === 'design') {
  3998. this.createVoiceDesignProfile();
  3999. return;
  4000. }
  4001. this.createVoiceCloneProfile();
  4002. }
  4003. private createVoiceCloneProfile(): void {
  4004. const speakerId = this.voiceForm.speakerId.trim();
  4005. const displayName = this.voiceForm.displayName.trim();
  4006. const audioText = this.voiceForm.audioText.trim();
  4007. const sampleText = this.voiceForm.sampleText.trim();
  4008. const synthesisText = this.voiceForm.synthesisText.trim();
  4009. const sourceAudioFile = this.voiceSourceAudioFile;
  4010. if (!displayName) {
  4011. this.voiceDesignError = '请输入音色名称';
  4012. this.refreshView();
  4013. return;
  4014. }
  4015. if (!speakerId) {
  4016. this.voiceDesignError = '请输入音色代号 speaker_id';
  4017. this.refreshView();
  4018. return;
  4019. }
  4020. if (!sourceAudioFile) {
  4021. this.voiceDesignError = '请上传用于复刻的音频样本';
  4022. this.refreshView();
  4023. return;
  4024. }
  4025. if (!sampleText) {
  4026. this.voiceDesignError = '请输入试听文本';
  4027. this.refreshView();
  4028. return;
  4029. }
  4030. if (sampleText.length < 4 || sampleText.length > 80) {
  4031. this.voiceDesignError = '试听文本长度需在 4-80 字之间';
  4032. this.refreshView();
  4033. return;
  4034. }
  4035. this.isCreatingVoiceProfile = true;
  4036. this.voiceDesignError = '';
  4037. const finalizeCloneFlow = (profile: VoiceProfile | null, toastType: 'success' | 'warn', toastMessage: string) => {
  4038. if (profile) {
  4039. profile.draft_synthesis_text = profile.last_synthesis_text || synthesisText;
  4040. this.upsertLocalVoiceProfile(profile);
  4041. this.syncVoiceProfileToBackend(profile);
  4042. if (this.getVoiceProfileAudioUrl(profile)) {
  4043. this.preferredVoiceProfileId = profile.id;
  4044. }
  4045. }
  4046. this.resetVoiceCreateForm();
  4047. this.isCreatingVoiceProfile = false;
  4048. this.showToast(toastMessage, toastType, 5000);
  4049. this.refreshView();
  4050. };
  4051. this.readFileAsBase64(sourceAudioFile).then((audioBase64) => {
  4052. const sourceAudioFormat = this.inferVoiceSourceAudioFormat(sourceAudioFile);
  4053. this.http.post<any>(`${this.voiceTtsBaseUrl}/voice_clone`, {
  4054. token: this.voiceApiToken,
  4055. name: displayName,
  4056. speaker_id: speakerId,
  4057. audioData: {
  4058. base64: audioBase64,
  4059. format: sourceAudioFormat,
  4060. ...(audioText ? { text: audioText } : {})
  4061. },
  4062. language: this.voiceForm.language || 0,
  4063. extra_params: {
  4064. demo_text: sampleText
  4065. }
  4066. }).subscribe({
  4067. next: (res) => {
  4068. const baseProfile: VoiceProfile | null = res?.profile
  4069. ? this.hydrateVoiceProfile(res.profile)
  4070. : this.buildVoiceProfileFromCloneApiResponse(res, {
  4071. displayName,
  4072. speakerId,
  4073. sampleText,
  4074. audioText,
  4075. sourceAudioName: sourceAudioFile.name,
  4076. sourceAudioFormat,
  4077. language: this.voiceForm.language || 0
  4078. });
  4079. if (!synthesisText || !baseProfile) {
  4080. finalizeCloneFlow(
  4081. baseProfile,
  4082. 'success',
  4083. '✅ 音色复刻完成,可在列表中继续合成文本并用于数字人生成'
  4084. );
  4085. return;
  4086. }
  4087. this.http.post<any>(`${this.voiceTtsBaseUrl}/unidirectional`, {
  4088. token: this.voiceApiToken,
  4089. text: synthesisText,
  4090. timbreId: baseProfile.timbre_id || '',
  4091. speaker_id: baseProfile.icl_speaker_id || baseProfile.speaker_id || '',
  4092. isStream: false,
  4093. x_api_resource_id: baseProfile.x_api_resource_id || ''
  4094. }).subscribe({
  4095. next: (synthesisRes) => {
  4096. const nextProfile: VoiceProfile | null = synthesisRes?.profile
  4097. ? this.hydrateVoiceProfile(synthesisRes.profile)
  4098. : this.applySynthesisResponseToProfile(baseProfile, synthesisRes, {
  4099. text: synthesisText,
  4100. ssml: '',
  4101. xApiResourceId: baseProfile.x_api_resource_id || '',
  4102. model: '',
  4103. format: 'mp3',
  4104. sampleRate: 24000,
  4105. speechRate: 0,
  4106. loudnessRate: 0,
  4107. emotion: '',
  4108. emotionScale: 4,
  4109. enableSubtitle: false,
  4110. silenceDuration: 0,
  4111. enableLanguageDetector: false,
  4112. disableMarkdownFilter: false,
  4113. disableEmojiFilter: false,
  4114. explicitLanguage: ''
  4115. });
  4116. finalizeCloneFlow(nextProfile, 'success', '✅ 音色复刻完成,并已生成首条文本音频');
  4117. },
  4118. error: () => {
  4119. finalizeCloneFlow(baseProfile, 'warn', '⚠️ 音色复刻完成,但首条文本合成失败,可稍后重试');
  4120. }
  4121. });
  4122. },
  4123. error: (err) => {
  4124. this.isCreatingVoiceProfile = false;
  4125. this.voiceDesignError = this.getErrorText(err, '音色复刻失败,请检查 token、speaker_id 与音频参数');
  4126. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4127. this.refreshView();
  4128. }
  4129. });
  4130. }).catch(() => {
  4131. this.isCreatingVoiceProfile = false;
  4132. this.voiceDesignError = '音频文件读取失败,请重新选择音频样本';
  4133. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4134. this.refreshView();
  4135. });
  4136. }
  4137. private createVoiceDesignProfile(): void {
  4138. const speakerId = this.voiceForm.speakerId.trim();
  4139. const displayName = this.voiceForm.displayName.trim();
  4140. const sampleText = this.voiceForm.sampleText.trim();
  4141. const textPrompt = this.voiceForm.textPrompt.trim();
  4142. if (!displayName) {
  4143. this.voiceDesignError = '请输入音色名称';
  4144. this.refreshView();
  4145. return;
  4146. }
  4147. if (!speakerId) {
  4148. this.voiceDesignError = '请输入音色代号 speaker_id';
  4149. this.refreshView();
  4150. return;
  4151. }
  4152. if (!sampleText) {
  4153. this.voiceDesignError = '请输入试听文本';
  4154. this.refreshView();
  4155. return;
  4156. }
  4157. if (sampleText.length > 300) {
  4158. this.voiceDesignError = '试听文本不能超过 300 字';
  4159. this.refreshView();
  4160. return;
  4161. }
  4162. if (textPrompt.length > 200) {
  4163. this.voiceDesignError = '文本提示词不能超过 200 字';
  4164. this.refreshView();
  4165. return;
  4166. }
  4167. if (!textPrompt && !this.voiceDesignImageFile) {
  4168. this.voiceDesignError = '文本提示词与图片提示不能同时为空';
  4169. this.refreshView();
  4170. return;
  4171. }
  4172. this.isCreatingVoiceProfile = true;
  4173. this.voiceDesignError = '';
  4174. const formData = new FormData();
  4175. formData.append('speakerId', speakerId);
  4176. formData.append('displayName', displayName);
  4177. formData.append('sampleText', sampleText);
  4178. formData.append('textPrompt', textPrompt);
  4179. formData.append('language', String(this.voiceForm.language || 0));
  4180. if (this.voiceDesignImageFile) {
  4181. formData.append('image', this.voiceDesignImageFile, this.voiceDesignImageFile.name);
  4182. }
  4183. this.http.post<any>('/backend/api/voice/design', formData).subscribe({
  4184. next: (res) => {
  4185. const profile: VoiceProfile | null = res?.profile
  4186. ? this.hydrateVoiceProfile(res.profile)
  4187. : null;
  4188. if (profile) {
  4189. this.upsertLocalVoiceProfile(profile);
  4190. if (this.getVoiceProfileAudioUrl(profile)) {
  4191. this.preferredVoiceProfileId = profile.id;
  4192. }
  4193. }
  4194. this.resetVoiceCreateForm();
  4195. this.isCreatingVoiceProfile = false;
  4196. this.showToast('✅ 音色设计完成,可直接试听并用于数字人生成', 'success', 5000);
  4197. this.refreshView();
  4198. },
  4199. error: (err) => {
  4200. this.isCreatingVoiceProfile = false;
  4201. this.voiceDesignError = this.getErrorText(err, '音色设计失败,请检查 speaker_id、提示词与图片参数');
  4202. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4203. this.refreshView();
  4204. }
  4205. });
  4206. }
  4207. submitVoiceSynthesisForm(): void {
  4208. const profile = this.voiceProfiles.find((item) => item.id === this.voiceSynthesisForm.profileId) || null;
  4209. const manualVoiceId = String(this.voiceSynthesisForm.speakerId || '').trim();
  4210. if (!profile && !manualVoiceId) {
  4211. this.voiceDesignError = '请选择已有音色,或直接输入 timbreId / speaker_id';
  4212. this.refreshView();
  4213. return;
  4214. }
  4215. if (!profile) {
  4216. this.voiceDesignError = '';
  4217. if (this.isVoiceSpeakerIdentifier(manualVoiceId)) {
  4218. this.synthesizeVoiceBySpeakerId(manualVoiceId);
  4219. return;
  4220. }
  4221. const manualProfile = this.hydrateVoiceProfile({
  4222. id: `manual-${manualVoiceId}`,
  4223. name: `手动音色 ${manualVoiceId}`,
  4224. creation_mode: 'manual',
  4225. speaker_id: '',
  4226. timbre_id: manualVoiceId,
  4227. sample_text: '',
  4228. source_audio_text: '',
  4229. source_audio_name: '',
  4230. source_audio_format: '',
  4231. language: 0,
  4232. status: null,
  4233. status_label: '手动输入',
  4234. demo_audio: '',
  4235. x_api_resource_id: String(this.voiceSynthesisForm.xApiResourceId || '').trim(),
  4236. model_version: String(this.voiceSynthesisForm.model || '').trim(),
  4237. icl_speaker_id: '',
  4238. occupied: false,
  4239. created_at: new Date().toISOString(),
  4240. updated_at: new Date().toISOString()
  4241. });
  4242. manualProfile.draft_synthesis_text = this.voiceSynthesisForm.text;
  4243. manualProfile.draft_synthesis_ssml = this.voiceSynthesisForm.ssml;
  4244. manualProfile.draft_synthesis_x_api_resource_id = this.voiceSynthesisForm.xApiResourceId;
  4245. manualProfile.draft_synthesis_model = this.voiceSynthesisForm.model;
  4246. manualProfile.draft_synthesis_format = this.voiceSynthesisForm.format;
  4247. manualProfile.draft_synthesis_sample_rate = this.voiceSynthesisForm.sampleRate;
  4248. manualProfile.draft_synthesis_speech_rate = this.voiceSynthesisForm.speechRate;
  4249. manualProfile.draft_synthesis_loudness_rate = this.voiceSynthesisForm.loudnessRate;
  4250. manualProfile.draft_synthesis_emotion = this.voiceSynthesisForm.emotion;
  4251. manualProfile.draft_synthesis_emotion_scale = this.voiceSynthesisForm.emotionScale;
  4252. manualProfile.draft_synthesis_enable_subtitle = this.voiceSynthesisForm.enableSubtitle;
  4253. manualProfile.draft_synthesis_silence_duration = this.voiceSynthesisForm.silenceDuration;
  4254. manualProfile.draft_synthesis_enable_language_detector = this.voiceSynthesisForm.enableLanguageDetector;
  4255. manualProfile.draft_synthesis_disable_markdown_filter = this.voiceSynthesisForm.disableMarkdownFilter;
  4256. manualProfile.draft_synthesis_disable_emoji_filter = this.voiceSynthesisForm.disableEmojiFilter;
  4257. manualProfile.draft_synthesis_explicit_language = this.voiceSynthesisForm.explicitLanguage;
  4258. this.synthesizeVoiceProfile(manualProfile);
  4259. return;
  4260. }
  4261. this.voiceSynthesisForm.speakerId = String(profile.icl_speaker_id || profile.speaker_id || '').trim();
  4262. profile.draft_synthesis_text = this.voiceSynthesisForm.text;
  4263. profile.draft_synthesis_ssml = this.voiceSynthesisForm.ssml;
  4264. profile.draft_synthesis_x_api_resource_id = this.voiceSynthesisForm.xApiResourceId;
  4265. profile.draft_synthesis_model = this.voiceSynthesisForm.model;
  4266. profile.draft_synthesis_format = this.voiceSynthesisForm.format;
  4267. profile.draft_synthesis_sample_rate = this.voiceSynthesisForm.sampleRate;
  4268. profile.draft_synthesis_speech_rate = this.voiceSynthesisForm.speechRate;
  4269. profile.draft_synthesis_loudness_rate = this.voiceSynthesisForm.loudnessRate;
  4270. profile.draft_synthesis_emotion = this.voiceSynthesisForm.emotion;
  4271. profile.draft_synthesis_emotion_scale = this.voiceSynthesisForm.emotionScale;
  4272. profile.draft_synthesis_enable_subtitle = this.voiceSynthesisForm.enableSubtitle;
  4273. profile.draft_synthesis_silence_duration = this.voiceSynthesisForm.silenceDuration;
  4274. profile.draft_synthesis_enable_language_detector = this.voiceSynthesisForm.enableLanguageDetector;
  4275. profile.draft_synthesis_disable_markdown_filter = this.voiceSynthesisForm.disableMarkdownFilter;
  4276. profile.draft_synthesis_disable_emoji_filter = this.voiceSynthesisForm.disableEmojiFilter;
  4277. profile.draft_synthesis_explicit_language = this.voiceSynthesisForm.explicitLanguage;
  4278. this.voiceDesignError = '';
  4279. this.synthesizeVoiceProfile(profile);
  4280. }
  4281. private synthesizeVoiceBySpeakerId(speakerId: string): void {
  4282. if (this.isDirectVoiceSynthesizing) {
  4283. return;
  4284. }
  4285. const text = String(this.voiceSynthesisForm.text || '').trim();
  4286. const ssml = String(this.voiceSynthesisForm.ssml || '').trim();
  4287. if (!text && !ssml) {
  4288. this.voiceDesignError = '请输入要合成的文本内容或 SSML';
  4289. this.refreshView();
  4290. return;
  4291. }
  4292. const xApiResourceId = String(this.voiceSynthesisForm.xApiResourceId || '').trim();
  4293. const model = String(this.voiceSynthesisForm.model || '').trim();
  4294. const format = this.normalizeVoiceSynthesisFormat(this.voiceSynthesisForm.format);
  4295. const sampleRate = this.normalizeVoiceSynthesisSampleRate(this.voiceSynthesisForm.sampleRate);
  4296. const speechRate = this.clampVoiceSynthesisRate(this.voiceSynthesisForm.speechRate, 0);
  4297. const loudnessRate = this.clampVoiceSynthesisRate(this.voiceSynthesisForm.loudnessRate, 0);
  4298. const emotion = String(this.voiceSynthesisForm.emotion || '').trim();
  4299. const emotionScale = this.clampVoiceSynthesisEmotionScale(this.voiceSynthesisForm.emotionScale, 4);
  4300. const enableSubtitle = !!this.voiceSynthesisForm.enableSubtitle;
  4301. const silenceDuration = this.clampVoiceSynthesisSilenceDuration(this.voiceSynthesisForm.silenceDuration, 0);
  4302. const explicitLanguage = String(this.voiceSynthesisForm.explicitLanguage || '').trim();
  4303. this.voiceSynthesisForm = {
  4304. ...this.voiceSynthesisForm,
  4305. speakerId,
  4306. text,
  4307. ssml,
  4308. xApiResourceId,
  4309. model,
  4310. format,
  4311. sampleRate,
  4312. speechRate,
  4313. loudnessRate,
  4314. emotion,
  4315. emotionScale,
  4316. enableSubtitle,
  4317. silenceDuration,
  4318. explicitLanguage
  4319. };
  4320. this.voiceDesignError = '';
  4321. this.isDirectVoiceSynthesizing = true;
  4322. this.directVoiceSynthesisAudioUrl = '';
  4323. this.directVoiceSynthesisWorkId = '';
  4324. this.directVoiceSynthesisSpeakerId = speakerId;
  4325. this.refreshView();
  4326. this.http.post<any>(`${this.localVoiceTtsBaseUrl}/unidirectional`, {
  4327. token: this.voiceApiToken,
  4328. speaker_id: speakerId,
  4329. text,
  4330. ssml,
  4331. isStream: false,
  4332. x_api_resource_id: xApiResourceId,
  4333. model,
  4334. audio_params: {
  4335. format,
  4336. sample_rate: sampleRate,
  4337. speech_rate: speechRate,
  4338. loudness_rate: loudnessRate,
  4339. emotion,
  4340. emotion_scale: emotionScale,
  4341. enable_subtitle: enableSubtitle
  4342. },
  4343. additions: {
  4344. silence_duration: silenceDuration,
  4345. enable_language_detector: !!this.voiceSynthesisForm.enableLanguageDetector,
  4346. disable_markdown_filter: !!this.voiceSynthesisForm.disableMarkdownFilter,
  4347. disable_emoji_filter: !!this.voiceSynthesisForm.disableEmojiFilter,
  4348. ...(explicitLanguage ? { explicit_language: explicitLanguage } : {})
  4349. }
  4350. }).subscribe({
  4351. next: (res) => {
  4352. this.isDirectVoiceSynthesizing = false;
  4353. this.directVoiceSynthesisAudioUrl = String(res?.data?.audioUrl || '').trim();
  4354. this.directVoiceSynthesisWorkId = String(res?.data?.workId || '').trim();
  4355. this.directVoiceSynthesisSpeakerId = String(res?.speakerId || speakerId).trim();
  4356. if (res?.profile) {
  4357. const nextProfile = this.hydrateVoiceProfile(res.profile);
  4358. this.upsertLocalVoiceProfile(nextProfile);
  4359. this.syncVoiceProfileToBackend(nextProfile);
  4360. } else {
  4361. const matchedProfile = this.voiceProfiles.find((item) => (
  4362. String(item.icl_speaker_id || '').trim() === speakerId
  4363. || String(item.speaker_id || '').trim() === speakerId
  4364. ));
  4365. if (matchedProfile) {
  4366. const nextProfile = this.applySynthesisResponseToProfile(matchedProfile, res, {
  4367. text,
  4368. ssml,
  4369. xApiResourceId,
  4370. model,
  4371. format,
  4372. sampleRate,
  4373. speechRate,
  4374. loudnessRate,
  4375. emotion,
  4376. emotionScale,
  4377. enableSubtitle,
  4378. silenceDuration,
  4379. enableLanguageDetector: !!this.voiceSynthesisForm.enableLanguageDetector,
  4380. disableMarkdownFilter: !!this.voiceSynthesisForm.disableMarkdownFilter,
  4381. disableEmojiFilter: !!this.voiceSynthesisForm.disableEmojiFilter,
  4382. explicitLanguage
  4383. });
  4384. this.upsertLocalVoiceProfile(nextProfile);
  4385. this.syncVoiceProfileToBackend(nextProfile);
  4386. }
  4387. }
  4388. this.showToast(`✅ 已使用 speaker_id「${this.directVoiceSynthesisSpeakerId}」生成语音`, 'success');
  4389. this.refreshView();
  4390. },
  4391. error: (err) => {
  4392. this.isDirectVoiceSynthesizing = false;
  4393. this.voiceDesignError = this.getErrorText(err, '文本合成失败');
  4394. this.showToast(`❌ ${this.voiceDesignError}`, 'error');
  4395. this.refreshView();
  4396. }
  4397. });
  4398. }
  4399. synthesizeVoiceProfile(profile: VoiceProfile): void {
  4400. if (profile.is_synthesizing) {
  4401. return;
  4402. }
  4403. if (!this.canSynthesizeVoiceProfile(profile)) {
  4404. this.showToast('❌ 该音色记录缺少可用于语音合成的 speaker 标识,暂时无法进行文本合成', 'error');
  4405. return;
  4406. }
  4407. const text = String(profile.draft_synthesis_text || '').trim();
  4408. const ssml = String(profile.draft_synthesis_ssml || '').trim();
  4409. if (!text && !ssml) {
  4410. this.showToast('❌ 请输入要合成的文本内容或 SSML', 'error');
  4411. return;
  4412. }
  4413. const xApiResourceId = String(profile.draft_synthesis_x_api_resource_id || profile.x_api_resource_id || '').trim();
  4414. const model = String(profile.draft_synthesis_model || '').trim();
  4415. const format = this.normalizeVoiceSynthesisFormat(profile.draft_synthesis_format);
  4416. const sampleRate = this.normalizeVoiceSynthesisSampleRate(profile.draft_synthesis_sample_rate);
  4417. const speechRate = this.clampVoiceSynthesisRate(profile.draft_synthesis_speech_rate, 0);
  4418. const loudnessRate = this.clampVoiceSynthesisRate(profile.draft_synthesis_loudness_rate, 0);
  4419. const emotion = String(profile.draft_synthesis_emotion || '').trim();
  4420. const emotionScale = this.clampVoiceSynthesisEmotionScale(profile.draft_synthesis_emotion_scale, 4);
  4421. const enableSubtitle = !!profile.draft_synthesis_enable_subtitle;
  4422. const silenceDuration = this.clampVoiceSynthesisSilenceDuration(profile.draft_synthesis_silence_duration, 0);
  4423. const explicitLanguage = String(profile.draft_synthesis_explicit_language || '').trim();
  4424. profile.is_synthesizing = true;
  4425. this.refreshView();
  4426. this.http.post<any>(`${this.voiceTtsBaseUrl}/unidirectional`, {
  4427. token: this.voiceApiToken,
  4428. text,
  4429. ssml,
  4430. timbreId: profile.timbre_id || '',
  4431. speaker_id: profile.icl_speaker_id || profile.speaker_id || '',
  4432. isStream: false,
  4433. x_api_resource_id: xApiResourceId,
  4434. model,
  4435. audio_params: {
  4436. format,
  4437. sample_rate: sampleRate,
  4438. speech_rate: speechRate,
  4439. loudness_rate: loudnessRate,
  4440. emotion,
  4441. emotion_scale: emotionScale,
  4442. enable_subtitle: enableSubtitle
  4443. },
  4444. additions: {
  4445. silence_duration: silenceDuration,
  4446. enable_language_detector: !!profile.draft_synthesis_enable_language_detector,
  4447. disable_markdown_filter: !!profile.draft_synthesis_disable_markdown_filter,
  4448. disable_emoji_filter: !!profile.draft_synthesis_disable_emoji_filter,
  4449. ...(explicitLanguage ? { explicit_language: explicitLanguage } : {})
  4450. }
  4451. }).subscribe({
  4452. next: (res) => {
  4453. const nextProfile = res?.profile
  4454. ? this.hydrateVoiceProfile(res.profile)
  4455. : this.applySynthesisResponseToProfile(profile, res, {
  4456. text,
  4457. ssml,
  4458. xApiResourceId,
  4459. model,
  4460. format,
  4461. sampleRate,
  4462. speechRate,
  4463. loudnessRate,
  4464. emotion,
  4465. emotionScale,
  4466. enableSubtitle,
  4467. silenceDuration,
  4468. enableLanguageDetector: !!profile.draft_synthesis_enable_language_detector,
  4469. disableMarkdownFilter: !!profile.draft_synthesis_disable_markdown_filter,
  4470. disableEmojiFilter: !!profile.draft_synthesis_disable_emoji_filter,
  4471. explicitLanguage
  4472. });
  4473. nextProfile.draft_synthesis_text = text;
  4474. nextProfile.draft_synthesis_ssml = ssml;
  4475. nextProfile.draft_synthesis_x_api_resource_id = xApiResourceId;
  4476. nextProfile.draft_synthesis_model = model;
  4477. nextProfile.draft_synthesis_format = format;
  4478. nextProfile.draft_synthesis_sample_rate = sampleRate;
  4479. nextProfile.draft_synthesis_speech_rate = speechRate;
  4480. nextProfile.draft_synthesis_loudness_rate = loudnessRate;
  4481. nextProfile.draft_synthesis_emotion = emotion;
  4482. nextProfile.draft_synthesis_emotion_scale = emotionScale;
  4483. nextProfile.draft_synthesis_enable_subtitle = enableSubtitle;
  4484. nextProfile.draft_synthesis_silence_duration = silenceDuration;
  4485. nextProfile.draft_synthesis_enable_language_detector = !!profile.draft_synthesis_enable_language_detector;
  4486. nextProfile.draft_synthesis_disable_markdown_filter = !!profile.draft_synthesis_disable_markdown_filter;
  4487. nextProfile.draft_synthesis_disable_emoji_filter = !!profile.draft_synthesis_disable_emoji_filter;
  4488. nextProfile.draft_synthesis_explicit_language = explicitLanguage;
  4489. this.upsertLocalVoiceProfile(nextProfile);
  4490. this.syncVoiceProfileToBackend(nextProfile);
  4491. if (this.voiceSynthesisForm.profileId === nextProfile.id) {
  4492. this.voiceSynthesisForm = this.buildVoiceSynthesisFormFromProfile(nextProfile);
  4493. }
  4494. if (this.getVoiceProfileAudioUrl(nextProfile)) {
  4495. this.preferredVoiceProfileId = nextProfile.id;
  4496. }
  4497. this.showToast(`✅ 已为「${nextProfile.name}」生成文本音频`, 'success');
  4498. this.refreshView();
  4499. },
  4500. error: (err) => {
  4501. profile.is_synthesizing = false;
  4502. this.showToast(`❌ ${this.getErrorText(err, '文本合成失败')}`, 'error');
  4503. this.refreshView();
  4504. }
  4505. });
  4506. }
  4507. removeVoiceProfile(profile: VoiceProfile): void {
  4508. if (!confirm(`确定要删除音色「${profile.name}」吗?`)) {
  4509. return;
  4510. }
  4511. this.http.delete<any>(`/backend/voice-profiles/${profile.id}`).subscribe({
  4512. next: () => {
  4513. this.voiceProfiles = this.voiceProfiles.filter(item => item.id !== profile.id);
  4514. this.syncVoiceSynthesisFormSelection();
  4515. if (this.preferredVoiceProfileId === profile.id) {
  4516. this.preferredVoiceProfileId = '';
  4517. }
  4518. this.showToast(`🗑️ 已删除音色「${profile.name}」`, 'success');
  4519. this.refreshView();
  4520. },
  4521. error: (err) => {
  4522. this.showToast(`❌ ${this.getErrorText(err, '删除音色失败')}`, 'error');
  4523. }
  4524. });
  4525. }
  4526. onRemixDigitalHumanImageSelected(event: Event): void {
  4527. const input = event.target as HTMLInputElement;
  4528. if (!input.files || input.files.length === 0) {
  4529. return;
  4530. }
  4531. const file = input.files[0];
  4532. const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
  4533. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  4534. const allowedExts = ['.jpg', '.jpeg', '.png', '.gif'];
  4535. if ((!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) || file.size <= 0) {
  4536. this.remixDigitalHumanError = '仅支持 jpg、jpeg、png、gif 格式的形象图';
  4537. input.value = '';
  4538. this.refreshView();
  4539. return;
  4540. }
  4541. if (file.size > 20 * 1024 * 1024) {
  4542. this.remixDigitalHumanError = '形象图大小不能超过 20MB';
  4543. input.value = '';
  4544. this.refreshView();
  4545. return;
  4546. }
  4547. this.revokeDigitalHumanPreviewUrl();
  4548. this.remixDigitalHumanImageFile = file;
  4549. this.remixDigitalHumanImageName = file.name;
  4550. this.remixDigitalHumanImagePreviewUrl = URL.createObjectURL(file);
  4551. this.remixDigitalHumanImageAssetUrl = '';
  4552. this.remixDigitalHumanError = '';
  4553. input.value = '';
  4554. this.refreshView();
  4555. }
  4556. clearRemixDigitalHumanImage(): void {
  4557. this.revokeDigitalHumanPreviewUrl();
  4558. this.remixDigitalHumanImageFile = null;
  4559. this.remixDigitalHumanImageName = '';
  4560. this.remixDigitalHumanImageAssetUrl = '';
  4561. this.remixDigitalHumanError = '';
  4562. this.refreshView();
  4563. }
  4564. goToRemixGenerationConfig(): void {
  4565. if (this.remixMode === 'digital-human') {
  4566. if (!this.remixDigitalHumanImageFile) {
  4567. this.remixDigitalHumanError = '请先上传数字人形象图';
  4568. this.refreshView();
  4569. return;
  4570. }
  4571. if (this.remixPortraitPipelineRunning) {
  4572. this.remixDigitalHumanError = '形象图正在生成中,请稍候...';
  4573. this.refreshView();
  4574. return;
  4575. }
  4576. if (this.remixPortraitPrepareMode !== 'raw' && !this.remixGeneratedPortraitUrl) {
  4577. this.remixDigitalHumanError = '请先点击「生成形象图」完成 AI 处理,或切换到「直接使用上传图」';
  4578. this.refreshView();
  4579. return;
  4580. }
  4581. this.remixDigitalHumanError = '';
  4582. this.remixStep = 4;
  4583. this.refreshView();
  4584. return;
  4585. }
  4586. this.confirmTranscript();
  4587. }
  4588. private revokeDigitalHumanPreviewUrl(): void {
  4589. if (this.remixDigitalHumanImagePreviewUrl) {
  4590. URL.revokeObjectURL(this.remixDigitalHumanImagePreviewUrl);
  4591. this.remixDigitalHumanImagePreviewUrl = '';
  4592. }
  4593. }
  4594. private resetDigitalHumanState(): void {
  4595. this.revokeDigitalHumanPreviewUrl();
  4596. this.remixDigitalHumanImageFile = null;
  4597. this.remixDigitalHumanImageName = '';
  4598. this.remixDigitalHumanImageAssetUrl = '';
  4599. this.remixDigitalHumanPrompt = '';
  4600. this.remixDigitalHumanFastMode = false;
  4601. this.remixDigitalHumanResolution = '1080p';
  4602. this.remixDigitalHumanError = '';
  4603. this.remixDigitalHumanAudioSource = 'tts';
  4604. this.remixDigitalHumanTtsText = '';
  4605. this.remixDigitalHumanTtsTimbreId = '';
  4606. this.remixDigitalHumanTtsSynthesizing = false;
  4607. this.resetPortraitPipelineState();
  4608. }
  4609. // ===== 数字人形象准备:自拍优化 / 对标重塑 =====
  4610. setRemixPortraitPrepareMode(mode: 'raw' | 'normalize' | 'benchmark'): void {
  4611. if (this.remixPortraitPipelineRunning) {
  4612. return;
  4613. }
  4614. this.remixPortraitPrepareMode = mode;
  4615. // 切换模式时清空已生成结果,避免误用
  4616. this.remixGeneratedPortraitUrl = '';
  4617. this.remixGeneratedFullBodyUrl = '';
  4618. this.remixGeneratedBenchmarkSummary = '';
  4619. this.remixPortraitPipelineError = '';
  4620. this.remixPortraitPipelineStatus = '';
  4621. this.remixPortraitPipelineProgress = 0;
  4622. if (mode !== 'benchmark') {
  4623. this.clearRemixBenchmarkImage();
  4624. }
  4625. this.refreshView();
  4626. }
  4627. onRemixBenchmarkImageSelected(event: Event): void {
  4628. const input = event.target as HTMLInputElement;
  4629. if (!input.files || input.files.length === 0) {
  4630. return;
  4631. }
  4632. const file = input.files[0];
  4633. const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/webp'];
  4634. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  4635. const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  4636. if ((!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) || file.size <= 0) {
  4637. this.remixPortraitPipelineError = '对标场景图仅支持 jpg、jpeg、png、gif、webp 格式';
  4638. input.value = '';
  4639. this.refreshView();
  4640. return;
  4641. }
  4642. if (file.size > 20 * 1024 * 1024) {
  4643. this.remixPortraitPipelineError = '对标场景图大小不能超过 20MB';
  4644. input.value = '';
  4645. this.refreshView();
  4646. return;
  4647. }
  4648. this.revokeBenchmarkPreviewUrl();
  4649. this.remixBenchmarkImageFile = file;
  4650. this.remixBenchmarkImageName = file.name;
  4651. this.remixBenchmarkImagePreviewUrl = URL.createObjectURL(file);
  4652. this.remixPortraitPipelineError = '';
  4653. this.remixGeneratedPortraitUrl = '';
  4654. input.value = '';
  4655. this.refreshView();
  4656. }
  4657. clearRemixBenchmarkImage(): void {
  4658. this.revokeBenchmarkPreviewUrl();
  4659. this.remixBenchmarkImageFile = null;
  4660. this.remixBenchmarkImageName = '';
  4661. this.refreshView();
  4662. }
  4663. private revokeBenchmarkPreviewUrl(): void {
  4664. if (this.remixBenchmarkImagePreviewUrl) {
  4665. URL.revokeObjectURL(this.remixBenchmarkImagePreviewUrl);
  4666. this.remixBenchmarkImagePreviewUrl = '';
  4667. }
  4668. }
  4669. private resetPortraitPipelineState(): void {
  4670. this.remixPortraitPrepareMode = 'raw';
  4671. this.revokeBenchmarkPreviewUrl();
  4672. this.remixBenchmarkImageFile = null;
  4673. this.remixBenchmarkImageName = '';
  4674. this.remixPortraitPipelineRunning = false;
  4675. this.remixPortraitPipelineStatus = '';
  4676. this.remixPortraitPipelineProgress = 0;
  4677. this.remixPortraitPipelineError = '';
  4678. this.remixGeneratedPortraitUrl = '';
  4679. this.remixGeneratedFullBodyUrl = '';
  4680. this.remixGeneratedBenchmarkSummary = '';
  4681. }
  4682. /**
  4683. * 一键执行形象准备链路:
  4684. * - normalize: 仅 Step1 自拍 → 正面全身图
  4685. * - benchmark: Step1 + Step2 + Step3 对标重塑
  4686. */
  4687. runPortraitPipeline(): void {
  4688. if (this.remixPortraitPipelineRunning) {
  4689. return;
  4690. }
  4691. if (!this.remixDigitalHumanImageFile) {
  4692. this.remixPortraitPipelineError = '请先上传人物自拍/形象图';
  4693. this.refreshView();
  4694. return;
  4695. }
  4696. if (this.remixPortraitPrepareMode === 'benchmark' && !this.remixBenchmarkImageFile) {
  4697. this.remixPortraitPipelineError = '请上传一张对标账号的场景图';
  4698. this.refreshView();
  4699. return;
  4700. }
  4701. this.remixPortraitPipelineRunning = true;
  4702. this.remixPortraitPipelineError = '';
  4703. this.remixPortraitPipelineProgress = 0;
  4704. this.remixPortraitPipelineStatus = '正在上传素材...';
  4705. this.refreshView();
  4706. const selfieFile = this.remixDigitalHumanImageFile;
  4707. const benchmarkFile = this.remixPortraitPrepareMode === 'benchmark' ? this.remixBenchmarkImageFile : null;
  4708. // 1) 上传自拍 → URL
  4709. this.jimengService.uploadFileToParse(
  4710. selfieFile,
  4711. `portrait-selfie-${Date.now()}-${selfieFile.name}`,
  4712. selfieFile.type || 'image/jpeg'
  4713. ).subscribe({
  4714. next: (selfieUrl: string) => {
  4715. // 2) 如需对标,先上传对标图
  4716. const benchmarkUpload$ = benchmarkFile
  4717. ? this.jimengService.uploadFileToParse(
  4718. benchmarkFile,
  4719. `portrait-benchmark-${Date.now()}-${benchmarkFile.name}`,
  4720. benchmarkFile.type || 'image/jpeg'
  4721. )
  4722. : null;
  4723. const next = (benchmarkUrl: string | null) => {
  4724. this.portraitPipeline.buildBenchmarkedPortrait(selfieUrl, benchmarkUrl, (status, progress) => {
  4725. this.ngZone.run(() => {
  4726. this.remixPortraitPipelineStatus = status;
  4727. this.remixPortraitPipelineProgress = Math.round(progress);
  4728. this.refreshView();
  4729. });
  4730. }).subscribe({
  4731. next: (result: PortraitPipelineResult) => {
  4732. this.ngZone.run(() => {
  4733. this.remixGeneratedFullBodyUrl = result.fullBodyUrl;
  4734. this.remixGeneratedPortraitUrl = result.finalPortraitUrl;
  4735. this.remixGeneratedBenchmarkSummary = result.benchmarkPrompt?.merged || '';
  4736. this.remixPortraitPipelineRunning = false;
  4737. this.remixPortraitPipelineStatus = '形象图生成完成';
  4738. this.remixPortraitPipelineProgress = 100;
  4739. this.showToast('✅ 形象图生成完成,可继续配置数字人参数', 'success');
  4740. this.refreshView();
  4741. });
  4742. },
  4743. error: (err) => {
  4744. this.ngZone.run(() => {
  4745. this.remixPortraitPipelineRunning = false;
  4746. this.remixPortraitPipelineError = this.getErrorText(err, '形象图生成失败');
  4747. this.showToast(`❌ ${this.remixPortraitPipelineError}`, 'error');
  4748. this.refreshView();
  4749. });
  4750. }
  4751. });
  4752. };
  4753. if (benchmarkUpload$) {
  4754. benchmarkUpload$.subscribe({
  4755. next: (benchmarkUrl: string) => next(benchmarkUrl),
  4756. error: (err) => {
  4757. this.ngZone.run(() => {
  4758. this.remixPortraitPipelineRunning = false;
  4759. this.remixPortraitPipelineError = this.getErrorText(err, '对标场景图上传失败');
  4760. this.showToast(`❌ ${this.remixPortraitPipelineError}`, 'error');
  4761. this.refreshView();
  4762. });
  4763. }
  4764. });
  4765. } else {
  4766. next(null);
  4767. }
  4768. },
  4769. error: (err) => {
  4770. this.ngZone.run(() => {
  4771. this.remixPortraitPipelineRunning = false;
  4772. this.remixPortraitPipelineError = this.getErrorText(err, '形象图上传失败');
  4773. this.showToast(`❌ ${this.remixPortraitPipelineError}`, 'error');
  4774. this.refreshView();
  4775. });
  4776. }
  4777. });
  4778. }
  4779. resetGeneratedPortrait(): void {
  4780. if (this.remixPortraitPipelineRunning) {
  4781. return;
  4782. }
  4783. this.remixGeneratedPortraitUrl = '';
  4784. this.remixGeneratedFullBodyUrl = '';
  4785. this.remixGeneratedBenchmarkSummary = '';
  4786. this.remixPortraitPipelineStatus = '';
  4787. this.remixPortraitPipelineProgress = 0;
  4788. this.remixPortraitPipelineError = '';
  4789. this.refreshView();
  4790. }
  4791. // ===== 数字人共享表单:选项与回调(用于 <app-digital-human-form>)=====
  4792. get remixTimbreOptions(): TimbreOption[] {
  4793. return (this.vsClonedTimbreList || []).map(t => ({
  4794. id: t.objectId,
  4795. name: t.name || t.objectId
  4796. }));
  4797. }
  4798. readonly digitalHumanPromptPresets: PromptPreset[] = [
  4799. { label: '专业播报', value: '以新闻主播的语气朗读,吐字清晰、节奏稳定、表情自信端正。' },
  4800. { label: '亲切自然', value: '用朋友聊天的语气,亲切自然、面带微笑,语速适中略带轻松感。' },
  4801. { label: '科技感', value: '冷静理性的科技感口吻,节奏明快、抑扬有度,强调数据与关键词。' },
  4802. { label: '激情澎湃', value: '激情澎湃的演说家口吻,情感饱满、节奏起伏明显、富有感染力。' },
  4803. { label: '温柔治愈', value: '温柔轻缓的语气,气息柔和、节奏放慢,适合情感与生活类内容。' },
  4804. { label: '正式商务', value: '商务正式风格,语调克制、用词严谨,仪态端庄,适合企业宣传场景。' },
  4805. ];
  4806. /**
  4807. * 视频重塑里:<app-digital-human-form> 的 (request) 事件入口。
  4808. * 接管 startDigitalHumanGeneration 的全部任务管理逻辑,
  4809. * 内部链路改用 DigitalHumanService 编排执行。
  4810. */
  4811. onRemixDhRequest(req: DigitalHumanRequest): void {
  4812. const video = this.remixTargetVideo;
  4813. if (!video || this.isRemixSubmitting) {
  4814. return;
  4815. }
  4816. // 原视频音频时长校验(保留旧约束)
  4817. if (req.audio.source === 'original') {
  4818. const safeDuration = Number(video.duration || 0);
  4819. if (safeDuration > 60) {
  4820. this.remixDigitalHumanError = '原视频音频时长超过 60 秒,当前数字人接口不支持';
  4821. this.showToast(`❌ ${this.remixDigitalHumanError}`, 'error');
  4822. this.refreshView();
  4823. return;
  4824. }
  4825. }
  4826. // 同步音频来源到旧字段,让 step 5/6 已有 UI 仍能显示
  4827. this.remixDigitalHumanAudioSource = req.audio.source === 'tts' ? 'tts' : 'original';
  4828. this.remixDigitalHumanResolution = req.resolution || '1080p';
  4829. this.remixDigitalHumanFastMode = !!req.fastMode;
  4830. this.remixDigitalHumanPrompt = req.prompt || '';
  4831. if (req.audio.source === 'tts') {
  4832. this.remixDigitalHumanTtsText = req.audio.ttsText || '';
  4833. this.remixDigitalHumanTtsTimbreId = req.audio.ttsTimbreId || '';
  4834. }
  4835. // 注入原视频 ID(form 没有这个字段,由父组件补齐)
  4836. if (req.audio.source === 'original' && !req.audio.videoId) {
  4837. req.audio.videoId = video.id;
  4838. }
  4839. const styleName = '数字人生成';
  4840. this.isRemixSubmitting = true;
  4841. this.remixStep = 5;
  4842. video.isRemixing = true;
  4843. video.remixProgress = 0;
  4844. video.remixStyle = styleName;
  4845. this.remixResults = { total: 1, success: 0, failed: 0 };
  4846. this.remixStatusText = '正在准备数字人素材...';
  4847. this.remixStitchStatus = 'idle';
  4848. this.remixStitchError = '';
  4849. this.remixFinalVideoUrl = '';
  4850. this.currentRemixId = `REMIX-${Date.now()}`;
  4851. const newTask: Task = {
  4852. id: `TASK-${Date.now()}`,
  4853. keyword: `${video.title} - ${styleName}`,
  4854. status: 'processing',
  4855. step: 'generate',
  4856. progress: 0,
  4857. cost: 0,
  4858. created_at: new Date(),
  4859. updated_at: new Date(),
  4860. original_video_title: video.title,
  4861. duration: '数字人视频'
  4862. };
  4863. this.activeTasks.unshift(newTask);
  4864. this.currentRemixTaskId = newTask.id;
  4865. this.saveTask(newTask);
  4866. this.showToast('数字人任务已提交,可在「任务管理」中查看进度', 'success');
  4867. this.showRemixModal = false;
  4868. this.digitalHumanService.generate(req).subscribe({
  4869. next: (evt: DigitalHumanEvent) => {
  4870. this.ngZone.run(() => {
  4871. if (evt.type === 'progress') {
  4872. video.remixProgress = evt.progress;
  4873. this.remixStatusText = evt.status;
  4874. this.updateRemixTaskProgress('generate', evt.progress);
  4875. this.refreshView();
  4876. } else {
  4877. // result
  4878. video.remixProgress = 100;
  4879. this.remixResults.success = 1;
  4880. this.remixFinalVideoUrl = evt.videoUrl;
  4881. this.remixStatusText = '数字人视频生成完成';
  4882. this.remixDigitalHumanImageAssetUrl = evt.imageUrl;
  4883. this.createDigitalHumanVersion(video, evt.videoUrl);
  4884. this.completeRemixTask('completed', evt.videoUrl);
  4885. this.saveRemixSession('completed');
  4886. video.isRemixing = false;
  4887. this.isRemixSubmitting = false;
  4888. this.remixStep = 6;
  4889. this.showToast(`✅ 数字人视频已生成:${video.title}`, 'success', 6000);
  4890. this.refreshView();
  4891. }
  4892. });
  4893. },
  4894. error: (err: any) => {
  4895. this.ngZone.run(() => {
  4896. this.handleDigitalHumanGenerationError(video, this.getErrorText(err, '数字人生成失败'));
  4897. });
  4898. }
  4899. });
  4900. }
  4901. // 加载该视频关联的 Whisper 处理文件(通过后端读取)
  4902. loadWhisperFiles(video: ManagedVideo): void {
  4903. if (!video.whisper) {
  4904. console.log('ℹ️ 该视频无 Whisper 转录数据,跳过自动加载');
  4905. return;
  4906. }
  4907. const w = video.whisper;
  4908. // 优先加载美化文字稿,其次原始转录
  4909. const transcriptPath = w.beautified || w.transcript;
  4910. if (transcriptPath) {
  4911. this.http.get(`/backend/files/read`, { params: { path: transcriptPath }, responseType: 'text' }).subscribe({
  4912. next: (text) => {
  4913. this.remixTranscript = text;
  4914. if (w.beautified) this.remixBeautifiedTranscript = text;
  4915. console.log(`📄 已加载 Whisper 文字稿: ${transcriptPath}`);
  4916. },
  4917. error: () => console.log(`⚠️ 未能加载文字稿: ${transcriptPath}`)
  4918. });
  4919. }
  4920. // 加载分镜脚本
  4921. if (w.storyboard) {
  4922. this.http.get<any>(`/backend/files/read`, { params: { path: w.storyboard } }).subscribe({
  4923. next: (data: any) => {
  4924. if (Array.isArray(data)) {
  4925. this.remixStoryboard = data.map((seg: any) => ({
  4926. id: seg.id,
  4927. act: seg.act,
  4928. narration: seg.narration,
  4929. prompt: seg.prompt,
  4930. duration: seg.duration,
  4931. status: 'pending' as const
  4932. }));
  4933. console.log(`📝 已加载分镜脚本: ${this.remixStoryboard.length} 个片段`);
  4934. }
  4935. },
  4936. error: () => console.log(`⚠️ 未能加载分镜脚本: ${w.storyboard}`)
  4937. });
  4938. }
  4939. }
  4940. // 下一步
  4941. nextRemixStep(): void {
  4942. if (this.remixStep < 6) this.remixStep++;
  4943. }
  4944. // 上一步
  4945. prevRemixStep(): void {
  4946. if (this.remixStep > 1 && !this.isRemixSubmitting) this.remixStep--;
  4947. }
  4948. // 使用 Whisper 生成文字稿(通过本地后端)
  4949. generateTranscript(): void {
  4950. if (!this.remixTargetVideo || this.isWhisperRunning) return;
  4951. const video = this.remixTargetVideo;
  4952. this.isWhisperRunning = true;
  4953. this.whisperStatusText = '正在检查 Whisper 服务...';
  4954. // 先检查后端是否可用
  4955. this.http.get<any>('/backend/api/health').subscribe({
  4956. next: () => {
  4957. // 后端可用,调用 Whisper 转录
  4958. this.whisperStatusText = '正在调用 Whisper 语音识别,视频较长时可能需要数分钟...';
  4959. this.http.post<any>('/backend/api/whisper/transcribe', {
  4960. videoId: video.id,
  4961. language: 'Chinese',
  4962. model: 'base'
  4963. }).subscribe({
  4964. next: (res: any) => {
  4965. if (res?.success && res?.transcript) {
  4966. this.remixTranscript = res.transcript;
  4967. this.whisperStatusText = '✅ 识别完成!';
  4968. this.isWhisperRunning = false;
  4969. // 后端已自动更新 manifest,同步前端的 whisper 字段
  4970. if (res.whisper) {
  4971. video.whisper = res.whisper;
  4972. }
  4973. console.log('✅ Whisper 转录完成,manifest 已更新');
  4974. } else {
  4975. this.whisperStatusText = '识别完成但未返回文字稿';
  4976. this.isWhisperRunning = false;
  4977. this.showManualTranscriptInput = true;
  4978. }
  4979. },
  4980. error: (err) => {
  4981. console.error('Whisper 转录失败:', err);
  4982. const msg = err?.error?.error || err?.error?.hint || '转录过程出错';
  4983. this.whisperStatusText = `❌ ${msg}`;
  4984. this.isWhisperRunning = false;
  4985. this.showManualTranscriptInput = true;
  4986. }
  4987. });
  4988. },
  4989. error: () => {
  4990. // 后端不可用,降级为手动方案
  4991. this.onWhisperFallback(video);
  4992. }
  4993. });
  4994. }
  4995. // 后端不可用时的降级方案
  4996. private onWhisperFallback(video: ManagedVideo): void {
  4997. this.isWhisperRunning = false;
  4998. this.whisperStatusText = '';
  4999. const cmd = `whisper "data/videos/${video.filename}" --model base --language Chinese --output_dir "Whisper"`;
  5000. navigator.clipboard.writeText(cmd).then(() => {
  5001. alert(
  5002. `后端服务未启动。请先在终端运行:\n\nnpm run server\n\n` +
  5003. `或手动执行 Whisper 命令(已复制到剪贴板):\n\n${cmd}`
  5004. );
  5005. }).catch(() => {
  5006. alert(`后端服务未启动。请先运行 npm run server,或手动执行:\n\n${cmd}`);
  5007. });
  5008. this.showManualTranscriptInput = true;
  5009. }
  5010. // Step 1 → 2: 确认文字稿,进入AI美化
  5011. confirmTranscript(): void {
  5012. if (!this.remixTranscript.trim()) return;
  5013. this.remixStep = 2;
  5014. // 自动执行AI美化
  5015. this.beautifyTranscript();
  5016. }
  5017. // Step 2: AI美化文字稿(当前为本地处理,后续可接入LLM API)
  5018. beautifyTranscript(): void {
  5019. let text = this.remixTranscript;
  5020. // 去除口语化词汇
  5021. const fillerWords = ['嗯', '啊', '呢', '吧', '哦', '额', '那个', '就是说', '然后呢', '对吧'];
  5022. fillerWords.forEach(w => { text = text.replace(new RegExp(w, 'g'), ''); });
  5023. // 去除多余空格和空行
  5024. text = text.replace(/\s+/g, ' ').trim();
  5025. // 按句号/问号/感叹号分句,重新组织段落
  5026. const sentences = text.split(/(?<=[。!?.!?])/g).filter(s => s.trim());
  5027. const paragraphs: string[] = [];
  5028. let current = '';
  5029. sentences.forEach(s => {
  5030. current += s.trim();
  5031. if (current.length >= 60) {
  5032. paragraphs.push(current);
  5033. current = '';
  5034. }
  5035. });
  5036. if (current) paragraphs.push(current);
  5037. this.remixBeautifiedTranscript = paragraphs.join('\n\n');
  5038. if (!this.remixBeautifiedTranscript.trim()) {
  5039. this.remixBeautifiedTranscript = this.remixTranscript;
  5040. }
  5041. }
  5042. // Step 2 → 3: 确认美化文字稿,生成分镜脚本
  5043. confirmBeautified(): void {
  5044. if (!this.remixBeautifiedTranscript.trim()) return;
  5045. this.generateStoryboard();
  5046. this.remixStep = 3;
  5047. }
  5048. // Step 3: 根据美化文字稿生成分镜脚本(参考SKILL.md Stage 1)
  5049. generateStoryboard(): void {
  5050. const text = this.remixBeautifiedTranscript;
  5051. // 按约40-45个中文字(≈15秒语速)拆分为分镜段
  5052. const segmentCharLen = 42;
  5053. const segments: StoryboardSegment[] = [];
  5054. // 优先按段落分割
  5055. const paragraphs = text.split(/\n+/).filter(p => p.trim());
  5056. let charBuffer = '';
  5057. let segIndex = 0;
  5058. const pushSegment = (narration: string) => {
  5059. segIndex++;
  5060. const id = `S-${String(segIndex).padStart(2, '0')}`;
  5061. const act = segIndex === 1 ? '开场' : (segIndex <= 3 ? '引入' : '正文');
  5062. const stylePrompt = this.remixStyleOptions.find(s => s.id === this.remixStyle)?.prompt || '';
  5063. // 生成英文提示词:风格 + 场景描述
  5064. const prompt = `${stylePrompt}, cinematic scene depicting: ${narration.substring(0, 80)}`;
  5065. segments.push({
  5066. id,
  5067. act,
  5068. narration: narration.trim(),
  5069. prompt,
  5070. duration: this.remixFrames === 121 ? '5s' : '10s',
  5071. status: 'pending'
  5072. });
  5073. };
  5074. paragraphs.forEach(para => {
  5075. charBuffer += para;
  5076. while (charBuffer.length >= segmentCharLen) {
  5077. // 尝试在句子边界切割
  5078. let cutPos = segmentCharLen;
  5079. const searchRange = charBuffer.substring(0, segmentCharLen + 15);
  5080. const punctPos = Math.max(
  5081. searchRange.lastIndexOf('。'),
  5082. searchRange.lastIndexOf('!'),
  5083. searchRange.lastIndexOf('?'),
  5084. searchRange.lastIndexOf(','),
  5085. searchRange.lastIndexOf(';')
  5086. );
  5087. if (punctPos > segmentCharLen * 0.5) cutPos = punctPos + 1;
  5088. pushSegment(charBuffer.substring(0, cutPos));
  5089. charBuffer = charBuffer.substring(cutPos);
  5090. }
  5091. });
  5092. // 剩余部分
  5093. if (charBuffer.trim().length > 0) {
  5094. pushSegment(charBuffer);
  5095. }
  5096. this.remixStoryboard = segments;
  5097. console.log(`📝 分镜脚本生成完毕:${segments.length} 个片段`);
  5098. }
  5099. // Step 3 → 4: 确认分镜,进入参数配置
  5100. confirmStoryboard(): void {
  5101. if (this.remixStoryboard.length === 0) return;
  5102. this.remixStep = 4;
  5103. }
  5104. // Step 4 → 5: 开始批量生成
  5105. startBatchGeneration(): void {
  5106. if (this.isRemixSubmitting) return;
  5107. if (this.remixMode === 'digital-human') {
  5108. this.startDigitalHumanGeneration();
  5109. return;
  5110. }
  5111. if (this.remixStoryboard.length === 0) return;
  5112. const video = this.remixTargetVideo!;
  5113. const styleName = this.remixStyleOptions.find(s => s.id === this.remixStyle)?.name || this.remixStyle;
  5114. this.isRemixSubmitting = true;
  5115. this.remixStep = 5;
  5116. video.isRemixing = true;
  5117. video.remixProgress = 0;
  5118. video.remixStyle = styleName;
  5119. this.remixResults = { total: this.remixStoryboard.length, success: 0, failed: 0 };
  5120. this.remixStatusText = '正在提交生成任务...';
  5121. this.currentRemixId = `REMIX-${Date.now()}`;
  5122. // 创建持久化任务
  5123. const newTask: Task = {
  5124. id: `TASK-${Date.now()}`,
  5125. keyword: `${video.title} - ${styleName}`,
  5126. status: 'processing',
  5127. step: 'generate',
  5128. progress: 0,
  5129. cost: 0,
  5130. created_at: new Date(),
  5131. updated_at: new Date(),
  5132. original_video_title: video.title,
  5133. duration: `${this.remixStoryboard.length} 个片段`
  5134. };
  5135. this.activeTasks.unshift(newTask);
  5136. this.currentRemixTaskId = newTask.id;
  5137. this.saveTask(newTask);
  5138. // 显示 toast 并关闭模态框
  5139. this.showToast(`任务已提交,可在「任务管理」中查看进度`, 'success');
  5140. this.showRemixModal = false;
  5141. console.log(`🎨 开始批量生成 ${this.remixStoryboard.length} 个分镜视频, 任务ID: ${newTask.id}`);
  5142. // 逐个提交(串行,避免频率限制)
  5143. this.generateSegmentSequentially(0, video, styleName);
  5144. }
  5145. private startDigitalHumanGeneration(): void {
  5146. if (!this.remixTargetVideo || !this.remixDigitalHumanImageFile || this.isRemixSubmitting) {
  5147. return;
  5148. }
  5149. const video = this.remixTargetVideo;
  5150. const isTtsMode = this.remixDigitalHumanAudioSource === 'tts';
  5151. if (!isTtsMode) {
  5152. const safeDuration = Number(video.duration || 0);
  5153. if (safeDuration > 60) {
  5154. this.remixDigitalHumanError = '原视频音频时长超过 60 秒,当前数字人接口不支持';
  5155. this.showToast(`❌ ${this.remixDigitalHumanError}`, 'error');
  5156. this.refreshView();
  5157. return;
  5158. }
  5159. }
  5160. if (isTtsMode) {
  5161. if (!this.remixDigitalHumanTtsTimbreId.trim()) {
  5162. this.remixDigitalHumanError = '请输入或选择音色 ID(可在「语音合成」标签页中复刻获取)';
  5163. this.refreshView();
  5164. return;
  5165. }
  5166. if (!this.remixDigitalHumanTtsText.trim()) {
  5167. this.remixDigitalHumanError = '请输入要合成的语音文本';
  5168. this.refreshView();
  5169. return;
  5170. }
  5171. }
  5172. const styleName = '数字人生成';
  5173. this.isRemixSubmitting = true;
  5174. this.remixStep = 5;
  5175. video.isRemixing = true;
  5176. video.remixProgress = 0;
  5177. video.remixStyle = styleName;
  5178. this.remixResults = { total: 1, success: 0, failed: 0 };
  5179. this.remixStatusText = '正在准备数字人素材...';
  5180. this.remixStitchStatus = 'idle';
  5181. this.remixStitchError = '';
  5182. this.remixFinalVideoUrl = '';
  5183. this.currentRemixId = `REMIX-${Date.now()}`;
  5184. const newTask: Task = {
  5185. id: `TASK-${Date.now()}`,
  5186. keyword: `${video.title} - ${styleName}`,
  5187. status: 'processing',
  5188. step: 'generate',
  5189. progress: 0,
  5190. cost: 0,
  5191. created_at: new Date(),
  5192. updated_at: new Date(),
  5193. original_video_title: video.title,
  5194. duration: '数字人视频'
  5195. };
  5196. this.activeTasks.unshift(newTask);
  5197. this.currentRemixTaskId = newTask.id;
  5198. this.saveTask(newTask);
  5199. this.showToast('数字人任务已提交,可在「任务管理」中查看进度', 'success');
  5200. this.showRemixModal = false;
  5201. // 若已通过形象准备链路生成对标/规范化形象图,则直接复用其 URL,跳过原图上传
  5202. const ensureImage$: Observable<string> = this.remixGeneratedPortraitUrl
  5203. ? of(this.remixGeneratedPortraitUrl)
  5204. : this.jimengService.uploadFileToParse(
  5205. this.remixDigitalHumanImageFile,
  5206. `digital-human-${Date.now()}-${this.remixDigitalHumanImageFile.name}`,
  5207. this.remixDigitalHumanImageFile.type || 'image/jpeg'
  5208. );
  5209. ensureImage$.subscribe({
  5210. next: (imageUrl: string) => {
  5211. this.remixDigitalHumanImageAssetUrl = imageUrl;
  5212. video.remixProgress = 10;
  5213. this.updateRemixTaskProgress('generate', 10);
  5214. if (isTtsMode) {
  5215. this.remixStatusText = '形象图上传完成,正在合成语音...';
  5216. this.remixDigitalHumanTtsSynthesizing = true;
  5217. this.refreshView();
  5218. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/unidirectional', {
  5219. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600',
  5220. text: this.remixDigitalHumanTtsText.trim(),
  5221. timbreId: this.remixDigitalHumanTtsTimbreId.trim(),
  5222. isStream: false,
  5223. audio_params: {
  5224. format: 'mp3',
  5225. sample_rate: 24000,
  5226. speech_rate: 0,
  5227. loudness_rate: 0
  5228. }
  5229. }).subscribe({
  5230. next: (res) => {
  5231. this.remixDigitalHumanTtsSynthesizing = false;
  5232. if (res?.code === 200 && res?.data?.audioUrl) {
  5233. video.remixProgress = 30;
  5234. this.remixStatusText = '语音合成完成,正在识别数字人主体...';
  5235. this.updateRemixTaskProgress('generate', 30);
  5236. this.startDigitalHumanGenerationWithAudio(video, imageUrl, res.data.audioUrl);
  5237. } else {
  5238. this.handleDigitalHumanGenerationError(video, res?.error?.message || '语音合成失败,请检查音色ID和文本');
  5239. }
  5240. },
  5241. error: (err) => {
  5242. this.remixDigitalHumanTtsSynthesizing = false;
  5243. this.handleDigitalHumanGenerationError(video, this.getErrorText(err, '语音合成请求失败'));
  5244. }
  5245. });
  5246. } else {
  5247. this.remixStatusText = '形象图上传完成,正在提取原视频音频...';
  5248. this.refreshView();
  5249. this.http.post('/backend/api/remix/extract-audio', {
  5250. videoId: video.id
  5251. }, {
  5252. responseType: 'blob'
  5253. }).subscribe({
  5254. next: (audioBlob: Blob) => {
  5255. const audioFile = new File(
  5256. [audioBlob],
  5257. `${video.filename.replace(/\.[^.]+$/, '') || 'source-audio'}.wav`,
  5258. { type: audioBlob.type || 'audio/wav' }
  5259. );
  5260. video.remixProgress = 20;
  5261. this.remixStatusText = '音频提取完成,正在上传音频素材...';
  5262. this.updateRemixTaskProgress('generate', 20);
  5263. this.jimengService.uploadFileToParse(audioFile, audioFile.name, audioFile.type).subscribe({
  5264. next: (audioUrl: string) => {
  5265. video.remixProgress = 30;
  5266. this.remixStatusText = '素材准备完成,正在识别数字人主体...';
  5267. this.updateRemixTaskProgress('generate', 30);
  5268. this.startDigitalHumanGenerationWithAudio(video, imageUrl, audioUrl);
  5269. },
  5270. error: (err) => {
  5271. this.handleDigitalHumanGenerationError(video, err?.message || '上传音频素材失败');
  5272. }
  5273. });
  5274. },
  5275. error: async (err) => {
  5276. const message = await this.extractHttpBlobErrorMessage(err, '提取原视频音频失败,请确认已安装 ffmpeg');
  5277. this.handleDigitalHumanGenerationError(video, message);
  5278. }
  5279. });
  5280. }
  5281. },
  5282. error: (err) => {
  5283. this.handleDigitalHumanGenerationError(video, err?.message || '上传数字人形象图失败');
  5284. }
  5285. });
  5286. }
  5287. private startDigitalHumanGenerationWithAudio(video: ManagedVideo, imageUrl: string, audioUrl: string): void {
  5288. this.jimengService.identifyDigitalHuman(imageUrl).subscribe({
  5289. next: ({ workId }) => {
  5290. this.jimengService.pollDigitalHumanIdentifyUntilReady(workId, (status, progress) => {
  5291. const mappedProgress = Math.min(30 + progress * 0.2, 50);
  5292. video.remixProgress = mappedProgress;
  5293. this.remixStatusText = status;
  5294. this.updateRemixTaskProgress('generate', mappedProgress);
  5295. }).subscribe({
  5296. next: () => {
  5297. this.remixStatusText = '主体识别完成,开始生成数字人视频...';
  5298. video.remixProgress = 50;
  5299. this.updateRemixTaskProgress('generate', 50);
  5300. this.jimengService.generateDigitalHuman(workId, audioUrl, {
  5301. prompt: this.remixDigitalHumanPrompt,
  5302. peFastMode: this.remixDigitalHumanResolution === '720p' ? true : this.remixDigitalHumanFastMode,
  5303. outputResolution: this.remixDigitalHumanResolution,
  5304. maskUrl: []
  5305. }, (status, progress) => {
  5306. const mappedProgress = Math.min(50 + progress * 0.45, 95);
  5307. video.remixProgress = mappedProgress;
  5308. this.remixStatusText = status;
  5309. this.updateRemixTaskProgress('generate', mappedProgress);
  5310. }).subscribe({
  5311. next: (result) => {
  5312. video.remixProgress = 100;
  5313. this.remixResults.success = 1;
  5314. this.remixFinalVideoUrl = result.videoUrl;
  5315. this.remixStatusText = '数字人视频生成完成';
  5316. this.createDigitalHumanVersion(video, result.videoUrl);
  5317. this.completeRemixTask('completed', result.videoUrl);
  5318. this.saveRemixSession('completed');
  5319. video.isRemixing = false;
  5320. this.isRemixSubmitting = false;
  5321. this.remixStep = 6;
  5322. this.showToast(`✅ 数字人视频已生成:${video.title}`, 'success', 6000);
  5323. this.refreshView();
  5324. },
  5325. error: (err) => {
  5326. this.handleDigitalHumanGenerationError(video, err?.message || '数字人生成失败');
  5327. }
  5328. });
  5329. },
  5330. error: (err) => {
  5331. this.handleDigitalHumanGenerationError(video, err?.message || '数字人主体识别失败');
  5332. }
  5333. });
  5334. },
  5335. error: (err) => {
  5336. this.handleDigitalHumanGenerationError(video, err?.message || '提交数字人主体识别失败');
  5337. }
  5338. });
  5339. }
  5340. private handleDigitalHumanGenerationError(video: ManagedVideo, message: string): void {
  5341. video.isRemixing = false;
  5342. video.remixProgress = 0;
  5343. this.isRemixSubmitting = false;
  5344. this.remixResults.failed = 1;
  5345. this.remixStep = 6;
  5346. this.remixStatusText = message;
  5347. this.remixStitchStatus = 'failed';
  5348. this.remixStitchError = message;
  5349. this.completeRemixTask('failed', undefined, message);
  5350. this.saveRemixSession('failed');
  5351. this.showToast(`❌ ${message}`, 'error');
  5352. this.refreshView();
  5353. }
  5354. // 串行生成每个分镜段的视频
  5355. private generateSegmentSequentially(index: number, video: ManagedVideo, styleName: string): void {
  5356. if (index >= this.remixStoryboard.length) {
  5357. // 全部完成
  5358. this.onBatchGenerationComplete(video, styleName);
  5359. return;
  5360. }
  5361. const segment = this.remixStoryboard[index];
  5362. segment.status = 'generating';
  5363. const totalSegments = this.remixStoryboard.length;
  5364. this.remixStatusText = `正在生成第 ${index + 1}/${totalSegments} 个片段...`;
  5365. video.remixProgress = (index / totalSegments) * 100;
  5366. // 更新任务进度
  5367. this.updateRemixTaskProgress('generate', (index / totalSegments) * 80);
  5368. this.jimengService.remixVideo(
  5369. segment.prompt,
  5370. {
  5371. method: '1',
  5372. frames: this.remixFrames,
  5373. aspectRatio: this.remixAspectRatio,
  5374. quality: this.remixQuality
  5375. },
  5376. (status: string, progress: number) => {
  5377. // 单片段内进度映射到总进度
  5378. const segProgress = (index + progress / 100) / totalSegments * 100;
  5379. video.remixProgress = segProgress;
  5380. this.remixStatusText = `片段 ${index + 1}/${totalSegments}: ${status}`;
  5381. }
  5382. ).subscribe({
  5383. next: (result) => {
  5384. segment.status = 'completed';
  5385. segment.videoUrl = result.videoUrl;
  5386. segment.workId = result.workId;
  5387. this.remixResults.success++;
  5388. // 添加到生成结果
  5389. this.generatedResults.unshift({
  5390. id: `REMIX-${Date.now()}-${segment.id}`,
  5391. type: 'video',
  5392. url: result.videoUrl,
  5393. title: `${video.title} - ${styleName} [${segment.id}]`,
  5394. created_at: new Date(),
  5395. quality: this.remixQuality === 'pro' ? '1080P Pro' : '720P',
  5396. duration: this.remixFrames === 121 ? '5秒' : '10秒',
  5397. cost: this.remixQuality === 'pro' ? 5.0 : 1.4
  5398. });
  5399. console.log(`✅ 片段 ${segment.id} 完成: ${result.videoUrl}`);
  5400. // 自动保存当前会话
  5401. this.saveRemixSession('generating');
  5402. // 延迟1秒再提交下一个(避免频率限制)
  5403. setTimeout(() => this.generateSegmentSequentially(index + 1, video, styleName), 1000);
  5404. },
  5405. error: (err) => {
  5406. segment.status = 'failed';
  5407. segment.error = err.message || '生成失败';
  5408. this.remixResults.failed++;
  5409. console.error(`❌ 片段 ${segment.id} 失败:`, err);
  5410. this.saveRemixSession('generating');
  5411. // 失败也继续下一个
  5412. setTimeout(() => this.generateSegmentSequentially(index + 1, video, styleName), 1000);
  5413. }
  5414. });
  5415. }
  5416. // 批量生成完成 → 自动触发一键成片拼接
  5417. private onBatchGenerationComplete(video: ManagedVideo, styleName: string): void {
  5418. this.remixStep = 6;
  5419. this.remixStatusText = `片段生成完成:成功 ${this.remixResults.success}/${this.remixResults.total}`;
  5420. console.log(`🎉 批量生成完成: 成功${this.remixResults.success}, 失败${this.remixResults.failed}`);
  5421. // 更新任务进度到80%
  5422. this.updateRemixTaskProgress('generate', 80);
  5423. // 收集所有成功片段的视频URL
  5424. const successUrls = this.remixStoryboard
  5425. .filter(s => s.status === 'completed' && s.videoUrl)
  5426. .map(s => s.videoUrl!);
  5427. if (successUrls.length < 1) {
  5428. video.isRemixing = false;
  5429. video.remixProgress = 100;
  5430. this.isRemixSubmitting = false;
  5431. this.remixStitchStatus = 'failed';
  5432. this.remixStitchError = '没有成功的视频片段可以拼接';
  5433. this.remixStatusText = `生成完成,但没有可拼接的片段`;
  5434. this.completeRemixTask('failed', undefined, '所有片段生成失败');
  5435. this.saveRemixSession('failed');
  5436. this.showToast('任务失败:所有片段生成失败', 'error');
  5437. return;
  5438. }
  5439. // 一键成片功能暂时关闭(Quickly API 凭证过期),直接标记完成
  5440. // TODO: 待 Quickly 凭证更新后恢复自动拼接功能
  5441. this.remixStitchStatus = 'failed';
  5442. this.remixStitchError = '一键成片功能暂不可用(Quickly API 凭证过期),各片段可单独查看/下载';
  5443. this.remixStatusText = `片段生成完成:成功 ${successUrls.length} 个,一键成片暂不可用`;
  5444. video.isRemixing = false;
  5445. video.remixProgress = 100;
  5446. this.isRemixSubmitting = false;
  5447. const firstUrl = successUrls[0];
  5448. this.createRemixVersion(video, this.remixStyle, styleName, firstUrl);
  5449. this.completeRemixTask('completed', firstUrl);
  5450. this.saveRemixSession('completed');
  5451. this.showToast(`✅ AI重塑完成!「${video.title}」共 ${successUrls.length} 个片段`, 'success', 6000);
  5452. console.log(`✅ AI重塑完成(一键成片已跳过): ${successUrls.length} 个片段`);
  5453. }
  5454. // 结果页点击完成
  5455. finishRemix(): void {
  5456. this.showRemixModal = false;
  5457. this.remixTargetVideo = null;
  5458. this.resetDigitalHumanState();
  5459. this.setCurrentTab('results');
  5460. }
  5461. private createDigitalHumanVersion(video: ManagedVideo, videoUrl: string): void {
  5462. const remixVersion: RemixVersion = {
  5463. id: `REMIX-${Date.now()}`,
  5464. style: '数字人生成',
  5465. created_at: new Date(),
  5466. file_path: videoUrl,
  5467. thumbnail: this.remixDigitalHumanImageAssetUrl || video.thumbnail || 'assets/default-remix-thumb.jpg',
  5468. description: '使用上传形象图与原视频提取音频生成的数字人版本',
  5469. parameters: {
  5470. style: 'digital-human',
  5471. intensity: 1,
  5472. preserve_audio: true,
  5473. quality: this.remixDigitalHumanResolution === '1080p' ? 'high' : 'standard',
  5474. effects: ['digital-human']
  5475. }
  5476. };
  5477. if (!video.remixVersions) {
  5478. video.remixVersions = [];
  5479. }
  5480. video.remixVersions.unshift(remixVersion);
  5481. const durationSeconds = Math.min(Number(video.duration || 0) || 0, 60);
  5482. const estimatedCost = Math.round(durationSeconds * 100) / 100;
  5483. const qualityLabel = this.remixDigitalHumanResolution === '1080p' ? '1080P' : '720P';
  5484. this.saveResult({
  5485. type: 'video',
  5486. url: videoUrl,
  5487. title: `${video.title} - 数字人生成`,
  5488. quality: qualityLabel,
  5489. duration: durationSeconds > 0 ? `${durationSeconds} 秒` : '数字人视频',
  5490. cost: estimatedCost,
  5491. remixId: this.currentRemixId,
  5492. videoId: video.id,
  5493. segments: [{ id: 'DH-01', videoUrl, prompt: this.remixDigitalHumanPrompt, status: 'completed' }]
  5494. });
  5495. this.saveHistoryRecord({
  5496. keyword: `${video.title} - 数字人生成`,
  5497. original_video_title: video.title,
  5498. status: 'completed',
  5499. cost: estimatedCost,
  5500. duration: durationSeconds > 0 ? `${durationSeconds} 秒` : '数字人视频',
  5501. remixId: this.currentRemixId,
  5502. videoId: video.id,
  5503. styleName: '数字人生成',
  5504. resultUrl: videoUrl,
  5505. quality: qualityLabel,
  5506. segmentCount: 1,
  5507. successCount: 1
  5508. });
  5509. }
  5510. // 创建重塑版本 + 持久化结果和历史
  5511. private createRemixVersion(video: ManagedVideo, styleId: string, styleName: string, videoUrl?: string): void {
  5512. const remixVersion: RemixVersion = {
  5513. id: `REMIX-${Date.now()}`,
  5514. style: styleName,
  5515. created_at: new Date(),
  5516. file_path: videoUrl || `remix/${video.filename.replace('.mp4', `-${styleId}.mp4`)}`,
  5517. thumbnail: video.thumbnail || 'assets/default-remix-thumb.jpg',
  5518. description: `使用${styleName}风格重塑的视频版本`,
  5519. parameters: {
  5520. style: styleId,
  5521. intensity: 0.8,
  5522. preserve_audio: true,
  5523. quality: this.remixQuality === 'pro' ? 'ultra' : 'high',
  5524. effects: [styleId, 'enhancement']
  5525. }
  5526. };
  5527. if (!video.remixVersions) {
  5528. video.remixVersions = [];
  5529. }
  5530. video.remixVersions.unshift(remixVersion);
  5531. // 收集所有成功片段数据
  5532. const successSegments = this.remixStoryboard
  5533. .filter(s => s.status === 'completed' && s.videoUrl)
  5534. .map(s => ({ id: s.id, videoUrl: s.videoUrl!, prompt: s.prompt, status: s.status }));
  5535. // 计算费用估算
  5536. const costPerSecond = this.remixQuality === 'pro' ? 1.0 : this.remixQuality === '1080p' ? 0.63 : 0.28;
  5537. const estimatedCost = Math.round(this.remixResults.success * 5 * costPerSecond * 100) / 100;
  5538. // 质量显示
  5539. const qualityLabel = this.remixQuality === 'pro' ? 'Pro 1080P' : this.remixQuality === '1080p' ? '1080P' : '720P';
  5540. // 持久化:保存生成结果(包含所有片段)
  5541. this.saveResult({
  5542. type: 'video',
  5543. url: videoUrl || '',
  5544. title: `${video.title} - ${styleName}风格重塑`,
  5545. quality: qualityLabel,
  5546. duration: `${this.remixResults.success} 个片段`,
  5547. cost: estimatedCost,
  5548. remixId: this.currentRemixId,
  5549. videoId: video.id,
  5550. segments: successSegments
  5551. });
  5552. // 持久化:保存历史记录
  5553. this.saveHistoryRecord({
  5554. keyword: `${video.title} - ${styleName}`,
  5555. original_video_title: video.title,
  5556. status: this.remixResults.success > 0 ? 'completed' : 'failed',
  5557. cost: estimatedCost,
  5558. duration: `${this.remixResults.success}/${this.remixResults.total} 片段`,
  5559. remixId: this.currentRemixId,
  5560. videoId: video.id,
  5561. styleName: styleName,
  5562. resultUrl: videoUrl || successSegments[0]?.videoUrl || '',
  5563. quality: qualityLabel,
  5564. segmentCount: this.remixResults.total,
  5565. successCount: this.remixResults.success
  5566. });
  5567. console.log('重塑版本已创建:', remixVersion);
  5568. }
  5569. // 查看重塑版本
  5570. viewRemixVersions(video: ManagedVideo): void {
  5571. if (!video.remixVersions || video.remixVersions.length === 0) {
  5572. alert('该视频暂无重塑版本');
  5573. return;
  5574. }
  5575. console.log('查看重塑版本:', video.remixVersions);
  5576. let versionsList = `「${video.title}」的重塑版本:\n\n`;
  5577. video.remixVersions.forEach((version, index) => {
  5578. versionsList += `${index + 1}. ${version.style} - ${version.description}\n 创建时间: ${version.created_at.toLocaleString()}\n\n`;
  5579. });
  5580. alert(versionsList);
  5581. }
  5582. // 获取重塑状态文本
  5583. getRemixStatusText(video: ManagedVideo): string {
  5584. if (video.isRemixing && video.remixProgress !== undefined) {
  5585. return `重塑中... ${Math.round(video.remixProgress)}%`;
  5586. }
  5587. return 'AI重塑';
  5588. }
  5589. // 获取重塑状态颜色
  5590. getRemixStatusColor(video: ManagedVideo): string {
  5591. if (video.isRemixing) {
  5592. return 'btn-accent';
  5593. }
  5594. return 'btn-primary';
  5595. }
  5596. // ==================== 语音合成标签页方法 ====================
  5597. setVsTtsMode(mode: 'clone' | 'synthesize'): void {
  5598. this.vsTtsMode = mode;
  5599. this.vsCloneError = '';
  5600. this.vsSynthError = '';
  5601. this.refreshView();
  5602. }
  5603. onVsCloneAudioSelected(event: Event): void {
  5604. const input = event.target as HTMLInputElement;
  5605. if (!input.files || input.files.length === 0) return;
  5606. const file = input.files[0];
  5607. const allowedExts = ['.mp3', '.wav', '.m4a', '.ogg', '.aac', '.flac', '.wma'];
  5608. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  5609. if (!allowedExts.includes(ext) || file.size <= 0) {
  5610. this.vsCloneError = '仅支持 mp3、wav、m4a、ogg、aac、flac、wma 格式的音频文件';
  5611. input.value = '';
  5612. this.refreshView();
  5613. return;
  5614. }
  5615. if (file.size > 50 * 1024 * 1024) {
  5616. this.vsCloneError = '音频文件不能超过 50MB';
  5617. input.value = '';
  5618. this.refreshView();
  5619. return;
  5620. }
  5621. this.vsCloneAudioFile = file;
  5622. this.vsCloneAudioName = file.name;
  5623. this.vsCloneAudioUrl = '';
  5624. this.vsCloneError = '';
  5625. input.value = '';
  5626. this.refreshView();
  5627. }
  5628. clearVsCloneAudio(): void {
  5629. this.vsCloneAudioFile = null;
  5630. this.vsCloneAudioName = '';
  5631. this.vsCloneAudioUrl = '';
  5632. this.vsCloneError = '';
  5633. this.refreshView();
  5634. }
  5635. private vsUploadCloneAudio(): Promise<string> {
  5636. return new Promise((resolve, reject) => {
  5637. if (!this.vsCloneAudioFile) {
  5638. reject(new Error('未选择音频文件'));
  5639. return;
  5640. }
  5641. if (this.vsCloneAudioUrl) {
  5642. resolve(this.vsCloneAudioUrl);
  5643. return;
  5644. }
  5645. this.vsCloneUploading = true;
  5646. this.refreshView();
  5647. const formData = new FormData();
  5648. const filename = `voice-clone-${Date.now()}-${this.vsCloneAudioFile.name}`;
  5649. formData.append('file', this.vsCloneAudioFile, filename);
  5650. this.http.post<any>('/backend/api/remix/upload-asset', formData).subscribe({
  5651. next: (res) => {
  5652. this.vsCloneUploading = false;
  5653. const url = res?.url || '';
  5654. if (!url) {
  5655. reject(new Error('上传音频失败,未返回可用 URL'));
  5656. return;
  5657. }
  5658. this.vsCloneAudioUrl = url;
  5659. this.refreshView();
  5660. resolve(url);
  5661. },
  5662. error: (err) => {
  5663. this.vsCloneUploading = false;
  5664. this.refreshView();
  5665. reject(new Error(this.getErrorText(err, '音频上传失败')));
  5666. }
  5667. });
  5668. });
  5669. }
  5670. vsStartClone(): void {
  5671. if (this.vsCloneLoading || this.vsCloneUploading) return;
  5672. const { name, audioText, language, demoText } = this.vsCloneForm;
  5673. if (!name.trim()) {
  5674. this.vsCloneError = '请输入音色名称';
  5675. this.refreshView();
  5676. return;
  5677. }
  5678. if (!this.vsCloneAudioFile) {
  5679. this.vsCloneError = '请先上传音频文件';
  5680. this.refreshView();
  5681. return;
  5682. }
  5683. if (!demoText.trim() || demoText.trim().length < 4 || demoText.trim().length > 80) {
  5684. this.vsCloneError = '试听文本长度需在 4-80 字之间';
  5685. this.refreshView();
  5686. return;
  5687. }
  5688. this.vsCloneLoading = true;
  5689. this.vsCloneError = '';
  5690. this.vsCloneResult = null;
  5691. this.refreshView();
  5692. this.vsUploadCloneAudio().then((audioUrl) => {
  5693. // 自动从后端挑选一个未训练的 speaker_id
  5694. this.http.post<any>('/backend/api/voice/auto-speaker-id', {}).subscribe({
  5695. next: (idRes) => {
  5696. const pickedSpeakerId = String(idRes?.speaker_id || '').trim();
  5697. if (!pickedSpeakerId) {
  5698. this.vsCloneLoading = false;
  5699. this.vsCloneError = idRes?.error || '未能获取可用的 speaker_id';
  5700. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5701. this.refreshView();
  5702. return;
  5703. }
  5704. this.showToast(`🎯 已自动分配 speaker_id:${pickedSpeakerId}`, 'info', 3000);
  5705. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/voice_clone', {
  5706. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600',
  5707. name: name.trim(),
  5708. speaker_id: pickedSpeakerId,
  5709. audioData: {
  5710. url: audioUrl,
  5711. ...(audioText.trim() ? { text: audioText.trim() } : {})
  5712. },
  5713. language: language,
  5714. extra_params: {
  5715. demo_text: demoText.trim()
  5716. }
  5717. }).subscribe({
  5718. next: (res) => {
  5719. this.vsCloneLoading = false;
  5720. this.vsCloneResult = res;
  5721. if (res?.code === 200 && res?.data?.timbre) {
  5722. const timbre = res.data.timbre;
  5723. const newEntry = {
  5724. objectId: timbre.objectId,
  5725. name: timbre.name || name.trim(),
  5726. speakerId: timbre.speaker_id || pickedSpeakerId
  5727. };
  5728. const existingIndex = this.vsClonedTimbreList.findIndex(t => t.objectId === timbre.objectId);
  5729. if (existingIndex >= 0) {
  5730. // 同一 speaker_id 复刻会返回相同 objectId:更新现有条目(含名称)并置顶
  5731. const next = [...this.vsClonedTimbreList];
  5732. next.splice(existingIndex, 1);
  5733. next.unshift({ ...this.vsClonedTimbreList[existingIndex], ...newEntry });
  5734. this.vsClonedTimbreList = next;
  5735. } else {
  5736. this.vsClonedTimbreList = [newEntry, ...this.vsClonedTimbreList];
  5737. }
  5738. this.saveClonedTimbreList();
  5739. // 同步到本地后端,让 /api/voice/auto-speaker-id 后续能跳过此 speaker_id
  5740. const modelInfo = (Array.isArray(timbre.models) && timbre.models[0]) || {};
  5741. this.http.post('/backend/api/voice-profiles/sync', {
  5742. id: timbre.objectId,
  5743. timbre_id: timbre.objectId,
  5744. name: timbre.name || name.trim(),
  5745. speaker_id: timbre.speaker_id || pickedSpeakerId,
  5746. demo_audio: modelInfo.demo_audio || '',
  5747. latest_audio_url: modelInfo.demo_audio || '',
  5748. x_api_resource_id: modelInfo.x_api_resource_id || '',
  5749. icl_speaker_id: modelInfo.icl_speaker_id || '',
  5750. model_version: modelInfo.version || '',
  5751. status: timbre.status ?? null,
  5752. status_label: res?.data?.tip || '',
  5753. message: res?.data?.tip || '',
  5754. created_at: timbre.createdAt || undefined
  5755. }).subscribe({
  5756. next: () => {},
  5757. error: (e) => console.warn('voice-profiles/sync failed', e)
  5758. });
  5759. if (!this.vsSynthForm.timbreId) {
  5760. this.vsSynthForm.timbreId = timbre.objectId;
  5761. }
  5762. this.showToast(`✅ 音色「${timbre.name}」复刻成功`, 'success');
  5763. } else {
  5764. this.vsCloneError = res?.error?.message || '复刻失败,请检查参数';
  5765. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5766. }
  5767. this.refreshView();
  5768. },
  5769. error: (err) => {
  5770. this.vsCloneLoading = false;
  5771. this.vsCloneError = this.getErrorText(err, '音色复刻请求失败');
  5772. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5773. this.refreshView();
  5774. }
  5775. });
  5776. },
  5777. error: (err) => {
  5778. this.vsCloneLoading = false;
  5779. const errBody = err?.error;
  5780. this.vsCloneError = errBody?.error || this.getErrorText(err, '获取可用 speaker_id 失败');
  5781. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5782. this.refreshView();
  5783. }
  5784. });
  5785. }).catch((uploadErr) => {
  5786. this.vsCloneLoading = false;
  5787. this.vsCloneError = uploadErr?.message || '音频上传失败';
  5788. this.showToast(`❌ ${this.vsCloneError}`, 'error');
  5789. this.refreshView();
  5790. });
  5791. }
  5792. vsStartSynthesize(): void {
  5793. if (this.vsSynthLoading) return;
  5794. const { timbreId, voiceType, voiceSource, text, format, sampleRate, speechRate, loudnessRate } = this.vsSynthForm;
  5795. const usingOfficial = voiceSource === 'official';
  5796. const voiceId = usingOfficial ? (voiceType || '').trim() : (timbreId || '').trim();
  5797. if (!voiceId) {
  5798. this.vsSynthError = '请先选择声音模型';
  5799. this.refreshView();
  5800. return;
  5801. }
  5802. if (!text.trim()) {
  5803. this.vsSynthError = '请输入要合成的文本内容';
  5804. this.refreshView();
  5805. return;
  5806. }
  5807. this.vsSynthLoading = true;
  5808. this.vsSynthError = '';
  5809. this.vsSynthAudioUrl = '';
  5810. this.vsSynthWorkId = '';
  5811. this.refreshView();
  5812. const body: any = {
  5813. token: 'Bearer r:f0333969e312a40e4703e8fe4ed1c600',
  5814. text: text.trim(),
  5815. isStream: false,
  5816. audio_params: {
  5817. format: format || 'mp3',
  5818. sample_rate: sampleRate || 24000,
  5819. speech_rate: speechRate || 0,
  5820. loudness_rate: loudnessRate || 0
  5821. }
  5822. };
  5823. if (usingOfficial) {
  5824. // _uranus_bigtts 后缀对应豆包语音合成模型 2.0,需要 seed-tts-2.0 资源;
  5825. // 其它后缀回退到 seed-tts-1.0,可按需扩展。
  5826. body.volcengine_voice_type = voiceId;
  5827. body.x_api_resource_id = voiceId.includes('_uranus_bigtts') ? 'seed-tts-2.0' : 'seed-tts-1.0';
  5828. } else {
  5829. body.timbreId = voiceId;
  5830. }
  5831. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/unidirectional', body).subscribe({
  5832. next: (res) => {
  5833. this.vsSynthLoading = false;
  5834. if (res?.code === 200 && res?.data?.audioUrl) {
  5835. this.vsSynthAudioUrl = res.data.audioUrl;
  5836. this.vsSynthWorkId = res.data.workId || '';
  5837. this.showToast('✅ 语音合成成功', 'success');
  5838. } else {
  5839. this.vsSynthError = res?.error?.message || '合成失败,请检查参数';
  5840. this.showToast(`❌ ${this.vsSynthError}`, 'error');
  5841. }
  5842. this.refreshView();
  5843. },
  5844. error: (err) => {
  5845. this.vsSynthLoading = false;
  5846. this.vsSynthError = this.getErrorText(err, '语音合成请求失败');
  5847. this.showToast(`❌ ${this.vsSynthError}`, 'error');
  5848. this.refreshView();
  5849. }
  5850. });
  5851. }
  5852. vsSelectClonedTimbre(objectId: string): void {
  5853. this.vsSynthForm.timbreId = objectId;
  5854. this.vsSynthForm.voiceSource = 'cloned';
  5855. this.vsSynthForm.voiceType = '';
  5856. const matched = this.vsClonedTimbreList.find(t => t.objectId === objectId);
  5857. this.vsSynthForm.voiceName = matched?.name || objectId;
  5858. this.vsTtsMode = 'synthesize';
  5859. this.vsSynthError = '';
  5860. this.refreshView();
  5861. }
  5862. // ==================== 数字人合成独立页面 ====================
  5863. onDhImageSelected(event: Event): void {
  5864. const input = event.target as HTMLInputElement;
  5865. if (!input.files || input.files.length === 0) return;
  5866. const file = input.files[0];
  5867. const allowedExts = ['.jpg', '.jpeg', '.png', '.gif'];
  5868. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  5869. if (!allowedExts.includes(ext)) {
  5870. this.dhError = '仅支持 jpg、jpeg、png、gif 格式的形象图';
  5871. input.value = '';
  5872. this.refreshView();
  5873. return;
  5874. }
  5875. if (file.size > 20 * 1024 * 1024) {
  5876. this.dhError = '形象图大小不能超过 20MB';
  5877. input.value = '';
  5878. this.refreshView();
  5879. return;
  5880. }
  5881. this.dhRevokeImagePreview();
  5882. this.dhImageFile = file;
  5883. this.dhImageName = file.name;
  5884. this.dhImagePreviewUrl = URL.createObjectURL(file);
  5885. this.dhImageAssetUrl = '';
  5886. this.dhError = '';
  5887. input.value = '';
  5888. this.refreshView();
  5889. }
  5890. clearDhImage(): void {
  5891. this.dhRevokeImagePreview();
  5892. this.dhImageFile = null;
  5893. this.dhImageName = '';
  5894. this.dhImageAssetUrl = '';
  5895. this.dhError = '';
  5896. this.dhPreparedPortraitUrl = '';
  5897. this.dhPreparedFullBodyUrl = '';
  5898. this.dhPreparedBenchmarkSummary = '';
  5899. this.refreshView();
  5900. }
  5901. /** dh tab:<app-portrait-prepare> 的 (prepared) 事件回调 */
  5902. onDhPortraitPrepared(out: PortraitPrepareOutput): void {
  5903. this.dhPreparedPortraitUrl = out.portraitUrl;
  5904. this.dhPreparedFullBodyUrl = out.fullBodyUrl;
  5905. this.dhPreparedBenchmarkSummary = out.benchmarkSummary;
  5906. this.refreshView();
  5907. }
  5908. private dhRevokeImagePreview(): void {
  5909. if (this.dhImagePreviewUrl) {
  5910. URL.revokeObjectURL(this.dhImagePreviewUrl);
  5911. this.dhImagePreviewUrl = '';
  5912. }
  5913. }
  5914. onDhAudioSelected(event: Event): void {
  5915. const input = event.target as HTMLInputElement;
  5916. if (!input.files || input.files.length === 0) return;
  5917. const file = input.files[0];
  5918. const allowedExts = ['.mp3', '.wav', '.m4a', '.ogg', '.aac', '.flac', '.wma'];
  5919. const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  5920. if (!allowedExts.includes(ext)) {
  5921. this.dhError = '仅支持 MP3、WAV、M4A、OGG、AAC、FLAC、WMA 格式的音频';
  5922. input.value = '';
  5923. this.refreshView();
  5924. return;
  5925. }
  5926. if (file.size > 50 * 1024 * 1024) {
  5927. this.dhError = '音频文件大小不能超过 50MB';
  5928. input.value = '';
  5929. this.refreshView();
  5930. return;
  5931. }
  5932. this.dhUploadAudioFile = file;
  5933. this.dhUploadAudioName = file.name;
  5934. this.dhUploadAudioUrl = '';
  5935. this.dhError = '';
  5936. input.value = '';
  5937. this.refreshView();
  5938. }
  5939. clearDhAudio(): void {
  5940. this.dhUploadAudioFile = null;
  5941. this.dhUploadAudioName = '';
  5942. this.dhUploadAudioUrl = '';
  5943. this.dhError = '';
  5944. this.refreshView();
  5945. }
  5946. dhReset(): void {
  5947. this.dhRevokeImagePreview();
  5948. this.dhStep = 'form';
  5949. this.dhImageFile = null;
  5950. this.dhImageName = '';
  5951. this.dhImageAssetUrl = '';
  5952. this.dhAudioSource = 'tts';
  5953. this.dhTtsTimbreId = '';
  5954. this.dhTtsText = '';
  5955. this.dhUploadAudioFile = null;
  5956. this.dhUploadAudioName = '';
  5957. this.dhUploadAudioUrl = '';
  5958. this.dhUploadingAudio = false;
  5959. this.dhPrompt = '';
  5960. this.dhFastMode = false;
  5961. this.dhResolution = '1080p';
  5962. this.dhError = '';
  5963. this.dhLoading = false;
  5964. this.dhStatusText = '';
  5965. this.dhProgress = 0;
  5966. this.dhResultVideoUrl = '';
  5967. this.dhSynthesizing = false;
  5968. this.refreshView();
  5969. }
  5970. // 数字人形象库:从生成结果中筛选数字人作品
  5971. getDigitalHumanResults(): GeneratedResult[] {
  5972. return (this.generatedResults || []).filter(r => {
  5973. const title = String(r?.title || '');
  5974. return title.includes('数字人合成') || title.includes('数字人');
  5975. });
  5976. }
  5977. // ========================================================================
  5978. // 数字人合成页:AI 对话助手 —— 让用户用自然语言要求 AI 改写口播稿 / 优化提示词
  5979. // ========================================================================
  5980. /** 发送一条对话给 AI,AI 基于当前 dhTtsText / dhPrompt 给出修改建议 */
  5981. dhChatSend(): void {
  5982. const userMsg = (this.dhChatInput || '').trim();
  5983. if (!userMsg || this.dhChatLoading) return;
  5984. this.dhChatMessages.push({ role: 'user', content: userMsg });
  5985. this.dhChatInput = '';
  5986. this.dhChatLoading = true;
  5987. this.dhChatError = '';
  5988. this.refreshView();
  5989. const systemPrompt = `你是一位短视频数字人口播脚本编辑助手。你需要根据用户的自然语言指令,在不偏离原意的前提下改写「口播文本」或「补充提示词」。
  5990. 【当前口播文本】
  5991. ${this.dhTtsText || '(空)'}
  5992. 【当前补充提示词】
  5993. ${this.dhPrompt || '(空)'}
  5994. 【输出格式】请只输出严格 JSON:
  5995. {
  5996. "explanation": "用一两句话向用户解释你做了什么修改(≤40字)",
  5997. "ttsScript": "新的口播文本;若用户本轮指令不需要改写口播,请返回空字符串",
  5998. "dhPrompt": "新的补充提示词;若用户本轮指令不需要改写提示词,请返回空字符串"
  5999. }
  6000. 要求:
  6001. - 字符串内不得出现真实换行,必须用 \\n 转义。
  6002. - 口播文本控制在 200 字以内,第一人称、自然口语。
  6003. - 补充提示词控制在 80 字以内,描述动作 / 镜头语言 / 风格。
  6004. - 只返回纯 JSON,禁止 markdown 代码块、禁止前后缀。`;
  6005. // 把最近若干轮历史拼成一段上下文,避免 token 爆炸
  6006. const history = this.dhChatMessages
  6007. .slice(-8, -1) // 不含本次刚 push 的用户消息
  6008. .map(m => `${m.role === 'user' ? '用户' : 'AI'}: ${m.content}`)
  6009. .join('\n');
  6010. const userInput = (history ? `【历史对话】\n${history}\n\n` : '') + `【本轮用户指令】\n${userMsg}`;
  6011. console.log('🗣️ [dhChatSend] 发送对话:', { userMsg, ttsLen: this.dhTtsText.length, promptLen: this.dhPrompt.length });
  6012. this.llmService.askWithSystem(systemPrompt, userInput, { model: 'gemini-2.5-flash', max_tokens: 2048 })
  6013. .pipe(
  6014. timeout(60000),
  6015. // ★ finalize 保证不论 next/error/throw/cancel,都强制解锁按钮并刷新视图
  6016. finalize(() => {
  6017. this.dhChatLoading = false;
  6018. this.refreshView();
  6019. })
  6020. )
  6021. .subscribe({
  6022. next: (text) => {
  6023. console.log('🗣️ [dhChatSend] 收到回复,长度:', (text || '').length);
  6024. const cleaned = (text || '').replace(/^\s*```(?:json)?\s*/i, '').replace(/\s*```\s*$/i, '').trim();
  6025. const parsed: any = this.parseRewriteJson(cleaned);
  6026. if (parsed) {
  6027. const explanation = typeof parsed.explanation === 'string' ? parsed.explanation.trim() : '';
  6028. const tts = typeof parsed.ttsScript === 'string' ? parsed.ttsScript.trim() : '';
  6029. const prompt = typeof parsed.dhPrompt === 'string' ? parsed.dhPrompt.trim() : '';
  6030. this.dhChatMessages.push({
  6031. role: 'assistant',
  6032. content: explanation || (tts || prompt ? '已为你生成修改建议,可点击下方按钮应用' : '我没有给出修改'),
  6033. suggestedTts: tts || undefined,
  6034. suggestedPrompt: prompt || undefined,
  6035. });
  6036. } else {
  6037. // 兜底:把原文当作 assistant 文本呈现,不自动应用
  6038. this.dhChatMessages.push({ role: 'assistant', content: cleaned || '(AI 无返回)' });
  6039. }
  6040. this.refreshView();
  6041. },
  6042. error: (err) => {
  6043. console.error('🗣️ [dhChatSend] 请求失败:', err);
  6044. this.dhChatLoading = false;
  6045. // 优先抽取上游具体错误(fmode 网关返回的 "无效的令牌..." 等)
  6046. const upstream = err?.error?.error?.message || err?.error?.message || err?.error?.error || err?.error || '';
  6047. const msg = (typeof upstream === 'string' && upstream) || err?.message || 'AI 对话请求失败';
  6048. this.dhChatError = msg;
  6049. this.dhChatMessages.push({ role: 'assistant', content: `⚠️ ${msg}` });
  6050. this.refreshView();
  6051. }
  6052. });
  6053. }
  6054. /** 应用 AI 建议到对应字段;field 控制只应用一项还是两项一起 */
  6055. dhChatApply(msgIndex: number, field: 'tts' | 'prompt' | 'both'): void {
  6056. const msg = this.dhChatMessages[msgIndex];
  6057. if (!msg || msg.role !== 'assistant') return;
  6058. if ((field === 'tts' || field === 'both') && msg.suggestedTts) {
  6059. this.dhTtsText = msg.suggestedTts.slice(0, 600);
  6060. msg.appliedTts = true;
  6061. }
  6062. if ((field === 'prompt' || field === 'both') && msg.suggestedPrompt) {
  6063. this.dhPrompt = msg.suggestedPrompt.slice(0, 200);
  6064. msg.appliedPrompt = true;
  6065. }
  6066. this.showToast('✅ 已应用 AI 建议', 'success', 2000);
  6067. this.refreshView();
  6068. }
  6069. /** 清空对话历史 */
  6070. dhChatClear(): void {
  6071. this.dhChatMessages = [];
  6072. this.dhChatError = '';
  6073. this.dhChatInput = '';
  6074. this.refreshView();
  6075. }
  6076. /** 快捷指令:一键发送预设的改写诉求 */
  6077. dhChatQuickAsk(preset: string): void {
  6078. if (this.dhChatLoading) return;
  6079. this.dhChatInput = preset;
  6080. this.dhChatSend();
  6081. }
  6082. /** 刷新数字人形象库(重新拉取生成结果) */
  6083. refreshDigitalHumanGallery(): void {
  6084. this.http.get<any[]>('/backend/api/results').subscribe({
  6085. next: (results) => {
  6086. this.generatedResults = (results || []).map(r => ({ ...r, created_at: new Date(r.created_at) }));
  6087. this.showToast('🔄 形象库已刷新', 'success', 2500);
  6088. this.refreshView();
  6089. },
  6090. error: () => {
  6091. this.showToast('❌ 刷新失败,请稍后重试', 'error');
  6092. }
  6093. });
  6094. }
  6095. dhStartGeneration(): void {
  6096. if (this.dhLoading) return;
  6097. // 验证形象图
  6098. if (!this.dhImageFile) {
  6099. this.dhError = '请先上传数字人形象图';
  6100. this.refreshView();
  6101. return;
  6102. }
  6103. // 验证音频来源
  6104. if (this.dhAudioSource === 'tts') {
  6105. if (!this.dhTtsTimbreId.trim()) {
  6106. this.dhError = '请输入或选择音色 ID';
  6107. this.refreshView();
  6108. return;
  6109. }
  6110. if (!this.dhTtsText.trim()) {
  6111. this.dhError = '请输入口播文本';
  6112. this.refreshView();
  6113. return;
  6114. }
  6115. } else {
  6116. if (!this.dhUploadAudioFile) {
  6117. this.dhError = '请上传音频文件';
  6118. this.refreshView();
  6119. return;
  6120. }
  6121. }
  6122. this.dhError = '';
  6123. this.dhLoading = true;
  6124. this.dhStep = 'generating';
  6125. this.dhProgress = 0;
  6126. this.dhStatusText = '正在准备数字人素材...';
  6127. this.dhResultVideoUrl = '';
  6128. this.refreshView();
  6129. // 通过 DigitalHumanService 串联:上传图 → tts/upload 音频 → identify → generate
  6130. // 若已通过 <app-portrait-prepare> 生成对标/规范化形象图,则直接复用其 URL
  6131. const req: DigitalHumanRequest = {
  6132. portrait: this.dhPreparedPortraitUrl
  6133. ? { imageUrl: this.dhPreparedPortraitUrl }
  6134. : { imageFile: this.dhImageFile! },
  6135. audio: this.dhAudioSource === 'tts'
  6136. ? { source: 'tts', ttsText: this.dhTtsText.trim(), ttsTimbreId: this.dhTtsTimbreId.trim() }
  6137. : { source: 'upload', audioFile: this.dhUploadAudioFile! },
  6138. prompt: this.dhPrompt || '',
  6139. fastMode: this.dhFastMode,
  6140. resolution: this.dhResolution
  6141. };
  6142. this.digitalHumanService.generate(req).subscribe({
  6143. next: (evt: DigitalHumanEvent) => {
  6144. this.ngZone.run(() => {
  6145. if (evt.type === 'progress') {
  6146. this.dhProgress = evt.progress;
  6147. this.dhStatusText = evt.status;
  6148. // 同步老的子状态,让 checklist UI 仍能显示阶段
  6149. if (evt.stage === 'prepare-audio') {
  6150. this.dhSynthesizing = this.dhAudioSource === 'tts';
  6151. this.dhUploadingAudio = this.dhAudioSource === 'upload';
  6152. } else {
  6153. this.dhSynthesizing = false;
  6154. this.dhUploadingAudio = false;
  6155. }
  6156. this.refreshView();
  6157. } else {
  6158. // result
  6159. this.dhProgress = 100;
  6160. this.dhResultVideoUrl = evt.videoUrl;
  6161. this.dhImageAssetUrl = evt.imageUrl;
  6162. this.dhUploadAudioUrl = evt.audioUrl;
  6163. this.dhStatusText = '数字人视频生成完成!';
  6164. this.dhLoading = false;
  6165. this.dhStep = 'done';
  6166. this.dhSynthesizing = false;
  6167. this.dhUploadingAudio = false;
  6168. this.showToast('✅ 数字人视频已生成', 'success', 6000);
  6169. // 保存到结果
  6170. this.saveResult({
  6171. type: 'video',
  6172. url: evt.videoUrl,
  6173. title: `数字人合成 - ${new Date().toLocaleString('zh-CN')}`,
  6174. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6175. duration: '数字人视频',
  6176. cost: 0,
  6177. segments: [{ id: 'DH-01', videoUrl: evt.videoUrl, prompt: this.dhPrompt, status: 'completed' }]
  6178. });
  6179. this.saveHistoryRecord({
  6180. keyword: '数字人合成',
  6181. status: 'completed',
  6182. cost: 0,
  6183. duration: '数字人视频',
  6184. styleName: '数字人合成',
  6185. resultUrl: evt.videoUrl,
  6186. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6187. segmentCount: 1,
  6188. successCount: 1
  6189. });
  6190. this.addDhVideoToManifest(evt.videoUrl);
  6191. this.refreshView();
  6192. }
  6193. });
  6194. },
  6195. error: (err: any) => {
  6196. this.ngZone.run(() => {
  6197. this.dhHandleError(this.getErrorText(err, '数字人视频生成失败'));
  6198. });
  6199. }
  6200. });
  6201. }
  6202. /** @deprecated 旧的同名方法已合并到 dhStartGeneration,保留以避免破坏现有调用。 */
  6203. private _legacyDhUploadFlow(): void {
  6204. if (!this.dhImageFile) return;
  6205. this.jimengService.uploadFileToParse(
  6206. this.dhImageFile,
  6207. `digital-human-${Date.now()}-${this.dhImageFile.name}`,
  6208. this.dhImageFile.type || 'image/jpeg'
  6209. ).subscribe({
  6210. next: (imageUrl: string) => {
  6211. this.dhImageAssetUrl = imageUrl;
  6212. this.dhProgress = 10;
  6213. this.refreshView();
  6214. if (this.dhAudioSource === 'tts') {
  6215. this.dhStatusText = '形象图上传完成,正在合成语音...';
  6216. this.dhSynthesizing = true;
  6217. this.refreshView();
  6218. this.http.post<any>('https://server.fmode.cn/api/volcengine/tts/unidirectional', {
  6219. token: this.voiceApiToken,
  6220. text: this.dhTtsText.trim(),
  6221. timbreId: this.dhTtsTimbreId.trim(),
  6222. isStream: false,
  6223. audio_params: {
  6224. format: 'mp3',
  6225. sample_rate: 24000,
  6226. speech_rate: 0,
  6227. loudness_rate: 0
  6228. }
  6229. }).subscribe({
  6230. next: (res) => {
  6231. this.dhSynthesizing = false;
  6232. if (res?.code === 200 && res?.data?.audioUrl) {
  6233. this.dhProgress = 25;
  6234. this.dhStatusText = '语音合成完成,正在识别数字人主体...';
  6235. this.refreshView();
  6236. this.dhGenerateWithAudio(imageUrl, res.data.audioUrl);
  6237. } else {
  6238. this.dhHandleError(res?.error?.message || '语音合成失败,请检查音色ID和文本');
  6239. }
  6240. },
  6241. error: (err) => {
  6242. this.dhSynthesizing = false;
  6243. this.dhHandleError(this.getErrorText(err, '语音合成请求失败'));
  6244. }
  6245. });
  6246. } else {
  6247. // 上传音频文件
  6248. this.dhStatusText = '形象图上传完成,正在上传音频文件...';
  6249. this.dhUploadingAudio = true;
  6250. this.refreshView();
  6251. const audioFile = this.dhUploadAudioFile!;
  6252. this.jimengService.uploadFileToParse(
  6253. audioFile,
  6254. `dh-audio-${Date.now()}-${audioFile.name}`,
  6255. audioFile.type || 'audio/mpeg'
  6256. ).subscribe({
  6257. next: (audioUrl: string) => {
  6258. this.dhUploadingAudio = false;
  6259. this.dhUploadAudioUrl = audioUrl;
  6260. this.dhProgress = 25;
  6261. this.dhStatusText = '音频上传完成,正在识别数字人主体...';
  6262. this.refreshView();
  6263. this.dhGenerateWithAudio(imageUrl, audioUrl);
  6264. },
  6265. error: (err) => {
  6266. this.dhUploadingAudio = false;
  6267. this.dhHandleError(err?.message || '上传音频文件失败');
  6268. }
  6269. });
  6270. }
  6271. },
  6272. error: (err) => {
  6273. this.dhHandleError(err?.message || '上传形象图失败');
  6274. }
  6275. });
  6276. }
  6277. private dhGenerateWithAudio(imageUrl: string, audioUrl: string): void {
  6278. console.log('🤖 数字人生成 - imageUrl:', imageUrl, 'audioUrl:', audioUrl);
  6279. this.jimengService.identifyDigitalHuman(imageUrl).subscribe({
  6280. next: ({ workId }) => {
  6281. this.jimengService.pollDigitalHumanIdentifyUntilReady(workId, (status, progress) => {
  6282. this.dhProgress = Math.min(25 + progress * 0.25, 50);
  6283. this.dhStatusText = status;
  6284. this.refreshView();
  6285. }).subscribe({
  6286. next: () => {
  6287. this.dhStatusText = '主体识别完成,开始生成数字人视频...';
  6288. this.dhProgress = 50;
  6289. this.refreshView();
  6290. this.jimengService.generateDigitalHuman(workId, audioUrl, {
  6291. prompt: this.dhPrompt,
  6292. peFastMode: this.dhResolution === '720p' ? true : this.dhFastMode,
  6293. outputResolution: this.dhResolution,
  6294. maskUrl: []
  6295. }, (status, progress) => {
  6296. this.dhProgress = Math.min(50 + progress * 0.45, 95);
  6297. this.dhStatusText = status;
  6298. this.refreshView();
  6299. }).subscribe({
  6300. next: (result) => {
  6301. this.dhProgress = 100;
  6302. this.dhResultVideoUrl = result.videoUrl;
  6303. this.dhStatusText = '数字人视频生成完成!';
  6304. this.dhLoading = false;
  6305. this.dhStep = 'done';
  6306. this.showToast('✅ 数字人视频已生成', 'success', 6000);
  6307. // 保存到结果
  6308. this.saveResult({
  6309. type: 'video',
  6310. url: result.videoUrl,
  6311. title: `数字人合成 - ${new Date().toLocaleString('zh-CN')}`,
  6312. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6313. duration: '数字人视频',
  6314. cost: 0,
  6315. segments: [{ id: 'DH-01', videoUrl: result.videoUrl, prompt: this.dhPrompt, status: 'completed' }]
  6316. });
  6317. this.saveHistoryRecord({
  6318. keyword: '数字人合成',
  6319. status: 'completed',
  6320. cost: 0,
  6321. duration: '数字人视频',
  6322. styleName: '数字人合成',
  6323. resultUrl: result.videoUrl,
  6324. quality: this.dhResolution === '1080p' ? '1080P' : '720P',
  6325. segmentCount: 1,
  6326. successCount: 1
  6327. });
  6328. // 同步到视频管理
  6329. this.addDhVideoToManifest(result.videoUrl);
  6330. this.refreshView();
  6331. },
  6332. error: (err) => this.dhHandleError(typeof err === 'string' ? err : err?.message || err?.error?.message || '数字人视频生成失败')
  6333. });
  6334. },
  6335. error: (err) => this.dhHandleError(typeof err === 'string' ? err : err?.message || err?.error?.message || '数字人主体识别失败')
  6336. });
  6337. },
  6338. error: (err) => this.dhHandleError(typeof err === 'string' ? err : err?.message || err?.error?.message || '提交数字人主体识别失败')
  6339. });
  6340. }
  6341. private dhHandleError(message: string): void {
  6342. this.dhLoading = false;
  6343. this.dhSynthesizing = false;
  6344. this.dhUploadingAudio = false;
  6345. this.dhProgress = 0;
  6346. this.dhStep = 'done';
  6347. this.dhStatusText = message;
  6348. this.dhError = message;
  6349. this.showToast(`❌ ${message}`, 'error');
  6350. this.refreshView();
  6351. }
  6352. // ==================== 视频生成工作流 ====================
  6353. vgReset(): void {
  6354. this.vgStep = 1;
  6355. this.vgSourceFile = null;
  6356. this.vgSourceFileName = '';
  6357. this.vgSourceVideoUrl = '';
  6358. this.vgUploading = false;
  6359. this.vgUploadProgress = 0;
  6360. this.vgVideoId = '';
  6361. this.vgAnalyzing = false;
  6362. this.vgAnalysisText = '';
  6363. this.vgTranscript = '';
  6364. this.vgGeneratingScript = false;
  6365. this.vgScript = '';
  6366. this.vgScriptSegments = [];
  6367. this.vgGeneratingImages = false;
  6368. this.vgImageResults = [];
  6369. this.vgImageProgress = 0;
  6370. this.vgVoiceMode = 'system';
  6371. this.vgVoiceTimbreId = '';
  6372. this.vgSynthesizing = false;
  6373. this.vgAudioUrls = [];
  6374. this.vgCompositing = false;
  6375. this.vgCompositingProgress = 0;
  6376. this.vgFinalVideoUrl = '';
  6377. this.vgError = '';
  6378. this.vgTaskId = '';
  6379. }
  6380. // 视频生成:创建任务(上传成功后调用)
  6381. private vgCreateTask(): void {
  6382. const tempId = `VG-${Date.now()}`;
  6383. const task: Task = {
  6384. id: tempId,
  6385. keyword: this.vgSourceFileName || '视频生成',
  6386. status: 'processing',
  6387. step: 'vg-upload',
  6388. progress: 10,
  6389. cost: 0,
  6390. created_at: new Date(),
  6391. updated_at: new Date(),
  6392. original_video_title: this.vgSourceFileName,
  6393. type: 'video-generation',
  6394. vgData: this.vgBuildSnapshot()
  6395. };
  6396. this.vgTaskId = tempId;
  6397. this.activeTasks.unshift(task);
  6398. // saveTask POST 后端会返回真实 id,回填后同步 vgTaskId
  6399. this.taskSaveReady = new Promise<void>((resolve) => {
  6400. this.http.post<any>('/backend/api/tasks', task).subscribe({
  6401. next: (res) => {
  6402. if (res?.task?.id) {
  6403. task.id = res.task.id;
  6404. this.vgTaskId = res.task.id;
  6405. }
  6406. this.updateTaskStats();
  6407. console.log('💾 视频生成任务已保存:', task.id);
  6408. resolve();
  6409. },
  6410. error: (err) => {
  6411. console.warn('⚠️ 任务保存失败:', err);
  6412. resolve();
  6413. }
  6414. });
  6415. });
  6416. this.updateTaskStats();
  6417. this.showToast('任务已创建,可在「任务管理」中查看和恢复进度', 'success');
  6418. }
  6419. // 视频生成:更新任务进度(每个步骤转换时调用)
  6420. private vgUpdateTaskProgress(step: Task['step'], progress: number, status: Task['status'] = 'processing'): void {
  6421. const task = this.activeTasks.find(t => t.id === this.vgTaskId || (t.type === 'video-generation' && t.vgData?.videoId === this.vgVideoId));
  6422. if (!task) return;
  6423. // 若任务已被用户取消,则不再覆盖回 processing 状态
  6424. if (task.id && this.canceledTaskIds.has(task.id)) {
  6425. return;
  6426. }
  6427. this.vgTaskId = task.id;
  6428. task.step = step;
  6429. task.progress = progress;
  6430. task.status = status;
  6431. task.updated_at = new Date();
  6432. task.error_message = status === 'failed' ? this.vgError : undefined;
  6433. task.vgData = this.vgBuildSnapshot();
  6434. if (status === 'completed' && this.vgFinalVideoUrl) {
  6435. task.result_url = this.vgFinalVideoUrl;
  6436. }
  6437. this.updateTask(task);
  6438. this.updateTaskStats();
  6439. }
  6440. // 视频生成:构建当前状态快照
  6441. private vgBuildSnapshot(): Task['vgData'] {
  6442. return {
  6443. videoId: this.vgVideoId,
  6444. sourceFileName: this.vgSourceFileName,
  6445. sourceVideoUrl: this.vgSourceVideoUrl,
  6446. step: this.vgStep,
  6447. transcript: this.vgTranscript,
  6448. analysisText: this.vgAnalysisText,
  6449. script: this.vgScript,
  6450. scriptSegments: this.vgScriptSegments,
  6451. imageResults: this.vgImageResults,
  6452. audioUrls: this.vgAudioUrls,
  6453. voiceMode: this.vgVoiceMode,
  6454. voiceSpeakerId: this.vgVoiceSpeakerId,
  6455. voiceTimbreId: this.vgVoiceTimbreId,
  6456. finalVideoUrl: this.vgFinalVideoUrl
  6457. };
  6458. }
  6459. // 视频生成:从任务恢复状态
  6460. vgResumeFromTask(task: Task): void {
  6461. if (!task.vgData) {
  6462. this.showToast('该任务没有可恢复的数据', 'warn');
  6463. return;
  6464. }
  6465. const d = task.vgData;
  6466. this.vgTaskId = task.id;
  6467. this.vgVideoId = d.videoId;
  6468. this.vgSourceFileName = d.sourceFileName;
  6469. this.vgSourceVideoUrl = d.sourceVideoUrl;
  6470. this.vgSourceFile = null; // File 对象无法持久化
  6471. this.vgStep = d.step;
  6472. this.vgTranscript = d.transcript;
  6473. this.vgAnalysisText = d.analysisText;
  6474. this.vgScript = d.script;
  6475. this.vgScriptSegments = d.scriptSegments || [];
  6476. this.vgImageResults = d.imageResults || [];
  6477. this.vgAudioUrls = d.audioUrls || [];
  6478. this.vgVoiceMode = d.voiceMode || 'system';
  6479. this.vgVoiceSpeakerId = d.voiceSpeakerId || 'zh_female_shuangkuai-am_16k';
  6480. this.vgVoiceTimbreId = d.voiceTimbreId || '';
  6481. this.vgFinalVideoUrl = d.finalVideoUrl || '';
  6482. this.vgError = '';
  6483. this.vgUploading = false;
  6484. this.vgAnalyzing = false;
  6485. this.vgGeneratingScript = false;
  6486. this.vgGeneratingImages = false;
  6487. this.vgSynthesizing = false;
  6488. this.vgCompositing = false;
  6489. // 切换到视频生成页
  6490. this.setCurrentTab('video-generation');
  6491. this.showToast(`已恢复任务:${d.sourceFileName},当前在第${d.step}步`, 'success');
  6492. this.refreshView();
  6493. }
  6494. // Step 1: 选择源视频文件
  6495. vgSelectFile(event: Event): void {
  6496. const input = event.target as HTMLInputElement;
  6497. const file = input?.files?.[0];
  6498. if (!file) return;
  6499. if (!file.type.startsWith('video/')) {
  6500. this.showToast('请选择视频文件', 'warn');
  6501. return;
  6502. }
  6503. this.vgSourceFile = file;
  6504. this.vgSourceFileName = file.name;
  6505. this.vgSourceVideoUrl = URL.createObjectURL(file);
  6506. this.vgError = '';
  6507. }
  6508. // Step 1 → 2: 上传视频并进入解析
  6509. vgUploadAndAnalyze(): void {
  6510. if (!this.vgSourceFile || this.vgUploading) return;
  6511. this.vgUploading = true;
  6512. this.vgUploadProgress = 0;
  6513. this.vgError = '';
  6514. const formData = new FormData();
  6515. formData.append('video', this.vgSourceFile);
  6516. formData.append('title', `视频生成源 - ${new Date().toLocaleString('zh-CN')}`);
  6517. const xhr = new XMLHttpRequest();
  6518. xhr.open('POST', '/backend/api/upload/video');
  6519. xhr.upload.onprogress = (e) => {
  6520. if (e.lengthComputable) {
  6521. this.vgUploadProgress = Math.round((e.loaded / e.total) * 100);
  6522. this.cdr.detectChanges();
  6523. }
  6524. };
  6525. xhr.onload = () => {
  6526. this.ngZone.run(() => {
  6527. this.vgUploading = false;
  6528. if (xhr.status === 200) {
  6529. try {
  6530. const res = JSON.parse(xhr.responseText);
  6531. if (res?.success && res?.video?.id) {
  6532. this.vgVideoId = res.video.id;
  6533. this.vgStep = 2;
  6534. this.vgCreateTask();
  6535. this.vgUpdateTaskProgress('vg-analyze', 15);
  6536. this.vgStartAnalysis();
  6537. } else {
  6538. this.vgError = '上传返回异常';
  6539. }
  6540. } catch { this.vgError = '解析上传结果失败'; }
  6541. } else {
  6542. this.vgError = `上传失败 (${xhr.status})`;
  6543. }
  6544. this.cdr.detectChanges();
  6545. });
  6546. };
  6547. xhr.onerror = () => {
  6548. this.ngZone.run(() => {
  6549. this.vgUploading = false;
  6550. this.vgError = '网络错误,上传失败';
  6551. this.cdr.detectChanges();
  6552. });
  6553. };
  6554. xhr.send(formData);
  6555. }
  6556. // Step 2: Gemini 视频识别(分析 + 转录),Whisper 作为降级方案
  6557. private vgStartAnalysis(): void {
  6558. this.vgAnalyzing = true;
  6559. this.vgTranscript = '';
  6560. this.vgAnalysisText = '';
  6561. this.refreshView();
  6562. const fileSizeMB = this.vgSourceFile ? this.vgSourceFile.size / 1024 / 1024 : 0;
  6563. if (this.vgSourceFile && fileSizeMB <= 20) {
  6564. // ≤20MB:Gemini 直接分析视频(画面+音频+转录)
  6565. this.vgAnalysisText = `正在将视频 (${fileSizeMB.toFixed(1)}MB) 发送给 Gemini 进行视频理解...`;
  6566. this.refreshView();
  6567. this.vgRunGeminiAnalysisAndTranscript();
  6568. } else if (this.vgVideoId) {
  6569. // >20MB:后端 ffmpeg 提取音轨 → Gemini 音频识别 + 转录
  6570. this.vgAnalysisText = `视频 ${fileSizeMB.toFixed(1)}MB 超过 Gemini 视频限制,正在提取音轨用 Gemini 音频识别...`;
  6571. this.refreshView();
  6572. this.vgRunAudioExtractAndGemini();
  6573. } else {
  6574. // 无文件 → Whisper 降级
  6575. this.vgAnalysisText = '使用 Whisper 语音识别...';
  6576. this.refreshView();
  6577. this.vgRunWhisperFallback();
  6578. }
  6579. }
  6580. // Gemini 一次请求:视频分析 + 精确转录
  6581. private async vgRunGeminiAnalysisAndTranscript(): Promise<void> {
  6582. try {
  6583. const base64 = await this.llmService.fileToBase64(this.vgSourceFile!);
  6584. const mimeType = this.vgSourceFile!.type || 'video/mp4';
  6585. const prompt = `你是一个专业的视频内容分析师。请仔细观看这个视频,完成以下两个任务:
  6586. ===== 任务一:视频内容分析 =====
  6587. 从画面和音频两个维度进行全面分析,提取:
  6588. 1. **视频主题和核心观点**:视频讲了什么
  6589. 2. **画面内容描述**:出现了哪些场景、人物、物体、文字
  6590. 3. **目标受众**:适合什么人群观看
  6591. 4. **内容风格**:教程/评测/新闻/故事/口播/Vlog等
  6592. 5. **关键知识点或亮点**(3-5条)
  6593. 6. **视觉风格评价**:画面质量、构图、色调、字幕等
  6594. 7. **建议的改进方向**
  6595. ===== 任务二:完整语音转录 =====
  6596. 请将视频中所有语音内容逐字转录为中文文本。要求:
  6597. - 忠实还原每一句话,不遗漏、不改写、不总结
  6598. - 保留说话人的原始用词和语气
  6599. - 按自然段落分段
  6600. - 如有专业术语或人名,请尽量准确
  6601. 请严格按以下格式输出(用分隔线区分两部分):
  6602. 【内容分析】
  6603. (这里输出任务一的分析结果)
  6604. ---TRANSCRIPT_START---
  6605. (这里输出任务二的完整语音转录文本,只包含转录内容,不要加任何说明)
  6606. ---TRANSCRIPT_END---`;
  6607. this.llmService.analyzeVideo(base64, mimeType, prompt, {
  6608. model: 'gemini-2.5-flash',
  6609. generationConfig: { maxOutputTokens: 8192 }
  6610. }).subscribe({
  6611. next: (result) => {
  6612. this.vgParseGeminiResult(result);
  6613. this.vgAnalyzing = false;
  6614. this.vgUpdateTaskProgress('vg-analyze', 25);
  6615. this.refreshView();
  6616. },
  6617. error: (err) => {
  6618. console.warn('⚠️ Gemini 视频识别失败,降级为 Whisper:', err);
  6619. this.vgAnalysisText = 'Gemini 识别失败,正在使用 Whisper 语音识别...';
  6620. this.refreshView();
  6621. this.vgRunWhisperFallback();
  6622. }
  6623. });
  6624. } catch (err) {
  6625. console.warn('⚠️ 视频文件读取失败:', err);
  6626. this.vgAnalysisText = '视频文件读取失败,正在使用 Whisper 语音识别...';
  6627. this.refreshView();
  6628. this.vgRunWhisperFallback();
  6629. }
  6630. }
  6631. // 解析 Gemini 返回结果:拆分「内容分析」和「转录文本」
  6632. private vgParseGeminiResult(raw: string): void {
  6633. const transcriptMatch = raw.match(/---TRANSCRIPT_START---([\s\S]*?)---TRANSCRIPT_END---/);
  6634. if (transcriptMatch) {
  6635. this.vgTranscript = transcriptMatch[1].trim();
  6636. // 分析部分 = 转录标记之前的内容
  6637. const analysisPart = raw.substring(0, raw.indexOf('---TRANSCRIPT_START---')).trim();
  6638. this.vgAnalysisText = analysisPart.replace(/^【内容分析】\s*/, '') || '分析完成';
  6639. console.log(`✅ Gemini 分析+转录完成 (转录 ${this.vgTranscript.length} 字)`);
  6640. } else {
  6641. // 没有找到转录标记,整体作为分析结果
  6642. this.vgAnalysisText = raw || '分析完成';
  6643. console.warn('⚠️ Gemini 未返回转录标记,需手动输入文字稿');
  6644. }
  6645. }
  6646. // >20MB 视频:后端 ffmpeg 提取音轨 → Gemini 音频识别(分析+转录)
  6647. private vgRunAudioExtractAndGemini(): void {
  6648. this.http.post<any>('/backend/api/extract-audio-mp3', {
  6649. videoId: this.vgVideoId
  6650. }).subscribe({
  6651. next: (res) => {
  6652. if (res?.success && res?.audio?.base64) {
  6653. const audioSizeMB = res.audio.sizeMB || 0;
  6654. console.log(`🎵 音轨提取完成 (${audioSizeMB}MB),发送给 Gemini 音频识别...`);
  6655. this.vgAnalysisText = `音轨提取完成 (${audioSizeMB.toFixed(1)}MB),正在 Gemini 音频识别...`;
  6656. this.refreshView();
  6657. if (audioSizeMB > 20) {
  6658. // 音频仍然过大,降级为 Whisper
  6659. console.warn('⚠️ 提取的音频仍超过 20MB,降级为 Whisper');
  6660. this.vgAnalysisText = '音频文件仍较大,改用 Whisper 识别...';
  6661. this.refreshView();
  6662. this.vgRunWhisperFallback();
  6663. return;
  6664. }
  6665. const prompt = `你是一个专业的音频内容分析师。请仔细听这段音频,完成以下两个任务:
  6666. ===== 任务一:内容分析 =====
  6667. 从音频内容进行分析,提取:
  6668. 1. **主题和核心观点**:音频讲了什么
  6669. 2. **目标受众**:适合什么人群
  6670. 3. **内容风格**:教程/评测/新闻/故事/口播等
  6671. 4. **关键知识点或亮点**(3-5条)
  6672. 5. **建议的改进方向**
  6673. ===== 任务二:完整语音转录 =====
  6674. 请将音频中所有语音内容逐字转录为中文文本。要求:
  6675. - 忠实还原每一句话,不遗漏、不改写、不总结
  6676. - 保留说话人的原始用词和语气
  6677. - 按自然段落分段
  6678. - 如有专业术语或人名,请尽量准确
  6679. 请严格按以下格式输出(用分隔线区分两部分):
  6680. 【内容分析】
  6681. (这里输出任务一的分析结果)
  6682. ---TRANSCRIPT_START---
  6683. (这里输出任务二的完整语音转录文本,只包含转录内容,不要加任何说明)
  6684. ---TRANSCRIPT_END---`;
  6685. this.llmService.analyzeAudio(res.audio.base64, res.audio.mimeType || 'audio/mp3', prompt, {
  6686. model: 'gemini-2.5-flash',
  6687. generationConfig: { maxOutputTokens: 8192 }
  6688. }).subscribe({
  6689. next: (result) => {
  6690. this.vgParseGeminiResult(result);
  6691. this.vgAnalyzing = false;
  6692. this.refreshView();
  6693. },
  6694. error: (err) => {
  6695. console.warn('⚠️ Gemini 音频识别失败,降级为 Whisper:', err);
  6696. this.vgAnalysisText = 'Gemini 音频识别失败,改用 Whisper...';
  6697. this.refreshView();
  6698. this.vgRunWhisperFallback();
  6699. }
  6700. });
  6701. } else {
  6702. console.warn('⚠️ 音轨提取未返回数据,降级为 Whisper');
  6703. this.vgRunWhisperFallback();
  6704. }
  6705. },
  6706. error: (err) => {
  6707. const detail = err?.error?.error || err?.message || `HTTP ${err?.status}`;
  6708. console.warn('⚠️ 音轨提取失败:', detail, err);
  6709. this.vgAnalysisText = `音轨提取失败 (${detail}),改用 Whisper...`;
  6710. this.refreshView();
  6711. this.vgRunWhisperFallback();
  6712. }
  6713. });
  6714. }
  6715. // 降级方案:Whisper 转录 + GPT 文本分析
  6716. private vgRunWhisperFallback(): void {
  6717. this.http.post<any>('/backend/api/whisper/transcribe', {
  6718. videoId: this.vgVideoId,
  6719. language: 'Chinese',
  6720. model: 'large'
  6721. }).subscribe({
  6722. next: (res) => {
  6723. if (res?.success && res?.transcript) {
  6724. this.vgTranscript = res.transcript;
  6725. this.vgAnalysisText = 'Whisper 转录完成,正在 AI 分析内容...';
  6726. this.refreshView();
  6727. // 用 GPT 做文本分析
  6728. this.vgDoTextAnalysis();
  6729. } else {
  6730. this.vgAnalyzing = false;
  6731. this.vgAnalysisText = '语音识别完成但未返回文字稿,请手动输入';
  6732. this.refreshView();
  6733. }
  6734. },
  6735. error: (err) => {
  6736. this.vgAnalyzing = false;
  6737. this.vgAnalysisText = `Whisper 识别失败: ${err?.error?.error || err?.message || '未知错误'}。请手动输入文字稿。`;
  6738. this.refreshView();
  6739. }
  6740. });
  6741. }
  6742. private vgDoTextAnalysis(): void {
  6743. const systemPrompt = `你是一个专业的视频内容分析师。请分析以下视频的转录文字稿,提取:
  6744. 1. 视频主题和核心观点
  6745. 2. 目标受众
  6746. 3. 内容风格(教程/评测/新闻/故事等)
  6747. 4. 关键知识点或亮点(3-5条)
  6748. 5. 建议的改进方向
  6749. 请用简洁的中文回复。`;
  6750. this.llmService.askWithSystem(systemPrompt, this.vgTranscript, { model: 'gemini-2.5-flash', max_tokens: 1024 }).subscribe({
  6751. next: (analysis) => {
  6752. this.vgAnalysisText = analysis || '分析完成';
  6753. this.vgAnalyzing = false;
  6754. this.refreshView();
  6755. },
  6756. error: () => {
  6757. this.vgAnalysisText = '(AI 文本分析暂不可用,已完成 Whisper 转录)';
  6758. this.vgAnalyzing = false;
  6759. this.refreshView();
  6760. }
  6761. });
  6762. }
  6763. vgConfirmAnalysis(): void {
  6764. if (!this.vgTranscript.trim()) {
  6765. this.showToast('请先完成视频转录或手动输入文字稿', 'warn');
  6766. return;
  6767. }
  6768. this.vgStep = 3;
  6769. this.vgUpdateTaskProgress('vg-script', 30);
  6770. this.vgGenerateScript();
  6771. }
  6772. // Step 3: LLM 生成分镜脚本
  6773. private vgGenerateScript(): void {
  6774. this.vgGeneratingScript = true;
  6775. this.vgScript = '';
  6776. this.vgScriptSegments = [];
  6777. const systemPrompt = `你是一个专业的短视频脚本编剧。根据以下视频转录文字稿,生成一个完整的分镜脚本。
  6778. ⚠️ 最重要的要求:你必须完整覆盖原文的全部内容,不得遗漏任何段落或要点!将原文从头到尾全部改写为分镜旁白,确保信息量100%覆盖。
  6779. 要求:
  6780. 1. 根据内容长度自动决定片段数量(短文5-8段,长文8-15段),确保原文每一段内容都被覆盖到
  6781. 2. 每个片段包含:旁白文本(narration)、配图英文提示词(imagePrompt)、配图中文提示词(imagePromptCn)
  6782. 3. 旁白文本要求:必须包含原文中的所有关键信息、数据、观点,不能省略或概括,只做口语化改写
  6783. 4. 配图中文提示词(imagePromptCn)是最重要的配图生成依据,要求:
  6784. - 描述一幅完整的16:9横版信息图/示意图画面
  6785. - 必须全部用中文描述,图片中的所有文字标注都是中文
  6786. - 内容紧密关联该段旁白,提取关键数据、概念、流程等
  6787. - 风格:白色或浅色简洁背景,扁平化设计,信息图表/流程图/概念图
  6788. - 包含中文大标题、关键词、数据可视化、图标、箭头等元素
  6789. - 注意:提示词中不要出现"PPT"、"幻灯片"、"演示文稿"等字样,只描述画面内容本身
  6790. 5. 配图英文提示词(imagePrompt)是备选提示词,描述同样的画面内容
  6791. 请严格按以下 JSON 格式返回(不要包含其他文字,不要用 markdown 代码块包裹):
  6792. [
  6793. {"id": "S-01", "narration": "旁白文本...", "imagePrompt": "English: 16:9 infographic...", "imagePromptCn": "16:9横版信息图,白色背景,大标题"xxx",下方用流程图展示xxx的步骤..."},
  6794. {"id": "S-02", "narration": "旁白文本...", "imagePrompt": "English: 16:9 infographic...", "imagePromptCn": "16:9横版信息图,浅色背景,标题"xxx",用图标和箭头展示xxx的关系..."}
  6795. ]`;
  6796. this.llmService.askWithSystem(systemPrompt, this.vgTranscript, { model: 'gemini-2.5-flash', max_tokens: 16384 }).subscribe({
  6797. next: (result) => {
  6798. this.vgScript = result;
  6799. this.vgGeneratingScript = false;
  6800. this.vgParseScriptSegments(result);
  6801. this.vgUpdateTaskProgress('vg-script', 40);
  6802. this.refreshView();
  6803. },
  6804. error: (err) => {
  6805. this.vgGeneratingScript = false;
  6806. this.vgError = `脚本生成失败: ${err?.message || '请重试'}`;
  6807. this.vgUpdateTaskProgress('vg-script', 30, 'failed');
  6808. this.refreshView();
  6809. }
  6810. });
  6811. }
  6812. private vgParseScriptSegments(raw: string): void {
  6813. console.log('📝 原始脚本响应:', raw.substring(0, 500));
  6814. // 1. 去除 markdown code block 包裹
  6815. let cleaned = raw;
  6816. const codeBlockMatch = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
  6817. if (codeBlockMatch) {
  6818. cleaned = codeBlockMatch[1].trim();
  6819. }
  6820. // 2. 尝试提取 JSON 数组
  6821. const jsonMatch = cleaned.match(/\[[\s\S]*\]/);
  6822. if (jsonMatch) {
  6823. cleaned = jsonMatch[0];
  6824. }
  6825. // 3. 修复常见 JSON 问题(尾部逗号)
  6826. cleaned = cleaned.replace(/,\s*([}\]])/g, '$1');
  6827. try {
  6828. const parsed = JSON.parse(cleaned);
  6829. if (Array.isArray(parsed) && parsed.length > 0) {
  6830. this.vgScriptSegments = parsed.map((item: any, i: number) => ({
  6831. id: item.id || `S-${String(i + 1).padStart(2, '0')}`,
  6832. narration: item.narration || '',
  6833. imagePrompt: item.imagePrompt || item.image_prompt || '',
  6834. imagePromptCn: item.imagePromptCn || item.image_prompt_cn || ''
  6835. }));
  6836. console.log(`✅ 脚本解析成功: ${this.vgScriptSegments.length} 个片段`);
  6837. return;
  6838. }
  6839. } catch (e) {
  6840. console.warn('⚠️ JSON.parse 失败:', (e as Error).message);
  6841. }
  6842. // 4. 逐对象提取 fallback:正则匹配每个 {...} 块
  6843. try {
  6844. const objMatches = cleaned.match(/\{[^{}]*\}/g);
  6845. if (objMatches && objMatches.length > 0) {
  6846. const segments: any[] = [];
  6847. for (const objStr of objMatches) {
  6848. try {
  6849. const obj = JSON.parse(objStr.replace(/,\s*}/g, '}'));
  6850. if (obj.narration) segments.push(obj);
  6851. } catch {}
  6852. }
  6853. if (segments.length > 0) {
  6854. this.vgScriptSegments = segments.map((item: any, i: number) => ({
  6855. id: item.id || `S-${String(i + 1).padStart(2, '0')}`,
  6856. narration: item.narration || '',
  6857. imagePrompt: item.imagePrompt || item.image_prompt || '',
  6858. imagePromptCn: item.imagePromptCn || item.image_prompt_cn || ''
  6859. }));
  6860. console.log(`✅ 逐对象解析成功: ${this.vgScriptSegments.length} 个片段`);
  6861. return;
  6862. }
  6863. }
  6864. } catch {}
  6865. // 5. 最终 fallback:保留原始文本供用户手动编辑
  6866. console.warn('⚠️ 脚本解析全部失败,显示原文供手动编辑');
  6867. this.vgScriptSegments = [{
  6868. id: 'S-01',
  6869. narration: raw.replace(/```[\s\S]*?```/g, '').trim(),
  6870. imagePrompt: 'Professional PPT slide illustration, clean white background, infographic style',
  6871. imagePromptCn: '(脚本自动解析失败,请手动拆分片段)'
  6872. }];
  6873. }
  6874. vgConfirmScript(): void {
  6875. if (this.vgScriptSegments.length === 0) {
  6876. this.showToast('请先生成或编辑脚本', 'warn');
  6877. return;
  6878. }
  6879. this.vgStep = 4;
  6880. this.vgUpdateTaskProgress('vg-image', 45);
  6881. // 初始化图片结果列表
  6882. this.vgImageResults = this.vgScriptSegments.map(seg => ({
  6883. id: seg.id,
  6884. prompt: seg.imagePromptCn || seg.imagePrompt,
  6885. imageUrl: '',
  6886. status: 'pending' as const
  6887. }));
  6888. }
  6889. // Step 4: 批量生成配图(使用即梦 API)
  6890. vgGenerateImages(): void {
  6891. if (this.vgGeneratingImages) return;
  6892. this.vgGeneratingImages = true;
  6893. this.vgImageProgress = 0;
  6894. const pending = this.vgImageResults.filter(r => r.status === 'pending');
  6895. if (pending.length === 0) {
  6896. this.vgGeneratingImages = false;
  6897. return;
  6898. }
  6899. let completed = 0;
  6900. const total = pending.length;
  6901. const RETRY_MAX = 5;
  6902. const RETRY_DELAY = 15000; // 并发超限时等 15 秒重试
  6903. const GAP_DELAY = 6000; // 每张图之间间隔 6 秒,避免并发
  6904. const generateNext = (index: number, retryCount: number = 0) => {
  6905. if (index >= pending.length) {
  6906. this.vgGeneratingImages = false;
  6907. this.vgUpdateTaskProgress('vg-image', 60);
  6908. this.showToast(`配图生成完成 (${completed}/${total})`, completed > 0 ? 'success' : 'warn');
  6909. this.refreshView();
  6910. return;
  6911. }
  6912. const item = pending[index];
  6913. item.status = 'generating';
  6914. this.refreshView();
  6915. this.jimengService.generateImage(item.prompt, 1920, 1080).subscribe({
  6916. next: (res: any) => {
  6917. const workId = res?.data?.workId || res?.workId;
  6918. if (!workId) {
  6919. item.status = 'failed';
  6920. completed++;
  6921. this.refreshView();
  6922. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  6923. return;
  6924. }
  6925. this.jimengService.pollUntilComplete(workId, 'getText2ImgV31', (status: any, attempt: number) => {
  6926. this.vgImageProgress = Math.round(((completed + Math.min(attempt / 20, 0.9)) / total) * 100);
  6927. this.refreshView();
  6928. }).subscribe({
  6929. next: (result: any) => {
  6930. const imageUrl = result?.images?.[0] || result?.url || '';
  6931. item.imageUrl = imageUrl;
  6932. item.status = imageUrl ? 'done' : 'failed';
  6933. completed++;
  6934. this.vgImageProgress = Math.round((completed / total) * 100);
  6935. this.refreshView();
  6936. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  6937. },
  6938. error: () => {
  6939. item.status = 'failed';
  6940. completed++;
  6941. this.refreshView();
  6942. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  6943. }
  6944. });
  6945. },
  6946. error: (err) => {
  6947. const errMsg = err?.error?.error?.message || err?.error?.message || err?.message || '';
  6948. const isRetryable = errMsg.includes('并发超限') || err?.status === 500 || err?.status === 429;
  6949. if (isRetryable && retryCount < RETRY_MAX) {
  6950. const backoff = RETRY_DELAY * (retryCount + 1); // 递增退避: 15s, 30s, 45s...
  6951. console.warn(`⚠️ 配图 ${item.id} 请求失败(${errMsg || err?.status}),${backoff / 1000}s 后第${retryCount + 1}次重试...`);
  6952. item.status = 'pending';
  6953. this.refreshView();
  6954. setTimeout(() => generateNext(index, retryCount + 1), backoff);
  6955. } else {
  6956. console.error(`❌ 配图 ${item.id} 最终失败:`, errMsg || err?.status);
  6957. item.status = 'failed';
  6958. completed++;
  6959. this.refreshView();
  6960. setTimeout(() => generateNext(index + 1), GAP_DELAY);
  6961. }
  6962. }
  6963. });
  6964. };
  6965. generateNext(0);
  6966. }
  6967. vgConfirmImages(): void {
  6968. this.vgStep = 5;
  6969. this.vgUpdateTaskProgress('vg-voice', 65);
  6970. }
  6971. // Step 5: 语音配音
  6972. vgSynthesizeAll(): void {
  6973. if (this.vgSynthesizing) return;
  6974. this.vgSynthesizing = true;
  6975. this.vgAudioUrls = [];
  6976. this.vgError = '';
  6977. const segments = this.vgScriptSegments;
  6978. let index = 0;
  6979. const synthNext = () => {
  6980. if (index >= segments.length) {
  6981. this.vgSynthesizing = false;
  6982. this.vgUpdateTaskProgress('vg-voice', 80);
  6983. this.showToast(`配音完成 (${this.vgAudioUrls.length}/${segments.length})`, 'success');
  6984. this.refreshView();
  6985. return;
  6986. }
  6987. const seg = segments[index];
  6988. const text = seg.narration;
  6989. if (!text.trim()) {
  6990. index++;
  6991. synthNext();
  6992. return;
  6993. }
  6994. // 使用远程 TTS 合成(server.fmode.cn)
  6995. const payload: any = {
  6996. token: this.voiceApiToken,
  6997. text,
  6998. isStream: false,
  6999. audio_params: {
  7000. format: 'mp3',
  7001. sample_rate: 24000,
  7002. speech_rate: 0,
  7003. loudness_rate: 0
  7004. }
  7005. };
  7006. if (this.vgVoiceMode === 'clone' && this.vgVoiceTimbreId) {
  7007. payload.timbreId = this.vgVoiceTimbreId;
  7008. } else {
  7009. payload.speaker_id = this.vgVoiceSpeakerId || 'zh_female_shuangkuai-am_16k';
  7010. }
  7011. this.http.post<any>(`${this.voiceTtsBaseUrl}/unidirectional`, payload).subscribe({
  7012. next: (res) => {
  7013. const audioUrl = res?.data?.audioUrl || '';
  7014. if (audioUrl) {
  7015. this.vgAudioUrls.push({ segId: seg.id, audioUrl });
  7016. } else {
  7017. console.warn(`配音片段 ${seg.id}: 未返回 audioUrl`, res);
  7018. }
  7019. index++;
  7020. this.refreshView();
  7021. synthNext();
  7022. },
  7023. error: (err) => {
  7024. console.warn(`配音片段 ${seg.id} 失败:`, err);
  7025. index++;
  7026. synthNext();
  7027. }
  7028. });
  7029. };
  7030. synthNext();
  7031. }
  7032. vgConfirmVoice(): void {
  7033. this.vgStep = 6;
  7034. this.vgUpdateTaskProgress('vg-composite', 85);
  7035. }
  7036. // Step 6: 合成最终视频(图片+音频 → 视频)
  7037. vgComposite(): void {
  7038. this.vgCompositing = true;
  7039. this.vgCompositingProgress = 0;
  7040. this.vgFinalVideoUrl = '';
  7041. this.vgError = '';
  7042. this.refreshView();
  7043. // 构建片段数据:匹配图片和音频
  7044. const segments: { id: string; imageUrl: string; audioUrl: string; }[] = [];
  7045. for (const seg of this.vgScriptSegments) {
  7046. const img = this.vgImageResults.find(r => r.id === seg.id);
  7047. const audio = this.vgAudioUrls.find(a => a.segId === seg.id);
  7048. if (img?.imageUrl && audio?.audioUrl) {
  7049. segments.push({ id: seg.id, imageUrl: img.imageUrl, audioUrl: audio.audioUrl });
  7050. }
  7051. }
  7052. if (segments.length === 0) {
  7053. this.vgCompositing = false;
  7054. this.vgError = '没有可用的图片+音频配对,无法合成视频';
  7055. this.showToast(this.vgError, 'error');
  7056. this.refreshView();
  7057. return;
  7058. }
  7059. // 模拟进度(因为后端是同步处理,用定时器模拟进度条)
  7060. let fakeProgress = 0;
  7061. const progressTimer = setInterval(() => {
  7062. fakeProgress = Math.min(fakeProgress + 2, 90);
  7063. this.vgCompositingProgress = fakeProgress;
  7064. this.refreshView();
  7065. }, 1000);
  7066. this.http.post<any>('/backend/api/video/composite', {
  7067. segments,
  7068. title: this.vgSourceFileName?.replace(/\.[^.]+$/, '') || '视频生成'
  7069. }).subscribe({
  7070. next: (res) => {
  7071. clearInterval(progressTimer);
  7072. this.vgCompositingProgress = 100;
  7073. this.vgCompositing = false;
  7074. if (res?.success && res?.videoUrl) {
  7075. this.vgFinalVideoUrl = '/backend' + res.videoUrl;
  7076. this.vgUpdateTaskProgress('vg-composite', 100, 'completed');
  7077. this.showToast(`视频合成完成!共 ${res.segments} 个片段`, 'success');
  7078. } else {
  7079. this.vgError = '合成返回结果异常';
  7080. this.vgUpdateTaskProgress('vg-composite', 90, 'failed');
  7081. this.showToast(this.vgError, 'error');
  7082. }
  7083. this.refreshView();
  7084. },
  7085. error: (err) => {
  7086. clearInterval(progressTimer);
  7087. this.vgCompositing = false;
  7088. this.vgCompositingProgress = 0;
  7089. this.vgError = `视频合成失败: ${err?.error?.error || err?.message || '请重试'}`;
  7090. this.vgUpdateTaskProgress('vg-composite', 85, 'failed');
  7091. this.showToast(this.vgError, 'error');
  7092. this.refreshView();
  7093. }
  7094. });
  7095. }
  7096. // 回到上一步
  7097. vgPrevStep(): void {
  7098. if (this.vgStep > 1) this.vgStep--;
  7099. }
  7100. // ===== 卡片瀑布展开/折叠控制 =====
  7101. vgGetStepState(n: number): 'done' | 'active' | 'locked' {
  7102. if (n < this.vgStep) return 'done';
  7103. if (n === this.vgStep) return 'active';
  7104. return 'locked';
  7105. }
  7106. vgIsStepExpanded(n: number): boolean {
  7107. if (n > this.vgStep) return false; // 未解锁:永远折叠
  7108. if (n === this.vgStep) return true; // 当前步骤:始终展开
  7109. return this.vgUserExpandedSteps.has(n); // 已完成:仅在用户手动展开时显示
  7110. }
  7111. vgToggleStepExpand(n: number): void {
  7112. if (n >= this.vgStep) return; // 当前/未解锁不可切换
  7113. if (this.vgUserExpandedSteps.has(n)) this.vgUserExpandedSteps.delete(n);
  7114. else this.vgUserExpandedSteps.add(n);
  7115. }
  7116. // 跳转到某个已完成步骤进行编辑(同时展开它)
  7117. vgEditStep(n: number): void {
  7118. if (n > this.vgStep) return; // 不能跳到未解锁
  7119. if (n < this.vgStep) {
  7120. const downstream = this.vgStep - n;
  7121. const ok = confirm(`返回步骤 ${n}「${this.vgStepLabels[n - 1]}」编辑后,需要重新确认下游 ${downstream} 个步骤,相关结果(脚本/配图/配音/合成)可能会被覆盖。是否继续?`);
  7122. if (!ok) return;
  7123. }
  7124. this.vgStep = n;
  7125. // 同时把该步骤从用户展开集合中清除(active 步骤会自动展开)
  7126. this.vgUserExpandedSteps.delete(n);
  7127. }
  7128. // 重新生成脚本
  7129. vgRegenerateScript(): void {
  7130. this.vgGenerateScript();
  7131. }
  7132. private addDhVideoToManifest(videoUrl: string): void {
  7133. const now = new Date();
  7134. const id = `DH-${Date.now()}`;
  7135. const title = `数字人合成 - ${now.toLocaleString('zh-CN')}`;
  7136. const filename = videoUrl.split('/').pop() || `digital-human-${id}.mp4`;
  7137. const newEntry = {
  7138. id,
  7139. title,
  7140. filename,
  7141. filepath: videoUrl,
  7142. size: 0,
  7143. duration: 0,
  7144. created_at: now.toISOString(),
  7145. modified_at: now.toISOString(),
  7146. category: 'general',
  7147. tags: ['数字人', 'AI生成'],
  7148. description: `数字人合成视频 (${this.dhResolution})`,
  7149. source: 'generated',
  7150. metadata: {
  7151. resolution: this.dhResolution === '1080p' ? '1920x1080' : '1280x720',
  7152. format: 'mp4'
  7153. }
  7154. };
  7155. this.http.post<any>('/backend/api/manifest', newEntry).subscribe({
  7156. next: (res) => {
  7157. if (res?.success) {
  7158. this.managedVideos.unshift({
  7159. ...newEntry,
  7160. created_at: now,
  7161. modified_at: now,
  7162. source: 'generated' as const
  7163. } as ManagedVideo);
  7164. this.updateCategoryCounts();
  7165. console.log('📁 数字人视频已同步到视频管理:', id);
  7166. }
  7167. },
  7168. error: (err) => console.warn('⚠️ 同步视频管理失败:', err)
  7169. });
  7170. }
  7171. }