stat_ui / _app /immutable /nodes /2.BibxG5Sb.js
Hanzo03's picture
final static build
e278001
raw
history blame
40 kB
import"../chunks/DsnmJJEf.js";import"../chunks/RQJcbRZ4.js";import{a3 as it,E as at,b as ot,a4 as rt,i as ct,O as X,a5 as lt,S as ut,T as dt,W as pt,g as j,X as Y,Y as ht,a6 as z,a7 as re,$ as ee,Z as te,a8 as ft,_ as ne,a9 as he,a1 as _t,V as gt}from"../chunks/8qN8-VEG.js";import{e as mt,s as wt}from"../chunks/C9Nr9G0R.js";import{_ as je,i as De}from"../chunks/tlJ_21GF.js";import{i as vt}from"../chunks/BcatIsNN.js";function yt(e,n,t=n){var s=new WeakSet;it(e,"input",async i=>{var a=i?e.defaultValue:e.value;if(a=fe(e)?_e(a):a,t(a),X!==null&&s.add(X),await at(),a!==(a=n())){var o=e.selectionStart,r=e.selectionEnd,c=e.value.length;if(e.value=a??"",r!==null){var p=e.value.length;o===r&&r===c&&p>c?(e.selectionStart=p,e.selectionEnd=p):(e.selectionStart=o,e.selectionEnd=Math.min(r,p))}}}),(ct&&e.defaultValue!==e.value||ot(n)==null&&e.value)&&(t(fe(e)?_e(e.value):e.value),X!==null&&s.add(X)),rt(()=>{var i=n();if(e===document.activeElement){var a=lt??X;if(s.has(a))return}fe(e)&&i===_e(e.value)||e.type==="date"&&!i&&!e.value||i!==e.value&&(e.value=i??"")})}function fe(e){var n=e.type;return n==="number"||n==="range"}function _e(e){return e===""?null:+e}function bt(e){return function(...n){var t=n[0];return t.preventDefault(),e?.apply(this,n)}}var Et=Object.defineProperty,Ue=e=>{throw TypeError(e)},kt=(e,n,t)=>n in e?Et(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,d=(e,n,t)=>kt(e,typeof n!="symbol"?n+"":n,t),Be=(e,n,t)=>n.has(e)||Ue("Cannot "+t),se=(e,n,t)=>(Be(e,n,"read from private field"),n.get(e)),$t=(e,n,t)=>n.has(e)?Ue("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,t),xt=(e,n,t,s)=>(Be(e,n,"write to private field"),n.set(e,t),t);const St="host",Fe="queue/data",Pt="queue/join",Oe="upload",Ct="login",ce="config",Tt="info",jt="runtime",Dt="sleeptime",Ot="heartbeat",At="component_server",qt="reset",zt="cancel",Nt="app_id",Ge="This application is currently busy. Please try again. ",ae="Connection errored out. ",G="Could not resolve app config. ",It="Could not get space status. ",Lt="Could not get API info. ",ye="Space metadata could not be loaded. ",Rt="Invalid URL. A full URL path is required.",Ut="Not authorized to access this space. ",Je="Invalid credentials. Could not login. ",Bt="Login credentials are required to access this space.",Ft="File system access is only available in Node.js environments",We="Root URL not found in client config",Gt="Error uploading file";async function Ae(e,n,t){try{return(await(await fetch(`https://huggingface.co/api/spaces/${e}/jwt`,{headers:{Authorization:`Bearer ${n}`,...t?{Cookie:t}:{}}})).json()).token||!1}catch{return!1}}function Jt(e){let n={};return e.forEach(({api_name:t,id:s})=>{t&&(n[t]=s)}),n}async function Wt(e){const n=this.options.token?{Authorization:`Bearer ${this.options.token}`}:{};if(n["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 t=me(e,this.deep_link?ce+"?deep_link="+this.deep_link:ce);const s=await this.fetch(t,{headers:n,credentials:"include"}),i=await qe(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 t=me(e,this.deep_link?ce+"?deep_link="+this.deep_link:ce);const s=await this.fetch(t,{headers:n,credentials:"include"});return qe(s,e,!!this.options.auth)}throw new Error(G)}async function qe(e,n,t){var s,i;if(e?.status===401&&!t){const a=await e.json(),o=(s=a?.detail)==null?void 0:s.auth_message;throw new Error(o||Bt)}else if(e?.status===401&&t)throw new Error(Je);if(e?.status===200){let a=await e.json();return a.root=n,(i=a.dependencies)==null||i.forEach((o,r)=>{o.id===void 0&&(o.id=r)}),a}else if(e?.status===401)throw new Error(Ut);throw new Error(G)}async function Mt(){const{http_protocol:e,host:n}=await Ee(this.app_reference,this.options.token);try{if(this.options.auth){const t=await Me(e,n,this.options.auth,this.fetch,this.options.token);t&&this.set_cookies(t)}}catch(t){throw Error(t.message)}}async function Me(e,n,t,s,i){const a=new FormData;a.append("username",t?.[0]),a.append("password",t?.[1]);let o={};i&&(o.Authorization=`Bearer ${i}`);const r=await s(`${e}//${n}/${Ct}`,{headers:o,method:"POST",body:a,credentials:"include"});if(r.status===200)return r.headers.get("set-cookie");throw r.status===401?new Error(Je):new Error(ye)}function ge(e){if(e.startsWith("http")){const{protocol:n,host:t,pathname:s}=new URL(e);return{ws_protocol:n==="https:"?"wss":"ws",http_protocol:n,host:t+(s!=="/"?s:"")}}return{ws_protocol:"wss",http_protocol:"https:",host:new URL(e).host}}const Ve=e=>{let n=[];return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach(t=>{const[s,i]=t.split(";")[0].split("=");s&&i&&n.push(`${s.trim()}=${i.trim()}`)}),n},be=/^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/,Vt=/.*hf\.space\/{0,1}.*$/;async function Ee(e,n){const t={};n&&(t.Authorization=`Bearer ${n}`);const s=e.trim().replace(/\/$/,"");if(be.test(s))try{const i=(await(await fetch(`https://huggingface.co/api/spaces/${s}/${St}`,{headers:t})).json()).host;return{space_id:e,...ge(i)}}catch{throw new Error(ye)}if(Vt.test(s)){const{ws_protocol:i,http_protocol:a,host:o}=ge(s);return{space_id:o.split("/")[0].replace(".hf.space",""),ws_protocol:i,http_protocol:a,host:o}}return{space_id:!1,...ge(s)}}const me=(...e)=>{try{return e.reduce((n,t)=>(n=n.replace(/\/+$/,""),t=t.replace(/^\/+/,""),new URL(t,n+"/").toString()))}catch{throw new Error(Rt)}};function Ht(e,n,t){const 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 c,p,f,u;const h=((c=n.dependencies.find(l=>l.api_name===a||l.api_name===a.replace("/","")))==null?void 0:c.id)||t[a.replace("/","")]||-1,v=h!==-1?(p=n.dependencies.find(l=>l.id==h))==null?void 0:p.types:{generator:!1,cancel:!1};if(h!==-1&&((u=(f=n.dependencies.find(l=>l.id==h))==null?void 0:f.inputs)==null?void 0:u.length)!==o.length){const l=n.dependencies.find(_=>_.id==h).inputs.map(_=>{var $;return($=n.components.find(x=>x.id===_))==null?void 0:$.type});try{l.forEach((_,$)=>{if(_==="state"){const x={component:"state",example:null,parameter_default:null,parameter_has_default:!0,parameter_name:null,hidden:!0};o.splice($,0,x)}})}catch(_){console.error(_)}}const N=(l,_,$,x)=>({...l,description:Kt(l?.type,$),type:Zt(l?.type,_,$,x)||""});s[i][a]={parameters:o.map(l=>N(l,l?.component,l?.serializer,"parameter")),returns:r.map(l=>N(l,l?.component,l?.serializer,"return")),type:v}}))}),s}function Zt(e,n,t,s){if(n==="Api")return e.type;switch(e?.type){case"string":return"string";case"boolean":return"boolean";case"number":return"number"}if(t==="JSONSerializable"||t==="StringSerializable")return"any";if(t==="ListStringSerializable")return"string[]";if(n==="Image")return s==="parameter"?"Blob | File | Buffer":"string";if(t==="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(t==="GallerySerializable")return s==="parameter"?"[(Blob | File | Buffer), (string | null)][]":"[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]"}function Kt(e,n){return n==="GallerySerializable"?"array of [file, label] tuples":n==="ListStringSerializable"?"array of strings":n==="FileSerializable"?"array of files or single file":e?.description}function ze(e,n){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:Ge,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:n||"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}}}const Qt=(e=[],n)=>{const t=n?n.parameters:[];if(Array.isArray(e))return n&&t.length>0&&e.length>t.length&&console.warn("Too many arguments provided for the endpoint."),e;const s=[],i=Object.keys(e);return t.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(!t.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&&!t[o].parameter_has_default)throw new Error(`No value provided for required parameter: ${t[o].parameter_name}`)}),s};async function Xt(){if(this.api_info)return this.api_info;const{token:e}=this.options,{config:n}=this,t={"Content-Type":"application/json"};if(e&&(t.Authorization=`Bearer ${e}`),!!n)try{let s,i;if(typeof window<"u"&&window.gradio_api_info)i=window.gradio_api_info;else{const a=me(n.root,this.api_prefix,Tt);if(s=await this.fetch(a,{headers:t,credentials:"include"}),!s.ok)throw new Error(ae);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"]),Ht(i,n,this.api_map)}catch(s){throw new Error("Could not get API info. "+s.message)}}async function Yt(e,n,t){var s;const i={};(s=this==null?void 0:this.options)!=null&&s.token&&(i.Authorization=`Bearer ${this.options.token}`);const a=1e3,o=[];let r;for(let c=0;c<n.length;c+=a){const p=n.slice(c,c+a),f=new FormData;p.forEach(h=>{f.append("files",h)});try{const h=t?`${e}${this.api_prefix}/${Oe}?upload_id=${t}`:`${e}${this.api_prefix}/${Oe}`;r=await this.fetch(h,{method:"POST",body:f,headers:i,credentials:"include"})}catch(h){throw new Error(ae+h.message)}if(!r.ok){const h=await r.text();return{error:`HTTP ${r.status}: ${h}`}}const u=await r.json();u&&o.push(...u)}return{files:o}}async function en(e,n,t,s){let i=(Array.isArray(e)?e:[e]).map(o=>o.blob);const 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(n,i,t).then(async o=>{if(o.error)throw new Error(o.error);return o.files?o.files.map((r,c)=>new ke({...e[c],path:r,url:`${n}${this.api_prefix}/file=${r}`})):[]}))}class ke{constructor({path:n,url:t,orig_name:s,size:i,blob:a,is_stream:o,mime_type:r,alt_text:c,b64:p}){d(this,"path"),d(this,"url"),d(this,"orig_name"),d(this,"size"),d(this,"blob"),d(this,"is_stream"),d(this,"mime_type"),d(this,"alt_text"),d(this,"b64"),d(this,"meta",{_type:"gradio.FileData"}),this.path=n,this.url=t,this.orig_name=s,this.size=i,this.blob=t?void 0:a,this.is_stream=o,this.mime_type=r,this.alt_text=c,this.b64=p}}class tn{constructor(n,t){d(this,"type"),d(this,"command"),d(this,"meta"),d(this,"fileData"),this.type="command",this.command=n,this.meta=t}}typeof process<"u"&&process.versions&&process.versions.node;function Ne(e,n,t){for(;t.length>1;){const i=t.shift();if(typeof i=="string"||typeof i=="number")e=e[i];else throw new Error("Invalid key type")}const s=t.shift();if(typeof s=="string"||typeof s=="number")e[s]=n;else throw new Error("Invalid key type")}async function we(e,n=void 0,t=[],s=!1,i=void 0){if(Array.isArray(e)){let a=[];return await Promise.all(e.map(async(o,r)=>{var c;let p=t.slice();p.push(String(r));const f=await we(e[r],s?((c=i?.parameters[r])==null?void 0:c.component)||void 0:n,p,!1,i);a=a.concat(f)})),a}else{if(globalThis.Buffer&&e instanceof globalThis.Buffer||e instanceof Blob)return[{path:t,blob:new Blob([e]),type:n}];if(typeof e=="object"&&e!==null){let a=[];for(const o of Object.keys(e)){const r=[...t,o],c=e[o];a=a.concat(await we(c,void 0,r,!1,i))}return a}}return[]}function nn(e,n){var t,s;let i=(s=(t=n?.dependencies)==null?void 0:t.find(a=>a.id==e))==null?void 0:s.queue;return i!=null?!i:!n.enable_queue}function sn(e,n){return new Promise((t,s)=>{const i=new MessageChannel;i.port1.onmessage=({data:a})=>{i.port1.close(),t(a)},window.parent.postMessage(e,n,[i.port2])})}function le(e,n,t,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;const r=s==="input"?n.inputs:n.outputs;for(let c=0;c<r.length;c++){const p=r[c],f=t.find(u=>u.id===p);if(f?.type==="state"){if(i)if(e.length===r.length){const u=e[o];a.push(u),o++}else a.push(null);else{o++;continue}continue}else{const u=e[o];a.push(u),o++}}return a}async function an(e,n,t){const s=this;await on(s,n);const i=await we(n,void 0,[],!0,t);return(await Promise.all(i.map(async({path:a,blob:o,type:r})=>{if(!o)return{path:a,type:r};const c=await s.upload_files(e,[o]),p=c.files&&c.files[0];return{path:a,file_url:p,type:r,name:typeof File<"u"&&o instanceof File?o?.name:void 0}}))).forEach(({path:a,file_url:o,type:r,name:c})=>{if(r==="Gallery")Ne(n,o,a);else if(o){const p=new ke({path:o,orig_name:c});Ne(n,p,a)}}),n}async function on(e,n){var t,s;if(!((t=e.config)!=null&&t.root||(s=e.config)!=null&&s.root_url))throw new Error(We);await He(e,n)}async function He(e,n,t=[]){for(const s in n)n[s]instanceof tn?await rn(e,n,s):typeof n[s]=="object"&&n[s]!==null&&await He(e,n[s],[...t,s])}async function rn(e,n,t){var s,i;let a=n[t];const o=((s=e.config)==null?void 0:s.root)||((i=e.config)==null?void 0:i.root_url);if(!o)throw new Error(We);try{let r,c;if(typeof process<"u"&&process.versions&&process.versions.node){const h=await je(()=>import("../chunks/BIHI7g3E.js"),[],import.meta.url);c=(await je(async()=>{const{resolve:v}=await import("../chunks/BIHI7g3E.js");return{resolve:v}},[],import.meta.url)).resolve(process.cwd(),a.meta.path),r=await h.readFile(c)}else throw new Error(Ft);const p=new Blob([r],{type:"application/octet-stream"}),f=await e.upload_files(o,[p]),u=f.files&&f.files[0];if(u){const h=new ke({path:u,orig_name:a.meta.name||""});n[t]=h}}catch(r){console.error(Gt,r)}}async function cn(e,n,t){const s={"Content-Type":"application/json"};this.options.token&&(s.Authorization=`Bearer ${this.options.token}`);try{var i=await this.fetch(e,{method:"POST",body:JSON.stringify(n),headers:{...s,...t},credentials:"include"})}catch{return[{error:ae},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 ln(e,n={}){let t=!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{const i=e.replace(/^\//,"");this.config.dependencies.find(a=>a.id==this.api_map[i])}return new Promise(async(i,a)=>{const o=this.submit(e,n,null,null,!0);let r;for await(const c of o)c.type==="data"&&(s&&i(r),t=!0,r=c),c.type==="status"&&(c.stage==="error"&&a(c),c.stage==="complete"&&(s=!0,t&&i(r)))})}async function ie(e,n,t){let s=n==="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{t({status:"error",load_status:"error",message:It,detail:"NOT_FOUND"});return}if(!i||a!==200)return;const{runtime:{stage:o},id:r}=i;switch(o){case"STOPPED":case"SLEEPING":t({status:"sleeping",load_status:"pending",message:"Space is asleep. Waking it up...",detail:o}),setTimeout(()=>{ie(e,n,t)},1e3);break;case"PAUSED":t({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 Ie(r)});break;case"RUNNING":case"RUNNING_BUILDING":t({status:"running",load_status:"complete",message:"Space is running.",detail:o});break;case"BUILDING":t({status:"building",load_status:"pending",message:"Space is building...",detail:o}),setTimeout(()=>{ie(e,n,t)},1e3);break;case"APP_STARTING":t({status:"starting",load_status:"pending",message:"Space is starting...",detail:o}),setTimeout(()=>{ie(e,n,t)},1e3);break;default:t({status:"space_error",load_status:"error",message:"This space is experiencing an issue.",detail:o,discussions_enabled:await Ie(r)});break}}const Ze=async(e,n)=>{let t=0;const s=12,i=5e3;return new Promise(a=>{ie(e,be.test(e)?"space_name":"subdomain",o=>{n(o),o.status==="running"||o.status==="error"||o.status==="paused"||o.status==="space_error"?a():(o.status==="sleeping"||o.status==="building")&&(t<s?(t++,setTimeout(()=>{Ze(e,n).then(a)},i)):a())})})},un=/^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;async function Ie(e){try{const n=await fetch(`https://huggingface.co/api/spaces/${e}/discussions`,{method:"HEAD"}),t=n.headers.get("x-error-message");return!(!n.ok||t&&un.test(t))}catch{return!1}}async function dn(e,n){const t={};n&&(t.Authorization=`Bearer ${n}`);try{const s=await fetch(`https://huggingface.co/api/spaces/${e}/${jt}`,{headers:t});if(s.status!==200)throw new Error("Space hardware could not be obtained.");const{hardware:i}=await s.json();return i.current}catch(s){throw new Error(s.message)}}async function pn(e,n,t){const s={};t&&(s.Authorization=`Bearer ${t}`);const i={seconds:n};try{const a=await fetch(`https://huggingface.co/api/spaces/${e}/${Dt}`,{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)}}const Le=["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 hn(e,n){const{token:t,private:s,hardware:i,timeout:a,auth:o}=n;if(i&&!Le.includes(i))throw new Error(`Invalid hardware type provided. Valid types are: ${Le.map(_=>`"${_}"`).join(",")}.`);const{http_protocol:r,host:c}=await Ee(e,t);let p=null;if(o){const _=await Me(r,c,o,fetch);_&&(p=Ve(_))}const f={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...p?{Cookie:p.join("; ")}:{}},u=(await(await fetch("https://huggingface.co/api/whoami-v2",{headers:f})).json()).name,h=e.split("/")[1],v={repository:`${u}/${h}`};s&&(v.private=!0);let N;try{i||(N=await dn(e,t))}catch(_){throw Error(ye+_.message)}const l=i||N||"cpu-basic";v.hardware=l;try{const _=await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`,{method:"POST",headers:f,body:JSON.stringify(v)});if(_.status===409)try{return await ve.connect(`${u}/${h}`,n)}catch(x){throw console.error("Failed to connect Client instance:",x),x}else if(_.status!==200)throw new Error(_.statusText);const $=await _.json();return await pn(`${u}/${h}`,a||300,t),await ve.connect(fn($.url),n)}catch(_){throw new Error(_)}}function fn(e){const n=/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/,t=e.match(n);if(t)return t[1]}var F;class _n extends TransformStream{constructor(n={allowCR:!1}){super({transform:(t,s)=>{for(t=se(this,F)+t;;){const i=t.indexOf(`
`),a=n.allowCR?t.indexOf("\r"):-1;if(a!==-1&&a!==t.length-1&&(i===-1||i-1>a)){s.enqueue(t.slice(0,a)),t=t.slice(a+1);continue}if(i===-1)break;const o=t[i-1]==="\r"?i-1:i;s.enqueue(t.slice(0,o)),t=t.slice(i+1)}xt(this,F,t)},flush:t=>{if(se(this,F)==="")return;const s=n.allowCR&&se(this,F).endsWith("\r")?se(this,F).slice(0,-1):se(this,F);t.enqueue(s)}}),$t(this,F,"")}}F=new WeakMap;function gn(e){let n=new TextDecoderStream,t=new _n({allowCR:!0});return e.pipeThrough(n).pipeThrough(t)}function mn(e){let n=/[:]\s*/.exec(e),t=n&&n.index;if(t)return[e.substring(0,t),e.substring(t+n[0].length)]}function Re(e,n,t){e.get(n)||e.set(n,t)}async function*wn(e,n){if(!e.body)return;let t=gn(e.body),s,i=t.getReader(),a;for(;;){if(n&&n.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]=mn(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 vn(e,n){let t=new Request(e,n);Re(t.headers,"Accept","text/event-stream"),Re(t.headers,"Content-Type","application/json");let s=await fetch(t);if(!s.ok)throw s;return wn(s,t.signal)}async function yn(){let{event_callbacks:e,unclosed_events:n,pending_stream_messages:t,stream_status:s,config:i,jwt:a}=this;const o=this;if(!i)throw new Error("Could not resolve app config");s.open=!0;let r=null,c=new URLSearchParams({session_hash:this.session_hash}).toString(),p=new URL(`${i.root}${this.api_prefix}/${Fe}?${c}`);if(a&&p.searchParams.set("__sign",a),r=this.stream(p),!r){console.warn("Cannot connect to SSE endpoint: "+p.toString());return}r.onmessage=async function(f){let u=JSON.parse(f.data);if(u.msg==="close_stream"){$e(s,o.abort_controller);return}const h=u.event_id;if(!h)await Promise.all(Object.keys(e).map(v=>e[v](u)));else if(e[h]&&i){u.msg==="process_completed"&&["sse","sse_v1","sse_v2","sse_v2.1","sse_v3"].includes(i.protocol)&&n.delete(h);let v=e[h];typeof window<"u"&&typeof document<"u"?setTimeout(v,0,u):v(u)}else t[h]||(t[h]=[]),t[h].push(u)},r.onerror=async function(f){console.error(f),await Promise.all(Object.keys(e).map(u=>e[u]({msg:"broken_connection",message:ae})))}}function $e(e,n){e&&(e.open=!1,n?.abort())}function bn(e,n,t){e[n]?t.data.forEach((s,i)=>{let a=En(e[n][i],s);e[n][i]=a,t.data[i]=a}):(e[n]=[],t.data.forEach((s,i)=>{e[n][i]=s}))}function En(e,n){return n.forEach(([t,s,i])=>{e=kn(e,s,t,i)}),e}function kn(e,n,t,s){if(n.length===0){if(t==="replace")return s;if(t==="append")return e+s;throw new Error(`Unsupported action: ${t}`)}let i=e;for(let o=0;o<n.length-1;o++)i=i[n[o]];const a=n[n.length-1];switch(t){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: ${t}`)}return e}function $n(e,n={}){const t={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 vn(e,n).then(async s=>{t.readyState=t.OPEN;try{for await(const i of s)t.onmessage&&t.onmessage(i);t.readyState=t.CLOSED}catch(i){t.onerror&&t.onerror(i),t.readyState=t.CLOSED}}).catch(s=>{console.error(s),t.onerror&&t.onerror(s),t.readyState=t.CLOSED}),t}function xn(e,n={},t,s,i){var a;try{let o=function(m){(i||Xe[m.type])&&f(m)},r=function(){for(tt=!0;Q.length>0;)Q.shift()({value:void 0,done:!0})},c=function(m){Q.length>0?Q.shift()(m):de.push(m)},p=function(m){c(Sn(m)),r()},f=function(m){c({value:m,done:!1})},u=function(){return de.length>0?Promise.resolve(de.shift()):new Promise(m=>Q.push(m))};const{token:h}=this.options,{fetch:v,app_reference:N,config:l,session_hash:_,api_info:$,api_map:x,stream_status:W,pending_stream_messages:M,pending_diff_streams:b,event_callbacks:R,unclosed_events:ue,post_data:V,options:J,api_prefix:S}=this,H=this;if(!$)throw new Error("No API found");if(!l)throw new Error("Could not resolve app config");let{fn_index:g,endpoint_info:xe,dependency:Z}=Pn($,e,x,l),Ke=Qt(n,xe),L,U=l.protocol??"ws";if(U==="ws")throw new Error("WebSocket protocol is not supported in this version");let Se="",Qe=()=>Se;const w=typeof e=="number"?"/predict":e;let oe,k=null,B=!1,Pe={},K=typeof window<"u"&&typeof document<"u"?new URLSearchParams(window.location.search).toString():"";const Xe=((a=J?.events)==null?void 0:a.reduce((m,D)=>(m[D]=!0,m),{}))||{};async function Ye(){let m={},D={};m={event_id:k},D={event_id:k,session_hash:_,fn_index:g};try{if(!l)throw new Error("Could not resolve app config");"event_id"in D&&await v(`${l.root}${S}/${zt}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(D)}),await v(`${l.root}${S}/${qt}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(m)})}catch{console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.")}}const et=async m=>{await this._resolve_heartbeat(m)};async function Ce(m){if(!l)return;let D=m.render_id;l.components=[...l.components.filter(P=>P.props.rendered_in!==D),...m.components],l.dependencies=[...l.dependencies.filter(P=>P.rendered_in!==D),...m.dependencies];const pe=l.components.some(P=>P.type==="state"),E=l.dependencies.some(P=>P.targets.some(O=>O[1]==="unload"));l.connect_heartbeat=pe||E,await et(l),o({type:"render",data:m,endpoint:w,fn_index:g})}this.handle_blob(l.root,Ke,xe).then(async m=>{var D;if(oe={data:le(m,Z,l.components,"input",!0)||[],event_data:t,fn_index:g,trigger_id:s},nn(g,l))o({type:"status",endpoint:w,stage:"pending",queue:!1,fn_index:g,time:new Date}),V(`${l.root}${S}/run${w.startsWith("/")?w:`/${w}`}${K?"?"+K:""}`,{...oe,session_hash:_}).then(([E,P])=>{const O=E.data;P==200?(o({type:"data",endpoint:w,fn_index:g,data:le(O,Z,l.components,"output",J.with_null_state),time:new Date,event_data:t,trigger_id:s}),E.render_config&&Ce(E.render_config),o({type:"status",endpoint:w,fn_index:g,stage:"complete",eta:E.average_duration,queue:!1,time:new Date})):o({type:"status",stage:"error",endpoint:w,fn_index:g,message:E.error,queue:!1,time:new Date})}).catch(E=>{o({type:"status",stage:"error",message:E.message,endpoint:w,fn_index:g,queue:!1,time:new Date})});else if(U=="sse"){o({type:"status",stage:"pending",queue:!0,endpoint:w,fn_index:g,time:new Date});var pe=new URLSearchParams({fn_index:g.toString(),session_hash:_}).toString();let E=new URL(`${l.root}${S}/${Fe}?${K?K+"&":""}${pe}`);if(this.jwt&&E.searchParams.set("__sign",this.jwt),L=this.stream(E),!L)return Promise.reject(new Error("Cannot connect to SSE endpoint: "+E.toString()));L.onmessage=async function(P){const O=JSON.parse(P.data),{type:I,status:C,data:A}=ze(O,Pe[g]);if(I==="update"&&C&&!B)o({type:"status",endpoint:w,fn_index:g,time:new Date,...C}),C.stage==="error"&&(L?.close(),r());else if(I==="data"){let[T,y]=await V(`${l.root}${S}/queue/data`,{...oe,session_hash:_,event_id:k});y!==200&&(o({type:"status",stage:"error",message:ae,queue:!0,endpoint:w,fn_index:g,time:new Date}),L?.close(),r())}else I==="complete"?B=C:I==="log"?o({type:"log",title:A.title,log:A.log,level:A.level,endpoint:w,duration:A.duration,visible:A.visible,fn_index:g}):(I==="generating"||I==="streaming")&&o({type:"status",time:new Date,...C,stage:C?.stage,queue:!0,endpoint:w,fn_index:g});A&&(o({type:"data",time:new Date,data:le(A.data,Z,l.components,"output",J.with_null_state),endpoint:w,fn_index:g,event_data:t,trigger_id:s}),B&&(o({type:"status",time:new Date,...B,stage:C?.stage,queue:!0,endpoint:w,fn_index:g}),L?.close(),r()))}}else if(U=="sse_v1"||U=="sse_v2"||U=="sse_v2.1"||U=="sse_v3"){o({type:"status",stage:"pending",queue:!0,endpoint:w,fn_index:g,time:new Date});let E="";typeof window<"u"&&typeof document<"u"&&(E=(D=window?.location)==null?void 0:D.hostname);const P=E.includes(".dev.")?`https://moon-${E.split(".")[1]}.dev.spaces.huggingface.tech`:"https://huggingface.co";(typeof window<"u"&&typeof document<"u"&&window.parent!=window&&window.supports_zerogpu_headers?sn("zerogpu-headers",P):Promise.resolve(null)).then(O=>V(`${l.root}${S}/${Pt}?${K}`,{...oe,session_hash:_},O)).then(async([O,I])=>{if(I===503)o({type:"status",stage:"error",message:Ge,queue:!0,endpoint:w,fn_index:g,time:new Date});else if(I===422)o({type:"status",stage:"error",message:O.detail,queue:!0,endpoint:w,fn_index:g,code:"validation_error",time:new Date}),r();else if(I!==200)o({type:"status",stage:"error",broken:!1,message:O.detail,queue:!0,endpoint:w,fn_index:g,time:new Date});else{k=O.event_id,Se=k;let C=async function(A){try{const{type:T,status:y,data:q,original_msg:nt}=ze(A,Pe[g]);if(T=="heartbeat")return;if(T==="update"&&y&&!B)o({type:"status",endpoint:w,fn_index:g,time:new Date,original_msg:nt,...y});else if(T==="complete")B=y;else if(T=="unexpected_error"||T=="broken_connection"){console.error("Unexpected error",y?.message);const st=T==="broken_connection";o({type:"status",stage:"error",message:y?.message||"An Unexpected Error Occurred!",queue:!0,endpoint:w,broken:st,session_not_found:y?.session_not_found,fn_index:g,time:new Date})}else if(T==="log"){o({type:"log",title:q.title,log:q.log,level:q.level,endpoint:w,duration:q.duration,visible:q.visible,fn_index:g});return}else(T==="generating"||T==="streaming")&&(o({type:"status",time:new Date,...y,stage:y?.stage,queue:!0,endpoint:w,fn_index:g}),q&&Z.connection!=="stream"&&["sse_v2","sse_v2.1","sse_v3"].includes(U)&&bn(b,k,q));q&&(o({type:"data",time:new Date,data:le(q.data,Z,l.components,"output",J.with_null_state),endpoint:w,fn_index:g}),q.render_config&&await Ce(q.render_config),B&&(o({type:"status",time:new Date,...B,stage:y?.stage,queue:!0,endpoint:w,fn_index:g}),r())),(y?.stage==="complete"||y?.stage==="error")&&(R[k]&&delete R[k],k in b&&delete b[k])}catch(T){console.error("Unexpected client exception",T),o({type:"status",stage:"error",message:"An Unexpected Error Occurred!",queue:!0,endpoint:w,fn_index:g,time:new Date}),["sse_v2","sse_v2.1","sse_v3"].includes(U)&&($e(W,H.abort_controller),W.open=!1,r())}};k in M&&(M[k].forEach(A=>C(A)),delete M[k]),R[k]=C,ue.add(k),W.open||await this.open_stream()}})}});let tt=!1;const de=[],Q=[],Te={[Symbol.asyncIterator]:()=>Te,next:u,throw:async m=>(p(m),u()),return:async()=>(r(),u()),cancel:Ye,event_id:Qe};return Te}catch(o){throw console.error("Submit function encountered an error:",o),o}}function Sn(e){return{then:(n,t)=>t(e)}}function Pn(e,n,t,s){let i,a,o;if(typeof n=="number")i=n,a=e.unnamed_endpoints[i],o=s.dependencies.find(r=>r.id==n);else{const r=n.replace(/^\//,"");i=t[r],a=e.named_endpoints[n.trim()],o=s.dependencies.find(c=>c.id==t[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}}class ve{constructor(n,t={events:["data"]}){d(this,"app_reference"),d(this,"options"),d(this,"deep_link",null),d(this,"config"),d(this,"api_prefix",""),d(this,"api_info"),d(this,"api_map",{}),d(this,"session_hash",Math.random().toString(36).substring(2)),d(this,"jwt",!1),d(this,"last_status",{}),d(this,"cookies",null),d(this,"stream_status",{open:!1}),d(this,"closed",!1),d(this,"pending_stream_messages",{}),d(this,"pending_diff_streams",{}),d(this,"event_callbacks",{}),d(this,"unclosed_events",new Set),d(this,"heartbeat_event",null),d(this,"abort_controller",null),d(this,"stream_instance",null),d(this,"current_payload"),d(this,"view_api"),d(this,"upload_files"),d(this,"upload"),d(this,"handle_blob"),d(this,"post_data"),d(this,"submit"),d(this,"predict"),d(this,"open_stream"),d(this,"resolve_config"),d(this,"resolve_cookies");var s;this.app_reference=n,this.deep_link=((s=t.query_params)==null?void 0:s.deep_link)||null,t.events||(t.events=["data"]),this.options=t,this.current_payload={},this.view_api=Xt.bind(this),this.upload_files=Yt.bind(this),this.handle_blob=an.bind(this),this.post_data=cn.bind(this),this.submit=xn.bind(this),this.predict=ln.bind(this),this.open_stream=yn.bind(this),this.resolve_config=Wt.bind(this),this.resolve_cookies=Mt.bind(this),this.upload=en.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(n=null){if(!this.config)throw new Error(G);n===null&&(n=window.location.href);const t=o=>o.replace(/^\/+|\/+$/g,"");let s=t(new URL(this.config.root).pathname),i=t(new URL(n).pathname),a;return i.startsWith(s)?a=t(i.substring(s.length)):a="",this.get_page_config(a)}get_page_config(n){if(!this.config)throw new Error(G);let t=this.config;return n in t.page||(n=""),{...t,current_page:n,layout:t.page[n].layout,components:t.components.filter(s=>t.page[n].components.includes(s.id)),dependencies:this.config.dependencies.filter(s=>t.page[n].dependencies.includes(s.id))}}fetch(n,t){const s=new Headers(t?.headers||{});if(this&&this.cookies&&s.append("Cookie",this.cookies),this&&this.options.headers)for(const i in this.options.headers)s.append(i,this.options.headers[i]);return fetch(n,{...t,headers:s})}stream(n){const t=new Headers;if(this&&this.cookies&&t.append("Cookie",this.cookies),this&&this.options.headers)for(const s in this.options.headers)t.append(s,this.options.headers[s]);return this&&this.options.token&&t.append("Authorization",`Bearer ${this.options.token}`),this.abort_controller=new AbortController,this.stream_instance=$n(n.toString(),{credentials:"include",headers:t,signal:this.abort_controller.signal}),this.stream_instance}async init(){var n;this.options.auth&&await this.resolve_cookies(),await this._resolve_config().then(({config:t})=>this._resolve_heartbeat(t)),this.api_info=await this.view_api(),this.api_map=Jt(((n=this.config)==null?void 0:n.dependencies)||[])}async _resolve_heartbeat(n){if(n&&(this.config=n,this.api_prefix=n.api_prefix||"",this.config&&this.config.connect_heartbeat&&this.config.space_id&&this.options.token&&(this.jwt=await Ae(this.config.space_id,this.options.token,this.cookies))),n.space_id&&this.options.token&&(this.jwt=await Ae(n.space_id,this.options.token)),this.config&&this.config.connect_heartbeat){const t=new URL(`${this.config.root}${this.api_prefix}/${Ot}/${this.session_hash}`);this.jwt&&t.searchParams.set("__sign",this.jwt),this.heartbeat_event||(this.heartbeat_event=this.stream(t))}}static async connect(n,t={events:["data"]}){const s=new this(n,t);return t.session_hash&&(s.session_hash=t.session_hash),await s.init(),s}async reconnect(){const n=new URL(`${this.config.root}${this.api_prefix}/${Nt}`);let t;try{const s=await this.fetch(n);if(!s.ok)throw new Error;t=(await s.json()).app_id}catch{return"broken"}return t!==this.config.app_id?"changed":"connected"}close(){this.closed=!0,$e(this.stream_status,this.abort_controller)}set_current_payload(n){this.current_payload=n}static async duplicate(n,t={events:["data"]}){return hn(n,t)}async _resolve_config(){const{http_protocol:n,host:t,space_id:s}=await Ee(this.app_reference,this.options.token),{status_callback:i}=this.options;s&&i&&await Ze(s,i);let a;try{let o=`${n}//${t}`;if(a=await this.resolve_config(o),!a)throw new Error(G);return this.config_success(a)}catch(o){if(s&&i)ie(s,be.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(n){if(this.config=n,this.api_prefix=n.api_prefix||"",this.config.auth_required)return this.prepare_return_obj();try{this.api_info=await this.view_api()}catch(t){console.error(Lt+t.message)}return this.prepare_return_obj()}async handle_space_success(n){var t;if(!this)throw new Error(G);const{status_callback:s}=this.options;if(s&&s(n),n.status==="running")try{if(this.config=await this._resolve_config(),this.api_prefix=((t=this==null?void 0:this.config)==null?void 0:t.api_prefix)||"",!this.config)throw new Error(G);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(n,t,s){var i;if(!this.config)throw new Error(G);const a={},{token:o}=this.options,{session_hash:r}=this;o&&(a.Authorization=`Bearer ${this.options.token}`);let c,p=this.config.components.find(u=>u.id===n);(i=p?.props)!=null&&i.root_url?c=p.props.root_url:c=this.config.root;let f;if("binary"in s){f=new FormData;for(const u in s.data)u!=="binary"&&f.append(u,s.data[u]);f.set("component_id",n.toString()),f.set("fn_name",t),f.set("session_hash",r)}else f=JSON.stringify({data:s,component_id:n,fn_name:t,session_hash:r}),a["Content-Type"]="application/json";o&&(a.Authorization=`Bearer ${o}`);try{const u=await this.fetch(`${c}${this.api_prefix}/${At}/`,{method:"POST",body:f,headers:a,credentials:"include"});if(!u.ok)throw new Error("Could not connect to component server: "+u.statusText);return await u.json()}catch(u){console.warn(u)}}set_cookies(n){this.cookies=Ve(n).join("; ")}prepare_return_obj(){return{config:this.config,predict:this.predict,submit:this.submit,view_api:this.view_api,component_server:this.component_server}}}var Cn=dt('<main class="svelte-1uha8ag"><h1 class="svelte-1uha8ag">Svelte App ➡️ Gradio Client API</h1> <form><label for="input-text" class="svelte-1uha8ag">Input Prompt:</label> <textarea id="input-text" class="svelte-1uha8ag"></textarea> <button type="submit" class="svelte-1uha8ag"><!></button></form> <div class="result-box svelte-1uha8ag"><h2>API Result</h2> <p> </p></div></main>');function zn(e,n){ut(n,!1);const t="your_huggingface_access_token_here",s="Hanzo03/gradioapp",i="/process_text";let a=re(""),o=re("Submit a prompt to see the result..."),r=re(!1),c=re(null);async function p(){try{z(c,await ve.connect(s,{token:t})),console.log("Gradio Client connected successfully!")}catch(b){console.error("Failed to connect to Gradio Client:",b),z(o,`Connection Error: Failed to connect to ${s}. Check your token and space ID.`),z(c,null)}}p();async function f(){if(!j(a).trim()){z(o,"Please enter some text.");return}if(!j(c)){z(o,"Error: Gradio Client not initialized. Check console for connection errors.");return}z(r,!0),z(o,"Processing...");try{const b=await j(c).predict(i,[j(a)]);z(o,b.data[0])}catch(b){console.error("Gradio API Prediction Error:",b),z(o,`API Prediction Error: ${b.message}`)}finally{z(r,!1)}}vt();var u=Cn(),h=ee(te(u),2),v=ee(te(h),2);ft(v);var N=ee(v,2),l=te(N);{var _=b=>{var R=he("Sending...");Y(b,R)},$=b=>{var R=_t(),ue=gt(R);{var V=S=>{var H=he("Connecting...");Y(S,H)},J=S=>{var H=he("Process Text");Y(S,H)};De(ue,S=>{j(c)?S(J,!1):S(V)},!0)}Y(b,R)};De(l,b=>{j(r)?b(_):b($,!1)})}ne(N),ne(h);var x=ee(h,2),W=ee(te(x),2),M=te(W,!0);ne(W),ne(x),ne(u),pt(()=>{v.disabled=j(r)||!j(c),N.disabled=j(r)||!j(c),wt(M,j(o))}),yt(v,()=>j(a),b=>z(a,b)),mt("submit",h,bt(f)),Y(e,u),ht()}export{zn as component};