1import{j as e,a}from"./vendor-core.6lta8LCj.js";import{a0 as W,b as le,c as Z,e4 as hn,R as We,F as Pt,B as E,S as O,H as be,bp as fn,k as vt,j as Ae,K as xn,af as ve,as as P,at as L,au as I,ai as vn,cF as bn,cG as bt,az as fe,cN as yn,cU as Ge,v as wn,aM as yt,J as En,dM as Cn,bc as wt}from"./bootstrap.Yl9dpo2n.js";import{s as Sn,a as Pe,u as Dn}from"./xstate-react.esm.DZ5rsZvF.js";import{C as Vn}from"./CustomVoiceCapacityBanner.C3oJVB8X.js";import{I as Et,w as jn,C as In}from"./waitForPublishedVoices.B2o7ytSg.js";import{L as ue}from"./language_codes.pb.GWTrqnbO.js";import{D as Le,n as Tn}from"./useTTSVoicesV1.DSrWx7wt.js";import{P as Lt}from"./PlayButton._MdmE9Fc.js";import{c as _n,q as An,r as Pn,s as Ln,t as kn}from"./voices.4R5uC5ue.js";import{H as Rn}from"./CharacterSectionHelp.DOBjujku.js";import{g as Nn,M as kt,l as Ct,t as Rt}from"./languages.D_58T5oC.js";import{a as Fn,u as On,L as Gn,b as Me,V as Mn}from"./VoiceFormSection.DnSOqjMc.js";import{k as $,u as Un,l as ke,P as Bn,m as xe,n as $n,o as Re,V as Ne,I as Wn,a as Fe}from"./constants.jWjxC6rh.js";import"./vendor-firebase.dbYXL2Q0.js";import{f as Nt,C as St,t as Ue,ap as Dt,a9 as Vt,g as zn,q as qn,I as Hn,L as Kn}from"./App.DVmysEmP.js";import{s as Xn,y as j,ae as Be,ac as Yn,a7 as oe}from"./vendor-mui-x.CmnfcHjQ.js";import{e as Qn}from"./voicePickerPersistence.CvrMrcAp.js";import{S as Jn}from"./Slider.DKbSeTyH.js";import{A as Zn,m as ei}from"./vendor-framer-motion.CZgi-nAu.js";import"./capacityBannerUtils.hd491eqT.js";import"./utils.W3chGjiC.js";import"./useQueries.AyQcqfc2.js";import"./useHasPaidAccess.DWTRNMc3.js";import"./InworldAutocomplete.CfAdODpr.js";import"./InworldTextField.0GNO1Aiy.js";import"./LanguageFlagIcon.DD6sRh3E.js";import"./localeCountry.Ct_qy4z3.js";import"./languageOptionOrder.DXb3-FfN.js";import"./phonePickerInput.DiwofPS3.js";const Ft=({view:n,onChange:i,sx:r})=>{const s=n==="profile";return e.jsx(W,{className:"TextDesignViewSwitchButton",intent:"secondary",size:"small","aria-label":s?"Switch to Freeform":"Switch to Structured",startIcon:e.jsx(le,{icon:s?Z.faAlignLeft:Z.faSliders}),onClick:()=>i(s?"assisted":"profile"),sx:r,children:s?"Freeform":"Structured"})},ti=n=>{const i=a.useRef(n);a.useEffect(()=>{i.current=n},[n]),a.useEffect(()=>hn(r=>i.current(r)),[])},Ot=Xn(W)(({theme:n})=>({fontSize:Pt.sm,height:"1.5rem",border:"1px solid",borderColor:n.palette.divider,borderRadius:We.sm,padding:"0 0.5rem",minHeight:"unset","&:hover":{borderColor:n.palette.primary.main}})),Gt=({disabled:n=!1,showCharacterCounter:i=!1,currentValue:r="",maxLength:s,children:l})=>l===void 0&&!i?null:e.jsx(E,{component:"div",sx:{position:"absolute",bottom:"0.5rem",left:0,px:"0.5rem",width:"100%"},children:e.jsxs(O,{direction:"row",useFlexGap:!0,spacing:1,sx:{flexWrap:"wrap",alignItems:"flex-end"},children:[l,i&&s&&e.jsxs(j,{variant:"caption",component:"p",sx:{color:"text.secondary",".MuiStack-root > &":{ml:"auto"}},children:[(r==null?void 0:r.length)||0," / ",s]})]})}),ni=[[/[\u2018\u2019\u201A\u201B\u02BC]/g,"'"],[/[\u201C\u201D\u201E\u201F]/g,'"'],[/[\u2014\uFE58\uFE31]/g,"--"],[/[\u2013\u2012\u2212\uFE32]/g,"-"],[/[\u2026]/g,"..."],[/[\u00A0\u202F\u2009\u2008\u2007\u3000\uFEFF]/g," "],[/[\u00B6]/g,` 2`],[new RegExp("\v","g"),` 3`],[/[\u2028\u2029]/g,` 4`]];function K(n){let i=n;for(const[r,s]of ni)i=i.replace(r,s);return i}const ii=["dialect","gender","age","emotion","tone","pitch","volume","speed","clarity","fluency","personality","texture","environment"],Oe=ii.map(n=>`${n}: `).join(` 5`),ri=/^([a-z][a-z0-9 _-]*?)\s*:\s*(.*)$/,ai=n=>K(n).replace(/\s+/g," ").trim().toLowerCase(),ze=n=>K(n!=null?n:"").split(` 6`).reduce((i,r)=>{const s=ai(r);if(!s)return i;const l=ri.exec(s);return i.push(l?{key:l[1],value:l[2].trim(),text:s}:{key:null,value:"",text:s}),i},[]),si=n=>{const i=K(n!=null?n:"").trim();return i?(i.includes(` 7`)?i.split(` 8`):i.split(";")).map(r=>r.trim()).filter(Boolean).join(` 9`):""},oi=n=>ze(n).map(i=>i.key===null?i.text:i.value?`${i.key}: ${i.value}
9`:"").filter(Boolean).join(` 10`),li=(n,i)=>{const r=ze(n),s={key:"dialect",value:i,text:`dialect: ${i}`},l=r.some(c=>c.key==="dialect")?r.map(c=>c.key==="dialect"?s:c):[s,...r];return ci(l)},ci=n=>n.map(i=>i.key===null?i.text:`${i.key}: ${i.value}`).join(` 11`),jt=new Map(kt.filter(n=>n.value!==ue.LANGUAGE_CODE_UNSPECIFIED).map(n=>[n.title.split(" (")[0].toLowerCase(),n.value])),ui={cockney:"english",geordie:"english",scouse:"english",brummie:"english","received pronunciation":"english",estuary:"english",parisian:"french",quebecois:"french",cajun:"french",castilian:"spanish",andalusian:"spanish",bavarian:"german",levantine:"arabic"},$e=n=>{var i,r;return(r=(i=ze(n).find(s=>s.key==="dialect"&&s.value))==null?void 0:i.value)!=null?r:null},di=new Set(["accent","accents","dialect","dialects"]),mi=n=>n.toLowerCase().split(/\bwith\b/)[0].split(/[,;:/()[\]]/).map(i=>{const r=i.split(/\s+/).filter(Boolean);for(;r.length&&di.has(r[r.length-1]);)r.pop();return r.join(" ")}).filter(Boolean),Mt=n=>{var r,s;const i=mi(n);for(const l of i){const c=jt.get((r=l.split(" ").pop())!=null?r:"");if(c)return c}for(const l of i)for(const[c,x]of Object.entries(ui))if(` ${l} `.includes(` ${c} `))return(s=jt.get(x))!=null?s:null;return null},pi=(n,i)=>{if(!i||i===ue.LANGUAGE_CODE_UNSPECIFIED)return null;const r=i.toLowerCase().replace(/_/g,"-"),s=n.find(c=>c.code.toLowerCase()===r);if(s){const c=[s.accentDisplayName,s.familyDisplayName].filter(Boolean).join(" ").toLowerCase();if(c)return c}const l=Nn(i);return!l||l===i?null:l.split(" (")[0].toLowerCase()},It=n=>{const i=$e(n);return i?Mt(i):null},gi=(n,i)=>!!n&&!!i&&n.split(/[-_]/)[0].toLowerCase()===i.split(/[-_]/)[0].toLowerCase(),hi=8,fi=`Write or paste a voice profile, one attribute per line (e.g., 12dialect: japanese 13gender: female 14age: young 15...)`,xi=({initialBlock:n,disabled:i,onBlockEdit:r,onDialectValue:s,suggestionChips:l,onChipApplied:c})=>{const[x,S]=a.useState(n),C=a.useRef($e(n)),T=g=>{const p=K(g).slice(0,$);S(p),r(p);const y=$e(p);y!==C.current&&(C.current=y,s(y!=null?y:""))};return e.jsxs(E,{component:"div",className:"CanonicalProfileReview",children:[e.jsxs(E,{component:"div",sx:{position:"relative"},children:[e.jsx(Be,{value:x,onChange:g=>T(g.target.value),multiline:!0,minRows:Math.max(hi,n.split(` 16`).length+1),fullWidth:!0,variant:"outlined",className:"inworld-text-field",size:"small",disabled:i,placeholder:fi,slotProps:{htmlInput:{maxLength:$,"aria-label":"Voice profile"}},sx:{"& .MuiInputBase-root.MuiOutlinedInput-root":{pb:"2.5rem"},"& .MuiInputBase-inputMultiline":{fontSize:Pt.md,lineHeight:1.9}}}),e.jsx(Gt,{showCharacterCounter:!0,currentValue:x,maxLength:$})]}),!!(l!=null&&l.length)&&e.jsx(O,{direction:"row",useFlexGap:!0,spacing:1,sx:{flexWrap:"wrap",mt:1},children:l.map(g=>e.jsx(Ot,{intent:"ghost","aria-label":g.label,disabled:i,onClick:()=>{T(g.description),c==null||c(g)},children:g.label},g.label))})]})},vi=40,bi=3,yi=60,wi=/^(the\s+)?voice\s+of\s+\S/i,Ei=n=>/does not describe how the voice should sound/i.test(n!=null?n:""),Ci=n=>{const i=n.trim();if(!i)return null;if(wi.test(i))return"name";const r=i.split(/\s+/).length;return i.length<=vi&&r<=bi?"name":i.length>=yi?"script":null},Si=[{label:"Agent",description:"A patient, helpful female voice, 25-40 years old. Warm, friendly tone with genuine empathy. Professional yet approachable. Skilled at conveying understanding and solutions."},{label:"Narrator",description:"A mature male voice speaking at a steady pace and neutral tone. The timbre is warm and resonant, conveying a sense of calm and authority, suitable for narrations."},{label:"Companion",description:"A bright, enthusiastic young female voice in her early 20s. High energy with upward inflections and animated delivery. Fast-paced, bubbly tone with expressive variations."},{label:"Instructor",description:"A soothing, calming female voice, 30-45 years old. Gentle, flowing delivery with natural pauses and smooth transitions. Warm, peaceful tone that creates relaxation without sounding robotic."},{label:"Pirate",description:"A swaggering pirate captain in his fifties, loud and boisterous, with a harsh, gravelly rasp. He drags out his vowels and laughs mid-sentence."}],Di=[{label:"Agent",description:["dialect: general american english","gender: female","age: adult","emotion: empathetic and understanding","tone: warm, friendly, and professional","pitch: mid-range with gentle, reassuring inflections","volume: moderate and consistent","speed: moderate pace with thoughtful pauses","clarity: clear and well-articulated","fluency: fluent with no hesitations","personality: patient, helpful, and approachable","texture: smooth and warm","environment: quiet indoor studio"].join(` 17`)},{label:"Narrator",description:["dialect: general american english","gender: male","age: middle-aged","emotion: calm and composed","tone: neutral, conveying a sense of authority","pitch: low male pitch with a relatively flat contour","volume: moderate and consistent","speed: slow and deliberate, with measured pauses","clarity: highly articulate and precise","fluency: fluent and measured","personality: authoritative and composed","texture: warm and resonant","environment: clean studio recording with very low noise"].join(` 18`)},{label:"Companion",description:["dialect: general american english","gender: female","age: young","emotion: cheerful and enthusiastic","tone: upbeat and animated","pitch: medium-high female pitch with rising inflections","volume: moderate to loud","speed: fast-paced and energetic","clarity: clear with expressive emphasis","fluency: fluent and lively","personality: bubbly, outgoing, and expressive","texture: bright and youthful","environment: quiet indoor studio"].join(` 19`)},{label:"Instructor",description:["dialect: general american english","gender: female","age: adult","emotion: serene and reassuring","tone: gentle and soothing","pitch: low to mid-range with soft inflections","volume: soft and even","speed: slow, with long c
19alming pauses","clarity: clear and unhurried","fluency: fluent with natural, flowing phrasing","personality: calm, nurturing, and mindful","texture: soft, breathy, and smooth","environment: quiet indoor studio"].join(` 20`)},{label:"Pirate",description:["dialect: west country english","gender: male","age: adult","emotion: amused and lighthearted","tone: performative and theatrical","pitch: medium-low male pitch with varied intonation for emphasis","volume: loud and projecting","speed: slow and deliberate, with dramatic pauses","clarity: moderate, some words are slurred or mumbled","fluency: fluent but interrupted by laughter","personality: playful, confident, and a bit mischievous","texture: harsh and raspy, with a gravelly, weathered quality","environment: large, reverberant indoor space, like a hall or chamber"].join(` 21`)}],Ut=a.createContext(null),Vi=({view:n,setView:i,children:r})=>{const s=a.useMemo(()=>({view:n,setView:i}),[n,i]);return e.jsx(Ut.Provider,{value:s,children:r})},ji=n=>{const i=a.useContext(Ut),[r,s]=a.useState(n),l=a.useMemo(()=>({view:r,setView:s}),[r]);return{...i!=null?i:l,hostedInHeader:!!i}},Tt=ue.EN_US,Ii=/Generated preview audio is [\d.]+s long, but must be between \d+s and \d+s\./,Ti=n=>{const i=n.match(Ii);return i?i[0]:null},_t=({control:n,name:i,maxLength:r,children:s})=>{const l=zn({control:n,name:i});return e.jsx(Gt,{showCharacterCounter:!0,currentValue:l,maxLength:r,children:s})},_i=({snapshot:n,send:i})=>{var lt,ct,ut,dt,mt,pt,gt,ht,ft,xt;const{workspace:r}=be(),{atOrOverLimit:s,remaining:l}=_n(r),{requireAccess:c,openAsk:x,dismissAsk:S}=Fn("voice-design"),[C]=fn(),T=C.get("prompt"),g=vt(Ae.STUDIO_V2_TTS_LANGUAGE_ACCENT_SELECTION),y=((lt=xn(Ae.STUDIO_TVD_GUIDE_URL).payload)==null?void 0:lt.value)||"",d=n.context.textDesignData,ee=(ut=(ct=d==null?void 0:d.voiceDescription)!=null?ct:T)!=null?ut:"",G=vt(Ae.STUDIO_TVD_DISABLE_AUTO_GENERATE_SCRIPT),m=kt.filter(t=>t.value!==ue.LANGUAGE_CODE_UNSPECIFIED),{control:D,handleSubmit:N,setValue:k,getValues:X,watch:ye,formState:{errors:te}}=Nt({defaultValues:{voiceDescription:ee,language:(dt=d==null?void 0:d.language)!=null?dt:Tt,previewScript:(mt=d==null?void 0:d.previewScript)!=null?mt:""},mode:"onTouched"}),q=ye("language"),de=Yn(t=>t.breakpoints.down("sm")),ne=a.useRef(!1),V=Un(),v=a.useCallback(t=>k("language",t),[k]);On({enabled:g&&(d==null?void 0:d.language)==null,entries:V,apply:v});const{view:h,setView:b,hostedInHeader:Y}=ji((d==null?void 0:d.canonicalPrompt)!=null?"profile":"assisted"),F=h==="profile",we=
21a.useRef(h),[qe,Ee]=a.useState({block:(pt=d==null?void 0:d.canonicalPrompt)!=null?pt:"",seq:0}),M=a.useRef((gt=d==null?void 0:d.canonicalPrompt)!=null?gt:null),[me,He]=a.useState(!1),Ke=a.useRef(!1),pe=a.useCallback(t=>K(t).replace(/\s+/g," ").trim(),[]),Xe=(ht=n.context.generatedVoices)!=null?ht:[],Bt=(ft=n.context.selectedGeneratedVoices)!=null?ft:[],Ye=a.useRef(!0);a.useEffect(()=>()=>{Ye.current=!1},[]);const[_,ie]=a.useState(!1),[U,Qe]=a.useState(Xe),[re,Je]=a.useState(new Set(Bt.map(t=>t.id))),[Ce,ae]=a.useState(null),[$t,Se]=a.useState(!1),[Wt,zt]=a.useState((xt=n.context.lowBalance)!=null?xt:!1),[Ze,B]=a.useState(null),[De,Ve]=a.useState(null),et=a.useRef(null),H=a.useRef(null);H.current||(H.current=new Audio);const je=a.useRef(Xe.filter(t=>t.audioUrl).map(t=>t.audioUrl)),Q=a.useRef(0),Ie=a.useRef(!1),Te=a.useRef(0),tt=a.useRef(null),_e=a.useRef(""),qt=a.useCallback(()=>{zt(!0),i({type:"setLowBalance"})},[i]);ti(qt);const{mutateAsync:nt}=An(r!=null?r:"",t=>{Ge(t)||ve("Failed to prepare the voice profile. Please try again.")}),{mutateAsync:it}=Pn(r!=null?r:"",()=>{}),{mutate:rt}=Ln(r!=null?r:"",t=>{var u,f,w,R;const o=(f=(u=t.previewVoices)==null?void 0:u.map((A,he)=>{let se;if(A.previewAudio){const J=A.previewAudio,mn=J instanceof Uint8Array?J:Uint8Array.from(atob(J),gn=>gn.charCodeAt(0)),pn=new Blob([new Uint8Array(mn)],{type:"audio/wav"});se=URL.createObjectURL(pn)}return{id:A.voiceId||`voice-${he}-${Date.now()}`,name:`Voice ${he+1}`,audioUrl:se,previewText:A.previewText}}))!=null?f:[];if(Ie.current=!1,P(L.GENERATED_VOICE_CANDIDATES,I.TextVoiceDesign,{draftVoiceIds:((w=t.previewVoices)!=null?w:[]).map(A=>A.voiceId).filter(Boolean),candidateCount:o.length,promptMode:(R=tt.current)!=null?R:"",latencyMs:Te.current?Date.now()-Te.current:0,attemptNumber:Q.current}),!Ye.current){o.forEach(A=>{A.audioUrl&&URL.revokeObjectURL(A.audioUrl)});return}je.current.push(...o.map(A=>A.audioUrl).filter(Boolean)),Qe(o),ie(!1)},t=>{if(console.error("Failed to generate voices:",t),Ie.current=!0,Ge(t)){ie(!1);return}const o=Ti(t.message||"");if(P(L.GENERATE_VOICE_ERROR,I.TextVoiceDesign,{errorMessage:t.message||"Unknown error",isPreviewAudioErr:!!o,langCode:q,voiceDescription:_e.current}),Ei(t.message)){Ve({message:t.message,hint:Ci(_e.current)}),ie(!1);return}const u=Ke.current?"Please adjust your preview text and try again.":"Please try generating again.";ve(o?`${o} ${u}`:t.message||"Failed to generate voices. Please try again."),ie(!1)}),z=a.useCallback(t=>{const o=t!=null?t:Tt;gi(o,X("language"))||k("language",o,{shouldDirty:!0})},[X,k]);a.useEffect(()=>{M.current&&z(It(M.current))},[z]);const Ht=a.useCallback(t=>{M.current=t,B(o=>o&&null)},[]),Kt=a.useCallback(t=>{z(t?Mt(t):null)},[z]),at=a.useCallback(async t=>{var u;const o=pe(t.voiceDescription);if(c()){He(!0);try{const f=await nt({designPrompt:o,...Ct(t.language)});let w=si((u=f==null?void 0:f.canonicalPrompt)!=null?u:"");if(!w){ve("No voice profile was returned. Please try again.");return}if(ne.current){const R=pi(V!=null?V:[],t.language);R&&(w=li(w,R))}P(L.CLICKED_REVIEW_VOICE_PROFILE,I.TextVoiceDesign,{description:o,profile:w}),M.current=w,Ee(R=>({block:w,seq:R.seq+1})),B(null),we.current="profile",b("profile"),z(It(w))}catch(f){}finally{He(!1)}}},[nt,c,z,pe,b,V]);a.useLayoutEffect(()=>{var t;if(we.current!==h){if(we.current=h,B(null),h==="profile"){const o=(t=M.current)!=null&&t.trim()?M.current:Oe;M.current=o,Ee(u=>u.block===o?u:{block:o,seq:u.seq+1})}P(L.SELECTED_DESCRIPTION_MODE,I.TextVoiceDesign,{view:h})}},[h]);const st=a.useCallback(async t=>{var o;if(!(t!=null&&t.trim())||G)return ke(t);try{const u=await it({description:t,langCode:Rt(q)}),f=(o=u==null?void 0:u.previewText)==null?void 0:o.trim();return f?(P(L.GENERATED_SCRIPT,I.TextVoiceDesign,{text:f,isTooLong:f.length>Bn}),f):ke(t)}catch(u){return ke(t)}},[it,q,G]),ot=Si,Xt=Di,Yt=a.useCallback(t=>{P(L.CLICKED_SUGGESTION_VOICE_DESCRIPTION,I.TextVoiceDesign,{title:t.label,text:t.description}),B(null)},[]),Qt=a.useMemo(()=>ot.map(t=>e.jsx(Ot,{intent:"ghost","aria-label":t.label,onClick:()=>{P(L.CLICKED_SUGGESTION_VOICE_DESCRIPTION,I.TextVoiceDesign,{title:t.label,text:t.description}),k("voiceDescription",K(t.description).slice(0,$),{shouldValidate:!0})},children:t.label},t.label)),[ot,k]);a.useEffect(()=>{const t=H.current;if(!t)return;const o=()=>ae(null);return t.addEventListener("ended",o),()=>{t.removeEventListener("ended",o),t.pause(),t.src=""}},[]),a.useEffect(()=>{!_&&U.length>0&&requestAnimationFrame(()=>{var t;(t=et.current)==null||t.scrollIntoView({behavior:"smooth",block:"start"})})},[_,U]);const ge=a.useCallback(async(t,o,u,f)=>{var se,J;if(!c())return;ie(!0),Ve(null),Qe([]),Je(new Set),Se(!1),ae(null),(se=H.current)==null||se.pause(),H.current&&(H.current.src=""),je.current.forEach(URL.revokeObjectURL),je.current=[];const w=o===Le.DESIGN_PROMPT_MODE_VERBATIM?((J=u.previewScript)!=null?J:"").trim():"";Ke.current=!!w;const R=w||await st(t);i({type:"saveTextDesignData",textDesignData:{voiceDescription:u.voiceDescription,language:u.language,canonicalPrompt:f,previewScript:w||void 0}}),Q.current+=1;const A=Q.current===1?"first":Ie.current?"retry_after_error":"regenerate";tt.current=o,_e.current=t,P(L.CLICKED_GENERATE_VOICE,I.TextVoiceDesign,{voiceDescription:t,promptMode:o,language:u.language,previewText:R,scriptSource:w?"typed":"auto",attemptNumber:Q.current,retryReason:A});const he={designPrompt:t,designPromptMode:o,previewText:R,voiceDesignConfig:{numberOfSamples:3,generateDraftVoices:!0},...Ct(u.language)};Te.current=Date.now(),rt(he)},[i,st,rt,c]),Jt=a.useCallback(()=>{M.current=Oe,Ee(t=>({block:Oe,seq:t.seq+1})),B(null),z(null)},[z]),Zt=a.useCallback(async t=>{await at(t)},[at]),en=a.useMemo(()=>N(async t=>{await ge(pe(t.voiceDescription),Le.DESIGN_PROMPT_MODE_ASSISTED,t)}),[N,ge,pe]),tn=a.useCallback(async()=>{var u;const t=(u=M.current)!=null?u:"",o=oi(t);if(!o){B("Please fill in at least one attribute to generate a voice.");return}if(o.length<xe){B(`Please add more detail â the voice profile must be at least ${xe} characters.`);return}if(o.length>$){B(`The voice profile must be under ${$} characters. Please shorten some values.`);return}B(null),await ge(o,Le.DESIGN_PROMPT_MODE_VERBATIM,X(),t)},[ge,X]),nn=a.useCallback(t=>{const o=H.current;if(!o)return;if(Ce===t){o.pause(),o.src="",ae(null);return}const u=U.find(f=>f.id===t);u!=null&&u.audioUrl&&(P(L.PLAYED_DESIGN_CANDIDATE,I.TextVoiceDesign,{voiceId:t,candidateIndex:U.findIndex(f=>f.id===t),...Q.current>0&&{attemptNumber:Q.current}}),o.pause(),o.src=u.audioUrl,ae(t),o.play().catch(()=>{ae(null)}))},[Ce,U]),rn=t=>{Je(o=>{const u=new Set(o);if(u.has(t))u.delete(t);else{if(l!=null&&u.size>=l)return o;u.add(t)}return u}),Se(!1)},an=()=>{const t=U.filter(o=>re.has(o.id));if(t.length===0){Se(!0);return}P(L.CLICKED_SELECT_VOICE,I.TextVoiceDesign,{voices:t.map(o=>o.id)}),i({type:"selectVoices",selectedVoices:t,allGeneratedVoices:U})},sn=F?"One attribute per line â edit any value, add your own, or start from a preset.":void 0,on=y?e.
21jsx(Rn,{intent:"ghost","aria-label":"Voice design guide",href:y,target:"_blank",startIcon:e.jsx(le,{icon:Z.faArrowUpRightFromSquare}),size:"small",sx:{flexShrink:0},children:"Voice design guide"}):null,ln=e.jsxs(e.Fragment,{children:["Select one or more voices to publish to your"," ",e.jsxs(fe,{"aria-label":"Open Voice Library",to:`/workspaces/${r}/voice-library`,target:"_blank",rel:"noopener noreferrer",children:["Voice Library",e.jsx(le,{icon:Z.faArrowUpRightFromSquare,size:"sm",style:{verticalAlign:"middle",marginLeft:"0.125rem"}})]}),", or click the Generate Voice button above to regenerate the voices."]}),cn=e.jsxs(E,{component:"div",children:[e.jsxs(E,{component:"div",sx:{position:"relative"},children:[e.jsx(St,{name:"voiceDescription",control:D,rules:{required:"Voice description is required",minLength:{value:xe,message:`Description must be at least ${xe} characters`},pattern:{value:$n,message:"Voice description must contain only English (ASCII) characters"}},render:({field:t,fieldState:{error:o}})=>e.jsx(Be,{...t,onChange:u=>{t.onChange(K(u.target.value).slice(0,$))},error:!!o,multiline:!0,rows:8,placeholder:"Describe in English the voice you want to create (e.g., A middle-aged male voice with a clear British accent speaking at a steady pace and with a neutral tone.)",fullWidth:!0,variant:"outlined",className:"inworld-text-field",size:"small",slotProps:{htmlInput:{maxLength:$,"aria-label":"Voice description"}},sx:{"& .MuiInputBase-root.MuiOutlinedInput-root":{pb:"2rem"}}})}),e.jsx(_t,{control:D,name:"voiceDescription",maxLength:$})]}),e.jsx(O,{direction:"row",useFlexGap:!0,spacing:1,sx:{flexWrap:"wrap",mt:1},children:Qt}),te.voiceDescription&&e.jsx(j,{variant:"caption",color:"error",sx:{mt:"2px",ml:"12px"},children:te.voiceDescription.message}),e.jsxs(E,{component:"div",sx:{mt:"1rem"},children:[!g&&e.jsx(j,{variant:"body2",sx:{fontWeight:600,mb:"0.75rem"},children:"Language"}),e.jsx(Gn,{name:"language",label:g?"Language":"",control:D,value:q,onChangeValue:t=>{ne.current=!0,k("language",t,{shouldValidate:!0,shouldDirty:!0})},fallbackLanguages:m,isDisabled:!1,surface:"voiceDesign"})]})]}),un=e.jsxs(E,{component:"div",children:[e.jsx(xi,{initialBlock:qe.block,disabled:_,onBlockEdit:Ht,onDialectValue:Kt,suggestionChips:Xt,onChipApplied:Yt},qe.seq),Ze&&e.jsx(j,{variant:"caption",color:"error",sx:{mt:"0.75rem",display:"block"},children:Ze}),e.jsx(O,{direction:"row",sx:{justifyContent:"flex-end",mt:"0.5rem"},children:e.jsx(W,{intent:"secondary","aria-label":"Clear",size:"small",onClick:Jt,disabled:_,children:"Clear"})}),e.jsx(E,{component:"div",sx:{mt:"1rem"},children:e.jsx(vn,{label:"Text for Preview",renderOptionalLabel:!0,infoHelperProps:{tooltip:"Leave this empty and we write a script from the profile. Aim for text that reads in 5 to 45 seconds, roughly 50 to 500 characters in English."},children:e.jsxs(E,{component:"div",sx:{position:"relative"},children:[e.jsx(St,{name:"previewScript",control:D,render:({field:t})=>e.jsx(Be,{...t,onChange:o=>{t.onChange(o.target.value.slice(0,Re))},multiline:!0,rows:3,placeholder:"Enter the text you want the previewed voices to speak, or leave empty and we'll write it.",fullWidth:!0,variant:"outlined",className:"inworld-text-field",size:"small",disabled:_,slotProps:{htmlInput:{maxLength:Re,"aria-label":"Text for Preview"}},sx:{"& .MuiInputBase-root.MuiOutlinedInput-root":{pb:"2.5rem"}}})}),e.jsx(_t,{control:D,name:"previewScript",maxLength:Re})]})})})]}),dn=e.jsxs(Ue,{severity:"warning",sx:{svg:{color:t=>t.palette.warning.main},"&.MuiAlert-standard.MuiAlert-colorWarning":{borderColor:t=>t.palette.warning.main},mb:"1rem"},icon:e.jsx(le,{icon:Z.faCircleExclamation}),children:[e.jsx(Dt,{children:"Low balance"}),e.jsxs(j,{variant:"body2",sx:{fontWeight:400},children:["Some features are disabled due to low credit balance for the current workspace."," ",e.jsx(fe,{"aria-label":"Add credits",to:`/workspaces/${r}/settings/billing`,style:{color:"inherit"},children:"Add credits"})]})]});return e.jsxs("form",{className:"TextDescriptionForm",onSubmit:N(Zt),children:[e.jsxs(E,{component:"div",sx:{pb:4},children:[Wt&&dn,e.jsx(Me,{first:!0,title:F?"Voice profile":"Voice description",description:sn,titleAdornment:on,trailing:de?Y?null:e.jsx(Ft,{view:h,onChange:b}):e.jsxs(bn,{value:h,exclusive:!0,onChange:(t,o)=>{o!==null&&b(o)},size:"small",children:[e.jsx(oe,{title:"Describe the voice in your own words, and we build the full voice profile from it",children:e.jsx(bt,{"aria-label":"Freeform",value:"assisted",selected:h==="assisted",disableRipple:!0,children:"Freeform"})}),e.jsx(oe,{title:"Edit the voice profile directly for full control over the voice's nuances",children:e.jsx(bt,{"aria-label":"Structured",value:"profile",selected:h==="profile",disableRipple:!0,children:"Structured"})})]}),children:F?un:cn}),e.jsxs(O,{sx:{pt:{xs:2.5,sm:3}},children:[De&&e.jsxs(Ue,{className:"DesignPromptError",severity:"warning",icon:e.jsx(le,{icon:Z.faCircleExclamation}),onClose:()=>Ve(null),sx:{mb:"1rem",svg:{color:t=>t.palette.warning.main},"&.MuiAlert-standard.MuiAlert-colorWarning":{borderColor:t=>t.palette.warning.main}},children:[e.jsx(Dt,{children:"Nothing to build a voice from"}),e.jsx(j,{variant:"body2",sx:{fontWeight:400},children:"This description doesnât say how the voice should sound. Add vocal characteristics â things like gender, age, accent, tone, pitch, or pace."}),De.hint==="script"&&e.jsxs(j,{variant:"body2",sx:{fontWeight:400,mt:"0.5rem"},children:["That looks like the words you want spoken."," ",F?e.jsxs(e.Fragment,{children:["Describe the voice here and put the words themselves in"," ",e.jsx("strong",{children:"Text for Preview"})," below."]}):e.jsx(e.Fragment,{children:"This field describes how the voice sounds â for example âwarm, low-pitched narrator with a slight British accentâ."})]}),De.hint==="name"&&e.jsxs(j,{variant:"body2",sx:{fontWeight:400,mt:"0.5rem"},children:["That looks like a name. Voice design cannot copy a specific personâs voice â describe how they sound instead, or use"," ",e.jsx(fe,{"aria-label":"Instant Voice Clone",to:"../clone-voice",relative:"path",style:{color:"inherit"},children:"Instant Voice Clone"})," ","with audio you have the rights to."]})]}),e.jsx(oe,{title:s?"Voice capacity reached. Please upgrade your plan to create more voices.":"",children:e.jsx("span",{style:{display:"block"},children:F?e.jsx(W,{type:"button",fullWidth:!0,disabled:_||s,"aria-label":"Generate voice",loading:_,onClick:tn,children:_?"Generatingâ¦":"Generate voice"}):e.jsxs(O,{spacing:1.5,children:[e.jsx(W,{type:"button",fullWidth:!0,disabled:_||me||s,"aria-label":"Generate voice",loading:_,onClick:en,children:_?"Generatingâ¦":"Generate voice"}),e.jsx(oe,{title:"See and edit the structured profile we build from your description before generating",children:e.jsx("span",{style:{display:"block",width:"100%"},children:e.jsx(W,{intent:"secondary",type:"submit",fullWidth:!0,disabled:_||me||s,"aria-label":"Review structured profile",loading:me,children:me?"Preparing profileâ¦":"Review structured profile"})})})]})})})]}),!_&&U.length>0&&e.jsxs(E,{component:"div",ref:et,children:[e.jsx(Me,{title:"Voice previews",description:ln,children:e.jsxs(E,{component:"div",children:[e.jsx(Vt,{container:!0,spacing:1.5,children:U.map(t=>{var w;const o=re.has(t.id),u=Ce===t.id,f=l!=null&&!o&&re.size>=l;return e.jsx(Vt,{size:{xs:12,sm:6,md:4},children:e.jsx(oe,{title:f?e.jsxs(e.Fragment,{children:["Only ",l," custom voice",l===1?"":"s"," remaining on your plan."," ",e.jsx(fe,{"aria-label":"Upgrade plan",to:`/workspaces
21/${r}/settings/billing`,style:{color:"inherit"},onClick:()=>P(L.CLICKED_CUSTOM_VOICE_CAPACITY_UPGRADE,I.TextVoiceDesign,{remaining:l!=null?l:0}),children:"Upgrade"})," ","to unlock more."]}):"",children:e.jsxs(O,{direction:"row",spacing:1,"aria-label":`Select voice ${(w=t.name)!=null?w:t.id}`,onClick:()=>rn(t.id),sx:{alignItems:"center",p:"0.5rem 0.75rem",cursor:f?"not-allowed":"pointer",borderRadius:We.md,border:"1px solid",borderColor:o?"primary.main":"divider",backgroundColor:o?"action.selected":"background.paper",opacity:f?.5:1,"&:hover":{borderColor:f?"divider":yn,backgroundColor:o?"action.selected":f?"background.paper":"action.hover"},transition:"background-color 0.15s ease, border-color 0.15s ease"},children:[e.jsx(Lt,{size:"small",playingIcon:"stop",isPlaying:u,"aria-label":u?"Stop voice preview":"Play voice preview",onClick:R=>{R.stopPropagation(),nn(t.id)}}),e.jsx(j,{variant:"body2",sx:{fontWeight:o?600:400,flexGrow:1},children:t.name})]})})},t.id)})}),$t&&e.jsx(j,{variant:"caption",color:"error",sx:{mt:"0.75rem",display:"block"},children:"Please select at least one voice to continue"})]})}),e.jsx(O,{sx:{pt:{xs:2.5,sm:3}},children:e.jsx(W,{"aria-label":"Select voice",fullWidth:!0,onClick:an,children:re.size>1?`Select ${re.size} voices`:"Select voice"})})]})]}),e.jsx(Mn,{feature:"voice-design",openAsk:x,onDismiss:S})]})},At=n=>{const i=Math.floor(n/60),r=Math.floor(n%60);return`${i}:${r.toString().padStart(2,"0")}`},Ai=({voice:n,isActive:i,onPlay:r})=>{const s=a.useRef(null);s.current||(s.current=new Audio);const l=a.useRef(null),c=a.useRef(r);c.current=r;const[x,S]=a.useState(0),[C,T]=a.useState(0),[g,p]=a.useState(!1),[y,d]=a.useState(!1);a.useEffect(()=>{const m=s.current;if(!m)return;const D=()=>{p(!1),c.current(null)},N=()=>{T(m.duration||0)},k=()=>{T(m.duration||0)};return m.addEventListener("ended",D),m.addEventListener("loadedmetadata",N),m.addEventListener("durationchange",k),()=>{m.removeEventListener("ended",D),m.removeEventListener("loadedmetadata",N),m.removeEventListener("durationchange",k),m.pause(),m.src=""}},[]),a.useEffect(()=>{var m;!i&&g&&((m=s.current)==null||m.pause(),p(!1))},[i,g]),a.useEffect(()=>{const m=()=>{s.current&&S(s.current.currentTime),l.current=requestAnimationFrame(m)};return g&&(l.current=requestAnimationFrame(m)),()=>{l.current&&cancelAnimationFrame(l.current)}},[g]);const ee=a.useCallback(async()=>{const m=s.current;if(m)if(m.paused){n.audioUrl&&m.src!==n.audioUrl&&(d(!0),m.src=n.audioUrl,d(!1));try{r(n.id),await m.play(),p(!0)}catch(D){console.error("Play failed:",D),p(!1),r(null)}}else m.pause(),p(!1),r(null)},[n.audioUrl,n.id,r]),G=a.useCallback((m,D)=>{const N=D||0;s.current&&(s.current.currentTime=N),S(N)},[]);return e.jsxs(O,{direction:"row",spacing:1,sx:{alignItems:"center",p:"0.5rem 0.75rem",borderRadius:We.md,border:"1px solid",borderColor:"divider",backgroundColor:"background.paper"},children:[e.jsx(Lt,{size:"small",playingIcon:"stop",isPlaying:g,"aria-label":g?"Stop voice preview":"Play voice preview",onClick:ee}),e.jsx(j,{variant:"body2",sx:{fontWeight:600,flexShrink:0,mr:3},children:n.name}),e.jsx(j,{variant:"caption",sx:{fontFamily:yt.mono,flexShrink:0,minWidth:"2rem"},children:At(x)}),e.jsx(Jn,{"aria-label":"audio seek",size:"small",value:x,min:0,max:C||0,step:1e-4,sx:{flexGrow:1,"& .MuiSlider-thumb":{transition:"none"},"& .MuiSlider-track":{transition:"none"}},onChange:G,disabled:y||!C}),e.jsx(j,{variant:"caption",sx:{fontFamily:yt.mono,flexShrink:0,minWidth:"2rem"},children:At(C)})]})},Pi={displayName:"Name",language:"Language",tags:"Tags",description:"Description"},Li=({errors:n,voiceNames:i,onErrorClick:r})=>{const s=n.voices;if(!(s!=null&&s.length))return null;const l=[];for(let c=0;c<s.length;c++){const x=s[c];x&&Object.keys(x).forEach(S=>{var p,y,d;const C=x[S];if(!C)return;const T=i.length>1?`${(p=i[c])!=null?p:`Voice ${c+1}`} â `:"",g=(y=C.message)!=null?y:"Invalid";l.push({label:`${T}${(d=Pi[S])!=null?d:S}: ${g}`,path:`voices.${c}.${S}`})})}return l.length===0?null:e.jsxs(Ue,{severity:"error",sx:{mt:"1rem"},children:[e.jsx(j,{variant:"body2",sx:{mb:.5},children:"Please fix the following errors:"}),e.jsx(E,{component:"ul",sx:{m:0,pl:"1.25rem"},children:l.map(({label:c,path:x})=>e.jsx(E,{component:"li","aria-label":`Go to error: ${c}`,sx:{cursor:"pointer","&:hover":{textDecoration:"underline"}},onClick:()=>r(x),children:e.jsx(j,{variant:"body2",children:c})},x))})]})},ki=({snapshot:n,send:i,tryInPlayground:r})=>{var te,q,de,ne;const{workspace:s}
21=be(),l=wn(),[c,x]=a.useState(!1),[S,C]=a.useState(""),[T,g]=a.useState(null),p=n.context.selectedGeneratedVoices,y=(q=(te=n.context.textDesignData)==null?void 0:te.voiceDescription)!=null?q:"",d=(ne=(de=n.context.textDesignData)==null?void 0:de.language)!=null?ne:ue.EN_US,{mutateAsync:ee}=kn(s!=null?s:"",void 0,V=>{if(Ge(V))return;const v=V.message||"Failed to publish voice. Please try again.";C(v),ve(v)}),{control:G,handleSubmit:m,setFocus:D,formState:{errors:N}}=Nt({defaultValues:{voices:p.map(()=>({displayName:"",language:d,tags:[],description:y}))},mode:"onTouched"}),{fields:k}=qn({control:G,name:"voices"}),X=async V=>{var v,h;C(""),x(!0);try{await Promise.all(p.map((b,Y)=>{const F=V.voices[Y];return F?ee({name:`workspaces/${s}/voices/${b.id}`,voiceId:b.id,displayName:F.displayName,description:F.description,tags:F.tags,langCode:Rt(F.language)}):Promise.resolve()})),P(L.CLICKED_SAVE_VOICE,I.TextVoiceDesign,{voices:p.map(b=>b.id)}),Qn(),await jn(()=>l.fetchQuery(["voices_v1",s],()=>Tn(s!=null?s:"")),p.map(b=>b.id)),r==null||r((h=(v=p[0])==null?void 0:v.id)!=null?h:"")}catch(b){}finally{x(!1)}},ye=a.useCallback(V=>{const v=V.voices;if(v!=null&&v.length)for(let h=0;h<v.length;h++){const b=v[h];if(b){const Y=Object.keys(b)[0];if(Y){D(`voices.${h}.${Y}`);return}}}},[D]);return e.jsxs("form",{noValidate:!0,className:"TextSaveVoice",onSubmit:m(X,ye),children:[S&&e.jsx(Hn,{severity:"error",sx:{mb:2},children:S}),e.jsxs(E,{component:"div",sx:{pb:4},children:[k.map((V,v)=>{const h=p[v];return h?e.jsxs(Me,{first:v===0,title:h.name,children:[e.jsx(Ai,{voice:h,isActive:T===h.id,onPlay:g}),e.jsxs(O,{spacing:2,direction:{xs:"column",md:"row"},children:[e.jsx(Et,{name:`voices.${v}.displayName`,label:"Name",control:G,controllerProps:{rules:{required:"Display name is required",maxLength:{value:Ne,message:`Display name must not exceed ${Ne} characters`},validate:b=>(b==null?void 0:b.trim())!==""||"Display name cannot be empty"}},isDisabled:!1,textFieldProps:{slotProps:{htmlInput:{maxLength:Ne}}}}),e.jsx(Wn,{name:`voices.${v}.tags`,label:"Tags (optional)",control:G,isDisabled:!1})]}),e.jsx(Et,{name:`voices.${v}.description`,label:"Description (optional)",control:G,controllerProps:{rules:{maxLength:{value:Fe,message:`Description must not exceed ${Fe} characters`}}},isDisabled:!1,textFieldProps:{multiline:!0,rows:3,slotProps:{htmlInput:{maxLength:Fe}}}})]},V.id):null}),e.jsx(Li,{errors:N,voiceNames:p.map(V=>V.name),onErrorClick:D}),e.jsxs(O,{direction:{xs:"column",md:"row"},spacing:1,sx:{justifyContent:"space-between",pt:{xs:2.5,sm:3}},children:[e.jsx(W,{intent:"secondary","aria-label":"Back",disabled:c,onClick:()=>{P(L.CLICKED_VOICE_DESIGN_BACK,I.TextVoiceDesign),i({type:"back"})},children:"Back"}),e.jsx(W,{"aria-label":"Save voice",loading:c,type:"submit",disabled:c,sx:{minWidth:"10rem"},children:c?"Publishingâ¦":p.length>1?`Save ${p.length} Voices`:"Save Voice"})]})]})]})};var ce=(n=>(n.descriptionForm="descriptionForm",n.saveVoice="saveVoice",n))(ce||{});const Ri=Sn({}).createMachine({id:"voiceDesign",initial:"descriptionForm",context:{textDesignData:null,generatedVoices:[],selectedGeneratedVoices:[],lowBalance:!1},states:{descriptionForm:{meta:{description:"Text design: describe voice, generate clips, and select voices"},on:{saveTextDesignData:{actions:Pe({textDesignData:({event:n})=>n==null?void 0:n.textDesignData})},selectVoices:{actions:Pe({selectedGeneratedVoices:({event:n})=>{var i;return(i=n==null?void 0:n.selectedVoices)!=null?i:[]},generatedVoices:({event:n})=>{var i;return(i=n==null?void 0:n.allGeneratedVoices)!=null?i:[]}}),target:"saveVoice"},setLowBalance:{actions:Pe({lowBalance:()=>!0})}}},saveVoice:{meta:{description:"Text design: name and save the selected voices"},on:{back:{target:"descriptionForm"}}}}}),Ni=new Map([[ce.descriptionForm,_i],[ce.saveVoice,ki]]),Fi=()=>{const{workspace:n}=be(),i=En(),[r,s]=Dn(Ri),l=r.value,[c,x]=a.useState("assisted"),S=l===ce.descriptionForm,C=a.useRef(r.context.generatedVoices);C.current=r.context.generatedVoices,a.useEffect(()=>()=>{C.current.forEach(p=>{var y;(y=p.audioUrl)!=null&&y.startsWith("blob:")&&URL.revokeObjectURL(p.audioUrl)})},[]);const T=p=>
21{i(`/workspaces/${n}/tts-playground`,{state:{selectedVoiceId:p}})},g=a.useMemo(()=>Ni.get(l),[l]);return g?e.jsx(Kn,{EnhancedPageHeaderProps:{sx:{"& .page-header-column:first-child":{width:"unset"},[wt.breakpoints.only("sm")]:{"& > div":{flexDirection:"row"},"& .page-header-column:last-child":{justifyContent:"flex-end"}},[wt.breakpoints.only("xs")]:{"& > div":{flexDirection:"row","& .page-header-column:first-child":{justifyContent:"flex-start"},"& .page-header-column:last-child":{justifyContent:"flex-end"}}}},primaryAction:S?e.jsx(Ft,{view:c,onChange:x,sx:{display:{xs:"inline-flex",sm:"none"}}}):void 0,breadcrumbs:[{label:"Voices",href:`/workspaces/${n}/voice-library`},{label:"Create Voice",href:`/workspaces/${n}/voice-library/create-voice`},{label:"Voice Design"}]},children:e.jsxs(E,{component:"div",sx:{maxWidth:Cn.reading,margin:"auto",width:"100%",position:"relative",minHeight:"60vh"},children:[l===ce.descriptionForm&&e.jsx(E,{sx:{mb:2},children:e.jsx(Vn,{workspace:n,component:I.TextVoiceDesign,maxWidth:"100%"})}),e.jsx(Zn,{mode:"wait",children:e.jsx(ei.div,{initial:{y:10,opacity:0},animate:{y:0,opacity:1},exit:{y:-10,opacity:0},transition:{duration:.2},children:e.jsx(Vi,{view:c,setView:x,children:e.jsx(g,{snapshot:r,send:s,onExit:()=>i(-1),tryInPlayground:T})})},l)}),e.jsx(In,{workspace:n,component:I.TextVoiceDesign})]})}):null},pr=()=>{const{workspace:n}=be();return e.jsx(e.Fragment,{children:n?e.jsx(Fi,{},n):e.jsx(E,{component:"div",sx:{p:4},children:e.jsx(j,{variant:"body1",sx:{color:"text.secondary"},children:"Please select a workspace to continue"})})})};export{pr as TextVoiceDesignPage};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.