File size: 39,928 Bytes
1433b16
 
 
1
2
3
4
var GradioClient=(()=>{var ce=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var st=(e,t)=>()=>(e&&(t=e(e=0)),t);var Se=(e,t)=>{for(var n in t)ce(e,n,{get:t[n],enumerable:!0})},it=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tt(t))!nt.call(e,i)&&i!==n&&ce(e,i,{get:()=>t[i],enumerable:!(s=et(t,i))||s.enumerable});return e};var ot=e=>it(ce({},"__esModule",{value:!0}),e);var le={};Se(le,{default:()=>at});var at,ue=st(()=>{at={}});var hn={};Se(hn,{Client:()=>G});var rt=Object.defineProperty,Ne=e=>{throw TypeError(e)},ct=(e,t,n)=>t in e?rt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u=(e,t,n)=>ct(e,typeof t!="symbol"?t+"":t,n),Pe=(e,t,n)=>t.has(e)||Ne("Cannot "+n),Z=(e,t,n)=>(Pe(e,t,"read from private field"),n?n.call(e):t.get(e)),lt=(e,t,n)=>t.has(e)?Ne("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),ut=(e,t,n,s)=>(Pe(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n),pe=new Intl.Collator(0,{numeric:1}).compare;function ze(e,t,n){return e=e.split("."),t=t.split("."),pe(e[0],t[0])||pe(e[1],t[1])||(t[2]=t.slice(2).join("."),n=/[.-]/.test(e[2]=e.slice(2).join(".")),n==/[.-]/.test(t[2])?pe(e[2],t[2]):n?-1:1)}var pt="host",Ae="queue/data",dt="queue/join",xe="upload",ht="login",X="config",ft="info",_t="runtime",gt="sleeptime",mt="heartbeat",wt="component_server",yt="reset",vt="cancel",bt="app_id",$t="https://gradio-space-api-fetcher-v2.hf.space/api",Be="This application is currently busy. Please try again. ",W="Connection errored out. ",L="Could not resolve app config. ",kt="Could not get space status. ",Et="Could not get API info. ",we="Space metadata could not be loaded. ",St="Invalid URL. A full URL path is required.",xt="Not authorized to access this space. ",Le="Invalid credentials. Could not login. ",jt="Login credentials are required to access this space.",Ct="File system access is only available in Node.js environments",Ue="Root URL not found in client config",qt="Error uploading file";function Dt(e,t,n){return t.startsWith("http://")||t.startsWith("https://")?n?e:t:e+t}async function je(e,t,n){try{return(await(await fetch(`https://huggingface.co/api/spaces/${e}/jwt`,{headers:{Authorization:`Bearer ${t}`,...n?{Cookie:n}:{}}})).json()).token||!1}catch{return!1}}function Ot(e){let t={};return e.forEach(({api_name:n,id:s})=>{n&&(t[n]=s)}),t}async function Tt(e){let t=this.options.hf_token?{Authorization:`Bearer ${this.options.hf_token}`}:{};if(t["Content-Type"]="application/json",typeof window<"u"&&window.gradio_config&&location.origin!=="http://localhost:9876"){if(window.gradio_config.current_page&&(e=e.substring(0,e.lastIndexOf("/"))),window.gradio_config.dev_mode){let n=fe(e,this.deep_link?X+"?deep_link="+this.deep_link:X),s=await this.fetch(n,{headers:t,credentials:"include"}),i=await Ce(s,e,!!this.options.auth);window.gradio_config={...i,current_page:window.gradio_config.current_page}}return window.gradio_config.root=e,{...window.gradio_config}}else if(e){let n=fe(e,this.deep_link?X+"?deep_link="+this.deep_link:X),s=await this.fetch(n,{headers:t,credentials:"include"});return Ce(s,e,!!this.options.auth)}throw new Error(L)}async function Ce(e,t,n){var s,i;if(e?.status===401&&!n){let a=await e.json(),o=(s=a?.detail)==null?void 0:s.auth_message;throw new Error(o||jt)}else if(e?.status===401&&n)throw new Error(Le);if(e?.status===200){let a=await e.json();return a.root=t,(i=a.dependencies)==null||i.forEach((o,r)=>{o.id===void 0&&(o.id=r)}),a}else if(e?.status===401)throw new Error(xt);throw new Error(L)}async function Nt(){let{http_protocol:e,host:t}=await V(this.app_reference,this.options.hf_token);try{if(this.options.auth){let n=await Ie(e,t,this.options.auth,this.fetch,this.options.hf_token);n&&this.set_cookies(n)}}catch(n){throw Error(n.message)}}async function Ie(e,t,n,s,i){let a=new FormData;a.append("username",n?.[0]),a.append("password",n?.[1]);let o={};i&&(o.Authorization=`Bearer ${i}`);let r=await s(`${e}//${t}/${ht}`,{headers:o,method:"POST",body:a,credentials:"include"});if(r.status===200)return r.headers.get("set-cookie");throw r.status===401?new Error(Le):new Error(we)}function de(e){if(e.startsWith("http")){let{protocol:t,host:n,pathname:s}=new URL(e);return{ws_protocol:t==="https:"?"wss":"ws",http_protocol:t,host:n+(s!=="/"?s:"")}}return{ws_protocol:"wss",http_protocol:"https:",host:new URL(e).host}}var Re=e=>{let t=[];return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach(n=>{let[s,i]=n.split(";")[0].split("=");s&&i&&t.push(`${s.trim()}=${i.trim()}`)}),t},ye=/^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/,Pt=/.*hf\.space\/{0,1}.*$/;async function V(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);let s=e.trim().replace(/\/$/,"");if(ye.test(s))try{let i=(await(await fetch(`https://huggingface.co/api/spaces/${s}/${pt}`,{headers:n})).json()).host;return{space_id:e,...de(i)}}catch{throw new Error(we)}if(Pt.test(s)){let{ws_protocol:i,http_protocol:a,host:o}=de(s);return{space_id:o.split("/")[0].replace(".hf.space",""),ws_protocol:i,http_protocol:a,host:o}}return{space_id:!1,...de(s)}}var fe=(...e)=>{try{return e.reduce((t,n)=>(t=t.replace(/\/+$/,""),n=n.replace(/^\/+/,""),new URL(n,t+"/").toString()))}catch{throw new Error(St)}};function zt(e,t,n){let s={named_endpoints:{},unnamed_endpoints:{}};return Object.keys(e).forEach(i=>{(i==="named_endpoints"||i==="unnamed_endpoints")&&(s[i]={},Object.entries(e[i]).forEach(([a,{parameters:o,returns:r}])=>{var l,_,m,p;let g=((l=t.dependencies.find(c=>c.api_name===a||c.api_name===a.replace("/","")))==null?void 0:l.id)||n[a.replace("/","")]||-1,C=g!==-1?(_=t.dependencies.find(c=>c.id==g))==null?void 0:_.types:{generator:!1,cancel:!1};if(g!==-1&&((p=(m=t.dependencies.find(c=>c.id==g))==null?void 0:m.inputs)==null?void 0:p.length)!==o.length){let c=t.dependencies.find(f=>f.id==g).inputs.map(f=>{var D;return(D=t.components.find(P=>P.id===f))==null?void 0:D.type});try{c.forEach((f,D)=>{if(f==="state"){let P={component:"state",example:null,parameter_default:null,parameter_has_default:!0,parameter_name:null,hidden:!0};o.splice(D,0,P)}})}catch(f){console.error(f)}}let U=(c,f,D,P)=>({...c,description:Bt(c?.type,D),type:At(c?.type,f,D,P)||""});s[i][a]={parameters:o.map(c=>U(c,c?.component,c?.serializer,"parameter")),returns:r.map(c=>U(c,c?.component,c?.serializer,"return")),type:C}}))}),s}function At(e,t,n,s){if(t==="Api")return e.type;switch(e?.type){case"string":return"string";case"boolean":return"boolean";case"number":return"number"}if(n==="JSONSerializable"||n==="StringSerializable")return"any";if(n==="ListStringSerializable")return"string[]";if(t==="Image")return s==="parameter"?"Blob | File | Buffer":"string";if(n==="FileSerializable")return e?.type==="array"?s==="parameter"?"(Blob | File | Buffer)[]":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]":s==="parameter"?"Blob | File | Buffer":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";if(n==="GallerySerializable")return s==="parameter"?"[(Blob | File | Buffer), (string | null)][]":"[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]"}function Bt(e,t){return t==="GallerySerializable"?"array of [file, label] tuples":t==="ListStringSerializable"?"array of strings":t==="FileSerializable"?"array of files or single file":e?.description}function he(e,t){switch(e.msg){case"send_data":return{type:"data"};case"send_hash":return{type:"hash"};case"queue_full":return{type:"update",status:{queue:!0,message:Be,stage:"error",code:e.code,success:e.success}};case"heartbeat":return{type:"heartbeat"};case"unexpected_error":return{type:"unexpected_error",status:{queue:!0,message:e.message,session_not_found:e.session_not_found,stage:"error",success:!1}};case"broken_connection":return{type:"broken_connection",status:{queue:!0,message:e.message,stage:"error",success:!1}};case"estimation":return{type:"update",status:{queue:!0,stage:t||"pending",code:e.code,size:e.queue_size,position:e.rank,eta:e.rank_eta,success:e.success}};case"progress":return{type:"update",status:{queue:!0,stage:"pending",code:e.code,progress_data:e.progress_data,success:e.success}};case"log":return{type:"log",data:e};case"process_generating":return{type:"generating",status:{queue:!0,message:e.success?null:e.output.error,stage:e.success?"generating":"error",code:e.code,progress_data:e.progress_data,eta:e.average_duration,changed_state_ids:e.success?e.output.changed_state_ids:void 0},data:e.success?e.output:null};case"process_streaming":return{type:"streaming",status:{queue:!0,message:e.output.error,stage:"streaming",time_limit:e.time_limit,code:e.code,progress_data:e.progress_data,eta:e.eta},data:e.output};case"process_completed":return"error"in e.output?{type:"update",status:{queue:!0,title:e.output.title,message:e.output.error,visible:e.output.visible,duration:e.output.duration,stage:"error",code:e.code,success:e.success}}:{type:"complete",status:{queue:!0,message:e.success?void 0:e.output.error,stage:e.success?"complete":"error",code:e.code,progress_data:e.progress_data,changed_state_ids:e.success?e.output.changed_state_ids:void 0},data:e.success?e.output:null};case"process_starts":return{type:"update",status:{queue:!0,stage:"pending",code:e.code,size:e.rank,position:0,success:e.success,eta:e.eta},original_msg:"process_starts"}}return{type:"none",status:{stage:"error",queue:!0}}}var Lt=(e=[],t)=>{let n=t?t.parameters:[];if(Array.isArray(e))return t&&n.length>0&&e.length>n.length&&console.warn("Too many arguments provided for the endpoint."),e;let s=[],i=Object.keys(e);return n.forEach((a,o)=>{if(e.hasOwnProperty(a.parameter_name))s[o]=e[a.parameter_name];else if(a.parameter_has_default)s[o]=a.parameter_default;else throw new Error(`No value provided for required parameter: ${a.parameter_name}`)}),i.forEach(a=>{if(!n.some(o=>o.parameter_name===a))throw new Error(`Parameter \`${a}\` is not a valid keyword argument. Please refer to the API for usage.`)}),s.forEach((a,o)=>{if(a===void 0&&!n[o].parameter_has_default)throw new Error(`No value provided for required parameter: ${n[o].parameter_name}`)}),s};async function Ut(){if(this.api_info)return this.api_info;let{hf_token:e}=this.options,{config:t}=this,n={"Content-Type":"application/json"};if(e&&(n.Authorization=`Bearer ${e}`),!!t)try{let s,i;if(typeof window<"u"&&window.gradio_api_info)i=window.gradio_api_info;else{if(ze(t?.version||"2.0.0","3.30")<0)s=await this.fetch($t,{method:"POST",body:JSON.stringify({serialize:!1,config:JSON.stringify(t)}),headers:n,credentials:"include"});else{let a=fe(t.root,this.api_prefix,ft);s=await this.fetch(a,{headers:n,credentials:"include"})}if(!s.ok)throw new Error(W);i=await s.json()}return"api"in i&&(i=i.api),i.named_endpoints["/predict"]&&!i.unnamed_endpoints[0]&&(i.unnamed_endpoints[0]=i.named_endpoints["/predict"]),zt(i,t,this.api_map)}catch(s){throw new Error("Could not get API info. "+s.message)}}async function It(e,t,n){var s;let i={};(s=this==null?void 0:this.options)!=null&&s.hf_token&&(i.Authorization=`Bearer ${this.options.hf_token}`);let a=1e3,o=[],r;for(let l=0;l<t.length;l+=a){let _=t.slice(l,l+a),m=new FormData;_.forEach(g=>{m.append("files",g)});try{let g=n?`${e}${this.api_prefix}/${xe}?upload_id=${n}`:`${e}${this.api_prefix}/${xe}`;r=await this.fetch(g,{method:"POST",body:m,headers:i,credentials:"include"})}catch(g){throw new Error(W+g.message)}if(!r.ok){let g=await r.text();return{error:`HTTP ${r.status}: ${g}`}}let p=await r.json();p&&o.push(...p)}return{files:o}}async function Rt(e,t,n,s){let i=(Array.isArray(e)?e:[e]).map(o=>o.blob),a=i.filter(o=>o.size>(s??1/0));if(a.length)throw new Error(`File size exceeds the maximum allowed size of ${s} bytes: ${a.map(o=>o.name).join(", ")}`);return await Promise.all(await this.upload_files(t,i,n).then(async o=>{if(o.error)throw new Error(o.error);return o.files?o.files.map((r,l)=>new Q({...e[l],path:r,url:`${t}${this.api_prefix}/file=${r}`})):[]}))}var Q=class{constructor({path:t,url:n,orig_name:s,size:i,blob:a,is_stream:o,mime_type:r,alt_text:l,b64:_}){u(this,"path"),u(this,"url"),u(this,"orig_name"),u(this,"size"),u(this,"blob"),u(this,"is_stream"),u(this,"mime_type"),u(this,"alt_text"),u(this,"b64"),u(this,"meta",{_type:"gradio.FileData"}),this.path=t,this.url=n,this.orig_name=s,this.size=i,this.blob=n?void 0:a,this.is_stream=o,this.mime_type=r,this.alt_text=l,this.b64=_}},_e=class{constructor(t,n){u(this,"type"),u(this,"command"),u(this,"meta"),u(this,"fileData"),this.type="command",this.command=t,this.meta=n}},_n=typeof process<"u"&&process.versions&&process.versions.node;function qe(e,t,n){for(;n.length>1;){let i=n.shift();if(typeof i=="string"||typeof i=="number")e=e[i];else throw new Error("Invalid key type")}let s=n.shift();if(typeof s=="string"||typeof s=="number")e[s]=t;else throw new Error("Invalid key type")}async function ge(e,t=void 0,n=[],s=!1,i=void 0){if(Array.isArray(e)){let a=[];return await Promise.all(e.map(async(o,r)=>{var l;let _=n.slice();_.push(String(r));let m=await ge(e[r],s?((l=i?.parameters[r])==null?void 0:l.component)||void 0:t,_,!1,i);a=a.concat(m)})),a}else{if(globalThis.Buffer&&e instanceof globalThis.Buffer||e instanceof Blob)return[{path:n,blob:new Blob([e]),type:t}];if(typeof e=="object"&&e!==null){let a=[];for(let o of Object.keys(e)){let r=[...n,o],l=e[o];a=a.concat(await ge(l,void 0,r,!1,i))}return a}}return[]}function Ft(e,t){var n,s;let i=(s=(n=t?.dependencies)==null?void 0:n.find(a=>a.id==e))==null?void 0:s.queue;return i!=null?!i:!t.enable_queue}function Jt(e,t){return new Promise((n,s)=>{let i=new MessageChannel;i.port1.onmessage=({data:a})=>{i.port1.close(),n(a)},window.parent.postMessage(e,t,[i.port2])})}function K(e,t,n,s,i=!1){if(s==="input"&&!i)throw new Error("Invalid code path. Cannot skip state inputs for input.");if(s==="output"&&i)return e;let a=[],o=0,r=s==="input"?t.inputs:t.outputs;for(let l=0;l<r.length;l++){let _=r[l],m=n.find(p=>p.id===_);if(m?.type==="state"){if(i)if(e.length===r.length){let p=e[o];a.push(p),o++}else a.push(null);else{o++;continue}continue}else{let p=e[o];a.push(p),o++}}return a}async function Wt(e,t,n){let s=this;await Gt(s,t);let i=await ge(t,void 0,[],!0,n);return(await Promise.all(i.map(async({path:a,blob:o,type:r})=>{if(!o)return{path:a,type:r};let l=await s.upload_files(e,[o]),_=l.files&&l.files[0];return{path:a,file_url:_,type:r,name:typeof File<"u"&&o instanceof File?o?.name:void 0}}))).forEach(({path:a,file_url:o,type:r,name:l})=>{if(r==="Gallery")qe(t,o,a);else if(o){let _=new Q({path:o,orig_name:l});qe(t,_,a)}}),t}async function Gt(e,t){var n,s;if(!((n=e.config)!=null&&n.root||(s=e.config)!=null&&s.root_url))throw new Error(Ue);await Fe(e,t)}async function Fe(e,t,n=[]){for(let s in t)t[s]instanceof _e?await Mt(e,t,s):typeof t[s]=="object"&&t[s]!==null&&await Fe(e,t[s],[...n,s])}async function Mt(e,t,n){var s,i;let a=t[n],o=((s=e.config)==null?void 0:s.root)||((i=e.config)==null?void 0:i.root_url);if(!o)throw new Error(Ue);try{let r,l;if(typeof process<"u"&&process.versions&&process.versions.node){let g=await Promise.resolve().then(()=>(ue(),le));l=(await Promise.resolve().then(()=>(ue(),le))).resolve(process.cwd(),a.meta.path),r=await g.readFile(l)}else throw new Error(Ct);let _=new Blob([r],{type:"application/octet-stream"}),m=await e.upload_files(o,[_]),p=m.files&&m.files[0];if(p){let g=new Q({path:p,orig_name:a.meta.name||""});t[n]=g}}catch(r){console.error(qt,r)}}async function Ht(e,t,n){let s={"Content-Type":"application/json"};this.options.hf_token&&(s.Authorization=`Bearer ${this.options.hf_token}`);try{var i=await this.fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...s,...n},credentials:"include"})}catch{return[{error:W},500]}let a,o;try{a=await i.json(),o=i.status}catch(r){a={error:`Could not parse server response: ${r}`},o=500}return[a,o]}async function Zt(e,t={}){let n=!1,s=!1;if(!this.config)throw new Error("Could not resolve app config");if(typeof e=="number")this.config.dependencies.find(i=>i.id==e);else{let i=e.replace(/^\//,"");this.config.dependencies.find(a=>a.id==this.api_map[i])}return new Promise(async(i,a)=>{let o=this.submit(e,t,null,null,!0),r;for await(let l of o)l.type==="data"&&(s&&i(r),n=!0,r=l),l.type==="status"&&(l.stage==="error"&&a(l),l.stage==="complete"&&(s=!0,n&&i(r)))})}async function Y(e,t,n){let s=t==="subdomain"?`https://huggingface.co/api/spaces/by-subdomain/${e}`:`https://huggingface.co/api/spaces/${e}`,i,a;try{if(i=await fetch(s),a=i.status,a!==200)throw new Error;i=await i.json()}catch{n({status:"error",load_status:"error",message:kt,detail:"NOT_FOUND"});return}if(!i||a!==200)return;let{runtime:{stage:o},id:r}=i;switch(o){case"STOPPED":case"SLEEPING":n({status:"sleeping",load_status:"pending",message:"Space is asleep. Waking it up...",detail:o}),setTimeout(()=>{Y(e,t,n)},1e3);break;case"PAUSED":n({status:"paused",load_status:"error",message:"This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",detail:o,discussions_enabled:await De(r)});break;case"RUNNING":case"RUNNING_BUILDING":n({status:"running",load_status:"complete",message:"Space is running.",detail:o});break;case"BUILDING":n({status:"building",load_status:"pending",message:"Space is building...",detail:o}),setTimeout(()=>{Y(e,t,n)},1e3);break;case"APP_STARTING":n({status:"starting",load_status:"pending",message:"Space is starting...",detail:o}),setTimeout(()=>{Y(e,t,n)},1e3);break;default:n({status:"space_error",load_status:"error",message:"This space is experiencing an issue.",detail:o,discussions_enabled:await De(r)});break}}var Je=async(e,t)=>{let n=0,s=12,i=5e3;return new Promise(a=>{Y(e,ye.test(e)?"space_name":"subdomain",o=>{t(o),o.status==="running"||o.status==="error"||o.status==="paused"||o.status==="space_error"?a():(o.status==="sleeping"||o.status==="building")&&(n<s?(n++,setTimeout(()=>{Je(e,t).then(a)},i)):a())})})},Kt=/^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;async function De(e){try{let t=await fetch(`https://huggingface.co/api/spaces/${e}/discussions`,{method:"HEAD"}),n=t.headers.get("x-error-message");return!(!t.ok||n&&Kt.test(n))}catch{return!1}}async function Yt(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);try{let s=await fetch(`https://huggingface.co/api/spaces/${e}/${_t}`,{headers:n});if(s.status!==200)throw new Error("Space hardware could not be obtained.");let{hardware:i}=await s.json();return i.current}catch(s){throw new Error(s.message)}}async function Qt(e,t,n){let s={};n&&(s.Authorization=`Bearer ${n}`);let i={seconds:t};try{let a=await fetch(`https://huggingface.co/api/spaces/${e}/${gt}`,{method:"POST",headers:{"Content-Type":"application/json",...s},body:JSON.stringify(i)});if(a.status!==200)throw new Error("Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges.");return await a.json()}catch(a){throw new Error(a.message)}}var Oe=["cpu-basic","cpu-upgrade","cpu-xl","t4-small","t4-medium","a10g-small","a10g-large","a10g-largex2","a10g-largex4","a100-large","zero-a10g","h100","h100x8"];async function Xt(e,t){let{hf_token:n,private:s,hardware:i,timeout:a,auth:o}=t;if(i&&!Oe.includes(i))throw new Error(`Invalid hardware type provided. Valid types are: ${Oe.map(f=>`"${f}"`).join(",")}.`);let{http_protocol:r,host:l}=await V(e,n),_=null;if(o){let f=await Ie(r,l,o,fetch);f&&(_=Re(f))}let m={Authorization:`Bearer ${n}`,"Content-Type":"application/json",..._?{Cookie:_.join("; ")}:{}},p=(await(await fetch("https://huggingface.co/api/whoami-v2",{headers:m})).json()).name,g=e.split("/")[1],C={repository:`${p}/${g}`};s&&(C.private=!0);let U;try{i||(U=await Yt(e,n))}catch(f){throw Error(we+f.message)}let c=i||U||"cpu-basic";C.hardware=c;try{let f=await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`,{method:"POST",headers:m,body:JSON.stringify(C)});if(f.status===409)try{return await G.connect(`${p}/${g}`,t)}catch(P){throw console.error("Failed to connect Client instance:",P),P}else if(f.status!==200)throw new Error(f.statusText);let D=await f.json();return await Qt(`${p}/${g}`,a||300,n),await G.connect(Vt(D.url),t)}catch(f){throw new Error(f)}}function Vt(e){let t=/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/,n=e.match(t);if(n)return n[1]}var B,me=class extends TransformStream{constructor(t={allowCR:!1}){super({transform:(n,s)=>{for(n=Z(this,B)+n;;){let i=n.indexOf(`
`),a=t.allowCR?n.indexOf("\r"):-1;if(a!==-1&&a!==n.length-1&&(i===-1||i-1>a)){s.enqueue(n.slice(0,a)),n=n.slice(a+1);continue}if(i===-1)break;let o=n[i-1]==="\r"?i-1:i;s.enqueue(n.slice(0,o)),n=n.slice(i+1)}ut(this,B,n)},flush:n=>{if(Z(this,B)==="")return;let s=t.allowCR&&Z(this,B).endsWith("\r")?Z(this,B).slice(0,-1):Z(this,B);n.enqueue(s)}}),lt(this,B,"")}};B=new WeakMap;function en(e){let t=new TextDecoderStream,n=new me({allowCR:!0});return e.pipeThrough(t).pipeThrough(n)}function tn(e){let t=/[:]\s*/.exec(e),n=t&&t.index;if(n)return[e.substring(0,n),e.substring(n+t[0].length)]}function Te(e,t,n){e.get(t)||e.set(t,n)}async function*nn(e,t){if(!e.body)return;let n=en(e.body),s,i=n.getReader(),a;for(;;){if(t&&t.aborted)return i.cancel();if(s=await i.read(),s.done)return;if(!s.value){a&&(yield a),a=void 0;continue}let[o,r]=tn(s.value)||[];o&&(o==="data"?(a||(a={}),a[o]=a[o]?a[o]+`
`+r:r):o==="event"?(a||(a={}),a[o]=r):o==="id"?(a||(a={}),a[o]=+r||r):o==="retry"&&(a||(a={}),a[o]=+r||void 0))}}async function sn(e,t){let n=new Request(e,t);Te(n.headers,"Accept","text/event-stream"),Te(n.headers,"Content-Type","application/json");let s=await fetch(n);if(!s.ok)throw s;return nn(s,n.signal)}async function on(){let{event_callbacks:e,unclosed_events:t,pending_stream_messages:n,stream_status:s,config:i,jwt:a}=this,o=this;if(!i)throw new Error("Could not resolve app config");s.open=!0;let r=null,l=new URLSearchParams({session_hash:this.session_hash}).toString(),_=new URL(`${i.root}${this.api_prefix}/${Ae}?${l}`);if(a&&_.searchParams.set("__sign",a),r=this.stream(_),!r){console.warn("Cannot connect to SSE endpoint: "+_.toString());return}r.onmessage=async function(m){let p=JSON.parse(m.data);if(p.msg==="close_stream"){ve(s,o.abort_controller);return}let g=p.event_id;if(!g)await Promise.all(Object.keys(e).map(C=>e[C](p)));else if(e[g]&&i){p.msg==="process_completed"&&["sse","sse_v1","sse_v2","sse_v2.1","sse_v3"].includes(i.protocol)&&t.delete(g);let C=e[g];typeof window<"u"&&typeof document<"u"?setTimeout(C,0,p):C(p)}else n[g]||(n[g]=[]),n[g].push(p)},r.onerror=async function(m){console.error(m),await Promise.all(Object.keys(e).map(p=>e[p]({msg:"broken_connection",message:W})))}}function ve(e,t){e&&(e.open=!1,t?.abort())}function an(e,t,n){e[t]?n.data.forEach((s,i)=>{let a=rn(e[t][i],s);e[t][i]=a,n.data[i]=a}):(e[t]=[],n.data.forEach((s,i)=>{e[t][i]=s}))}function rn(e,t){return t.forEach(([n,s,i])=>{e=cn(e,s,n,i)}),e}function cn(e,t,n,s){if(t.length===0){if(n==="replace")return s;if(n==="append")return e+s;throw new Error(`Unsupported action: ${n}`)}let i=e;for(let o=0;o<t.length-1;o++)i=i[t[o]];let a=t[t.length-1];switch(n){case"replace":i[a]=s;break;case"append":i[a]+=s;break;case"add":Array.isArray(i)?i.splice(Number(a),0,s):i[a]=s;break;case"delete":Array.isArray(i)?i.splice(Number(a),1):delete i[a];break;default:throw new Error(`Unknown action: ${n}`)}return e}function ln(e,t={}){let n={close:()=>{console.warn("Method not implemented.")},onerror:null,onmessage:null,onopen:null,readyState:0,url:e.toString(),withCredentials:!1,CONNECTING:0,OPEN:1,CLOSED:2,addEventListener:()=>{throw new Error("Method not implemented.")},dispatchEvent:()=>{throw new Error("Method not implemented.")},removeEventListener:()=>{throw new Error("Method not implemented.")}};return sn(e,t).then(async s=>{n.readyState=n.OPEN;try{for await(let i of s)n.onmessage&&n.onmessage(i);n.readyState=n.CLOSED}catch(i){n.onerror&&n.onerror(i),n.readyState=n.CLOSED}}).catch(s=>{console.error(s),n.onerror&&n.onerror(s),n.readyState=n.CLOSED}),n}function un(e,t={},n,s,i){var a;try{let o=function(w){(i||Ze[w.type])&&m(w)},r=function(){for(Qe=!0;H.length>0;)H.shift()({value:void 0,done:!0})},l=function(w){H.length>0?H.shift()(w):ae.push(w)},_=function(w){l(pn(w)),r()},m=function(w){l({value:w,done:!1})},p=function(){return ae.length>0?Promise.resolve(ae.shift()):new Promise(w=>H.push(w))},{hf_token:g}=this.options,{fetch:C,app_reference:U,config:c,session_hash:f,api_info:D,api_map:P,stream_status:ee,pending_stream_messages:te,pending_diff_streams:ne,event_callbacks:se,unclosed_events:We,post_data:ie,options:R,api_prefix:F}=this,Ge=this;if(!D)throw new Error("No API found");if(!c)throw new Error("Could not resolve app config");let{fn_index:d,endpoint_info:be,dependency:J}=dn(D,e,P,c),Me=Lt(t,be),q,z,A=c.protocol??"ws",$e="",He=()=>$e,h=typeof e=="number"?"/predict":e,M,k=null,O=!1,oe={},I=typeof window<"u"&&typeof document<"u"?new URLSearchParams(window.location.search).toString():"",Ze=((a=R?.events)==null?void 0:a.reduce((w,T)=>(w[T]=!0,w),{}))||{};async function Ke(){let w={},T={};A==="ws"?(q&&q.readyState===0?q.addEventListener("open",()=>{q.close()}):q.close(),w={fn_index:d,session_hash:f}):(w={event_id:k},T={event_id:k,session_hash:f,fn_index:d});try{if(!c)throw new Error("Could not resolve app config");"event_id"in T&&await C(`${c.root}${F}/${vt}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(T)}),await C(`${c.root}${F}/${yt}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(w)})}catch{console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.")}}let Ye=async w=>{await this._resolve_heartbeat(w)};async function ke(w){if(!c)return;let T=w.render_id;c.components=[...c.components.filter(E=>E.props.rendered_in!==T),...w.components],c.dependencies=[...c.dependencies.filter(E=>E.rendered_in!==T),...w.dependencies];let re=c.components.some(E=>E.type==="state"),b=c.dependencies.some(E=>E.targets.some(S=>S[1]==="unload"));c.connect_heartbeat=re||b,await Ye(c),o({type:"render",data:w,endpoint:h,fn_index:d})}this.handle_blob(c.root,Me,be).then(async w=>{var T;if(M={data:K(w,J,c.components,"input",!0)||[],event_data:n,fn_index:d,trigger_id:s},Ft(d,c))o({type:"status",endpoint:h,stage:"pending",queue:!1,fn_index:d,time:new Date}),ie(`${c.root}${F}/run${h.startsWith("/")?h:`/${h}`}${I?"?"+I:""}`,{...M,session_hash:f}).then(([b,E])=>{let S=b.data;E==200?(o({type:"data",endpoint:h,fn_index:d,data:K(S,J,c.components,"output",R.with_null_state),time:new Date,event_data:n,trigger_id:s}),b.render_config&&ke(b.render_config),o({type:"status",endpoint:h,fn_index:d,stage:"complete",eta:b.average_duration,queue:!1,time:new Date})):o({type:"status",stage:"error",endpoint:h,fn_index:d,message:b.error,queue:!1,time:new Date})}).catch(b=>{o({type:"status",stage:"error",message:b.message,endpoint:h,fn_index:d,queue:!1,time:new Date})});else if(A=="ws"){let{ws_protocol:b,host:E}=await V(U,g);o({type:"status",stage:"pending",queue:!0,endpoint:h,fn_index:d,time:new Date});let S=new URL(`${b}://${Dt(E,c.root,!0)}/queue/join${I?"?"+I:""}`);this.jwt&&S.searchParams.set("__sign",this.jwt),q=new WebSocket(S),q.onclose=x=>{x.wasClean||o({type:"status",stage:"error",broken:!0,message:W,queue:!0,endpoint:h,fn_index:d,time:new Date})},q.onmessage=function(x){let j=JSON.parse(x.data),{type:$,status:v,data:y}=he(j,oe[d]);if($==="update"&&v&&!O)o({type:"status",endpoint:h,fn_index:d,time:new Date,...v}),v.stage==="error"&&q.close();else if($==="hash"){q.send(JSON.stringify({fn_index:d,session_hash:f}));return}else $==="data"?q.send(JSON.stringify({...M,session_hash:f})):$==="complete"?O=v:$==="log"?o({type:"log",title:y.title,log:y.log,level:y.level,endpoint:h,duration:y.duration,visible:y.visible,fn_index:d}):$==="generating"&&o({type:"status",time:new Date,...v,stage:v?.stage,queue:!0,endpoint:h,fn_index:d});y&&(o({type:"data",time:new Date,data:K(y.data,J,c.components,"output",R.with_null_state),endpoint:h,fn_index:d,event_data:n,trigger_id:s}),O&&(o({type:"status",time:new Date,...O,stage:v?.stage,queue:!0,endpoint:h,fn_index:d}),q.close()))},ze(c.version||"2.0.0","3.6")<0&&addEventListener("open",()=>q.send(JSON.stringify({hash:f})))}else if(A=="sse"){o({type:"status",stage:"pending",queue:!0,endpoint:h,fn_index:d,time:new Date});var re=new URLSearchParams({fn_index:d.toString(),session_hash:f}).toString();let b=new URL(`${c.root}${F}/${Ae}?${I?I+"&":""}${re}`);if(this.jwt&&b.searchParams.set("__sign",this.jwt),z=this.stream(b),!z)return Promise.reject(new Error("Cannot connect to SSE endpoint: "+b.toString()));z.onmessage=async function(E){let S=JSON.parse(E.data),{type:x,status:j,data:$}=he(S,oe[d]);if(x==="update"&&j&&!O)o({type:"status",endpoint:h,fn_index:d,time:new Date,...j}),j.stage==="error"&&(z?.close(),r());else if(x==="data"){let[v,y]=await ie(`${c.root}${F}/queue/data`,{...M,session_hash:f,event_id:k});y!==200&&(o({type:"status",stage:"error",message:W,queue:!0,endpoint:h,fn_index:d,time:new Date}),z?.close(),r())}else x==="complete"?O=j:x==="log"?o({type:"log",title:$.title,log:$.log,level:$.level,endpoint:h,duration:$.duration,visible:$.visible,fn_index:d}):(x==="generating"||x==="streaming")&&o({type:"status",time:new Date,...j,stage:j?.stage,queue:!0,endpoint:h,fn_index:d});$&&(o({type:"data",time:new Date,data:K($.data,J,c.components,"output",R.with_null_state),endpoint:h,fn_index:d,event_data:n,trigger_id:s}),O&&(o({type:"status",time:new Date,...O,stage:j?.stage,queue:!0,endpoint:h,fn_index:d}),z?.close(),r()))}}else if(A=="sse_v1"||A=="sse_v2"||A=="sse_v2.1"||A=="sse_v3"){o({type:"status",stage:"pending",queue:!0,endpoint:h,fn_index:d,time:new Date});let b="";typeof window<"u"&&typeof document<"u"&&(b=(T=window?.location)==null?void 0:T.hostname);let E=b.includes(".dev.")?`https://moon-${b.split(".")[1]}.dev.spaces.huggingface.tech`:"https://huggingface.co";(typeof window<"u"&&typeof document<"u"&&window.parent!=window&&window.supports_zerogpu_headers?Jt("zerogpu-headers",E):Promise.resolve(null)).then(S=>ie(`${c.root}${F}/${dt}?${I}`,{...M,session_hash:f},S)).then(async([S,x])=>{if(x===503)o({type:"status",stage:"error",message:Be,queue:!0,endpoint:h,fn_index:d,time:new Date});else if(x===422)o({type:"status",stage:"error",message:S.detail,queue:!0,endpoint:h,fn_index:d,code:"validation_error",time:new Date}),r();else if(x!==200)o({type:"status",stage:"error",broken:!1,message:S.detail,queue:!0,endpoint:h,fn_index:d,time:new Date});else{k=S.event_id,$e=k;let j=async function($){try{let{type:v,status:y,data:N,original_msg:Xe}=he($,oe[d]);if(v=="heartbeat")return;if(v==="update"&&y&&!O)o({type:"status",endpoint:h,fn_index:d,time:new Date,original_msg:Xe,...y});else if(v==="complete")O=y;else if(v=="unexpected_error"||v=="broken_connection"){console.error("Unexpected error",y?.message);let Ve=v==="broken_connection";o({type:"status",stage:"error",message:y?.message||"An Unexpected Error Occurred!",queue:!0,endpoint:h,broken:Ve,session_not_found:y?.session_not_found,fn_index:d,time:new Date})}else if(v==="log"){o({type:"log",title:N.title,log:N.log,level:N.level,endpoint:h,duration:N.duration,visible:N.visible,fn_index:d});return}else(v==="generating"||v==="streaming")&&(o({type:"status",time:new Date,...y,stage:y?.stage,queue:!0,endpoint:h,fn_index:d}),N&&J.connection!=="stream"&&["sse_v2","sse_v2.1","sse_v3"].includes(A)&&an(ne,k,N));N&&(o({type:"data",time:new Date,data:K(N.data,J,c.components,"output",R.with_null_state),endpoint:h,fn_index:d}),N.render_config&&await ke(N.render_config),O&&(o({type:"status",time:new Date,...O,stage:y?.stage,queue:!0,endpoint:h,fn_index:d}),r())),(y?.stage==="complete"||y?.stage==="error")&&(se[k]&&delete se[k],k in ne&&delete ne[k])}catch(v){console.error("Unexpected client exception",v),o({type:"status",stage:"error",message:"An Unexpected Error Occurred!",queue:!0,endpoint:h,fn_index:d,time:new Date}),["sse_v2","sse_v2.1","sse_v3"].includes(A)&&(ve(ee,Ge.abort_controller),ee.open=!1,r())}};k in te&&(te[k].forEach($=>j($)),delete te[k]),se[k]=j,We.add(k),ee.open||await this.open_stream()}})}});let Qe=!1,ae=[],H=[],Ee={[Symbol.asyncIterator]:()=>Ee,next:p,throw:async w=>(_(w),p()),return:async()=>(r(),p()),cancel:Ke,event_id:He};return Ee}catch(o){throw console.error("Submit function encountered an error:",o),o}}function pn(e){return{then:(t,n)=>n(e)}}function dn(e,t,n,s){let i,a,o;if(typeof t=="number")i=t,a=e.unnamed_endpoints[i],o=s.dependencies.find(r=>r.id==t);else{let r=t.replace(/^\//,"");i=n[r],a=e.named_endpoints[t.trim()],o=s.dependencies.find(l=>l.id==n[r])}if(typeof i!="number")throw new Error("There is no endpoint matching that name of fn_index matching that number.");return{fn_index:i,endpoint_info:a,dependency:o}}var G=class{constructor(t,n={events:["data"]}){u(this,"app_reference"),u(this,"options"),u(this,"deep_link",null),u(this,"config"),u(this,"api_prefix",""),u(this,"api_info"),u(this,"api_map",{}),u(this,"session_hash",Math.random().toString(36).substring(2)),u(this,"jwt",!1),u(this,"last_status",{}),u(this,"cookies",null),u(this,"stream_status",{open:!1}),u(this,"closed",!1),u(this,"pending_stream_messages",{}),u(this,"pending_diff_streams",{}),u(this,"event_callbacks",{}),u(this,"unclosed_events",new Set),u(this,"heartbeat_event",null),u(this,"abort_controller",null),u(this,"stream_instance",null),u(this,"current_payload"),u(this,"ws_map",{}),u(this,"view_api"),u(this,"upload_files"),u(this,"upload"),u(this,"handle_blob"),u(this,"post_data"),u(this,"submit"),u(this,"predict"),u(this,"open_stream"),u(this,"resolve_config"),u(this,"resolve_cookies");var s;this.app_reference=t,this.deep_link=((s=n.query_params)==null?void 0:s.deep_link)||null,n.events||(n.events=["data"]),this.options=n,this.current_payload={},this.view_api=Ut.bind(this),this.upload_files=It.bind(this),this.handle_blob=Wt.bind(this),this.post_data=Ht.bind(this),this.submit=un.bind(this),this.predict=Zt.bind(this),this.open_stream=on.bind(this),this.resolve_config=Tt.bind(this),this.resolve_cookies=Nt.bind(this),this.upload=Rt.bind(this),this.fetch=this.fetch.bind(this),this.handle_space_success=this.handle_space_success.bind(this),this.stream=this.stream.bind(this)}get_url_config(t=null){if(!this.config)throw new Error(L);t===null&&(t=window.location.href);let n=o=>o.replace(/^\/+|\/+$/g,""),s=n(new URL(this.config.root).pathname),i=n(new URL(t).pathname),a;return i.startsWith(s)?a=n(i.substring(s.length)):a="",this.get_page_config(a)}get_page_config(t){if(!this.config)throw new Error(L);let n=this.config;return t in n.page||(t=""),{...n,current_page:t,layout:n.page[t].layout,components:n.components.filter(s=>n.page[t].components.includes(s.id)),dependencies:this.config.dependencies.filter(s=>n.page[t].dependencies.includes(s.id))}}fetch(t,n){let s=new Headers(n?.headers||{});if(this&&this.cookies&&s.append("Cookie",this.cookies),this&&this.options.headers)for(let i in this.options.headers)s.append(i,this.options.headers[i]);return fetch(t,{...n,headers:s})}stream(t){let n=new Headers;if(this&&this.cookies&&n.append("Cookie",this.cookies),this&&this.options.headers)for(let s in this.options.headers)n.append(s,this.options.headers[s]);return this&&this.options.hf_token&&n.append("Authorization",`Bearer ${this.options.hf_token}`),this.abort_controller=new AbortController,this.stream_instance=ln(t.toString(),{credentials:"include",headers:n,signal:this.abort_controller.signal}),this.stream_instance}async init(){var t;this.options.auth&&await this.resolve_cookies(),await this._resolve_config().then(({config:n})=>this._resolve_heartbeat(n)),this.api_info=await this.view_api(),this.api_map=Ot(((t=this.config)==null?void 0:t.dependencies)||[])}async _resolve_heartbeat(t){if(t&&(this.config=t,this.api_prefix=t.api_prefix||"",this.config&&this.config.connect_heartbeat&&this.config.space_id&&this.options.hf_token&&(this.jwt=await je(this.config.space_id,this.options.hf_token,this.cookies))),t.space_id&&this.options.hf_token&&(this.jwt=await je(t.space_id,this.options.hf_token)),this.config&&this.config.connect_heartbeat){let n=new URL(`${this.config.root}${this.api_prefix}/${mt}/${this.session_hash}`);this.jwt&&n.searchParams.set("__sign",this.jwt),this.heartbeat_event||(this.heartbeat_event=this.stream(n))}}static async connect(t,n={events:["data"]}){let s=new this(t,n);return n.session_hash&&(s.session_hash=n.session_hash),await s.init(),s}async reconnect(){let t=new URL(`${this.config.root}${this.api_prefix}/${bt}`),n;try{let s=await this.fetch(t);if(!s.ok)throw new Error;n=(await s.json()).app_id}catch{return"broken"}return n!==this.config.app_id?"changed":"connected"}close(){this.closed=!0,ve(this.stream_status,this.abort_controller)}set_current_payload(t){this.current_payload=t}static async duplicate(t,n={events:["data"]}){return Xt(t,n)}async _resolve_config(){let{http_protocol:t,host:n,space_id:s}=await V(this.app_reference,this.options.hf_token),{status_callback:i}=this.options;s&&i&&await Je(s,i);let a;try{let o=`${t}//${n}`;if(a=await this.resolve_config(o),!a)throw new Error(L);return this.config_success(a)}catch(o){if(s&&i)Y(s,ye.test(s)?"space_name":"subdomain",this.handle_space_success);else throw i&&i({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),Error(o)}}async config_success(t){if(this.config=t,this.api_prefix=t.api_prefix||"",this.config.auth_required)return this.prepare_return_obj();try{this.api_info=await this.view_api()}catch(n){console.error(Et+n.message)}return this.prepare_return_obj()}async handle_space_success(t){var n;if(!this)throw new Error(L);let{status_callback:s}=this.options;if(s&&s(t),t.status==="running")try{if(this.config=await this._resolve_config(),this.api_prefix=((n=this==null?void 0:this.config)==null?void 0:n.api_prefix)||"",!this.config)throw new Error(L);return await this.config_success(this.config)}catch(i){throw s&&s({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),i}}async component_server(t,n,s){var i;if(!this.config)throw new Error(L);let a={},{hf_token:o}=this.options,{session_hash:r}=this;o&&(a.Authorization=`Bearer ${this.options.hf_token}`);let l,_=this.config.components.find(p=>p.id===t);(i=_?.props)!=null&&i.root_url?l=_.props.root_url:l=this.config.root;let m;if("binary"in s){m=new FormData;for(let p in s.data)p!=="binary"&&m.append(p,s.data[p]);m.set("component_id",t.toString()),m.set("fn_name",n),m.set("session_hash",r)}else m=JSON.stringify({data:s,component_id:t,fn_name:n,session_hash:r}),a["Content-Type"]="application/json";o&&(a.Authorization=`Bearer ${o}`);try{let p=await this.fetch(`${l}${this.api_prefix}/${wt}/`,{method:"POST",body:m,headers:a,credentials:"include"});if(!p.ok)throw new Error("Could not connect to component server: "+p.statusText);return await p.json()}catch(p){console.warn(p)}}set_cookies(t){this.cookies=Re(t).join("; ")}prepare_return_obj(){return{config:this.config,predict:this.predict,submit:this.submit,view_api:this.view_api,component_server:this.component_server}}async connect_ws(t){return new Promise((n,s)=>{let i;try{i=new WebSocket(t)}catch{this.ws_map[t]="failed";return}this.ws_map[t]="pending",i.onopen=()=>{this.ws_map[t]=i,n()},i.onerror=a=>{console.error("WebSocket error:",a),this.close_ws(t),this.ws_map[t]="failed",n()},i.onclose=()=>{this.ws_map[t]="closed"},i.onmessage=a=>{}})}async send_ws_message(t,n){if(!(t in this.ws_map))await this.connect_ws(t);else if(this.ws_map[t]==="pending"||this.ws_map[t]==="closed"||this.ws_map[t]==="failed")return;let s=this.ws_map[t];s instanceof WebSocket?s.send(JSON.stringify(n)):this.post_data(t,n)}async close_ws(t){if(t in this.ws_map){let n=this.ws_map[t];n instanceof WebSocket&&(n.close(),delete this.ws_map[t])}}};return ot(hn);})();