loveaa commited on
Commit
77aeef0
·
verified ·
1 Parent(s): 90d354b

Deploy Home Pulse: grounded setup, isolated workspaces and shared HF visual inference

Browse files
.gitattributes CHANGED
@@ -1,6 +1,2 @@
1
  *.mp4 filter=lfs diff=lfs merge=lfs -text
2
  *.webm filter=lfs diff=lfs merge=lfs -text
3
- web/dist/media/posters/cat-active.jpg filter=lfs diff=lfs merge=lfs -text
4
- web/dist/media/posters/pkg-arrive.jpg filter=lfs diff=lfs merge=lfs -text
5
- web/dist/media/posters/pkg-taken.jpg filter=lfs diff=lfs merge=lfs -text
6
- web/dist/media/posters/porch-empty.jpg filter=lfs diff=lfs merge=lfs -text
 
1
  *.mp4 filter=lfs diff=lfs merge=lfs -text
2
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
app.py CHANGED
@@ -25,7 +25,7 @@ from starlette.background import BackgroundTask
25
  ROOT=Path(__file__).resolve().parent
26
  DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse'))
27
  INTERNAL_KEY=secrets.token_hex(32)
28
- NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','7861'))
29
  PORT=int(os.getenv('PORT','7860'))
30
  WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
31
  VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
@@ -33,7 +33,7 @@ os.environ.setdefault('TOKENIZERS_PARALLELISM','false')
33
  os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
34
  os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
35
  os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY,
36
- HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model')
37
 
38
  node=shutil.which('node')
39
  if not node: raise RuntimeError('Node.js is unavailable')
 
25
  ROOT=Path(__file__).resolve().parent
26
  DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse'))
27
  INTERNAL_KEY=secrets.token_hex(32)
28
+ NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','8791'))
29
  PORT=int(os.getenv('PORT','7860'))
30
  WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
31
  VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
 
33
  os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
34
  os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
35
  os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY,
36
+ HOME_PULSE_API_PORT=str(NODE_PORT),HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model')
37
 
38
  node=shutil.which('node')
39
  if not node: raise RuntimeError('Node.js is unavailable')
app_zerogpu.py CHANGED
@@ -22,7 +22,7 @@ from model_runtime import load_model, predict
22
  ROOT=Path(__file__).resolve().parent
23
  DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse'))
24
  INTERNAL_KEY=secrets.token_hex(32)
25
- NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','7861'))
26
  PORT=int(os.getenv('PORT','7860'))
27
  WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
28
  VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
@@ -30,7 +30,7 @@ os.environ.setdefault('TOKENIZERS_PARALLELISM','false')
30
  os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
31
  os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
32
  os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY,
33
- HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model')
34
 
35
  node=shutil.which('node')
36
  if not node: raise RuntimeError('Node.js is unavailable')
 
22
  ROOT=Path(__file__).resolve().parent
23
  DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse'))
24
  INTERNAL_KEY=secrets.token_hex(32)
25
+ NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','8791'))
26
  PORT=int(os.getenv('PORT','7860'))
27
  WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
28
  VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
 
30
  os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
31
  os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
32
  os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY,
33
+ HOME_PULSE_API_PORT=str(NODE_PORT),HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model')
34
 
35
  node=shutil.which('node')
36
  if not node: raise RuntimeError('Node.js is unavailable')
media-library/clips/negative_01.mp4 CHANGED
Binary files a/media-library/clips/negative_01.mp4 and b/media-library/clips/negative_01.mp4 differ
 
media-library/clips/negative_02.mp4 CHANGED
Binary files a/media-library/clips/negative_02.mp4 and b/media-library/clips/negative_02.mp4 differ
 
web/README.md CHANGED
@@ -144,3 +144,15 @@ node scripts/replay-decisions.mjs
144
  多标签页同步:关注、观察与通知变化通过浏览器存储事件同步;后台通知轮询先读取最新存档,本地引擎连接状态不再写回整份工作区,避免旧页面覆盖新证据。
145
 
146
  确认任务另在服务端保留最近60条观察,其中最近3条附带证据图;页面打开时恢复这些记录。界面缓存使用版本号与跨标签页同步,刷新后能恢复最新结果。最终75项自动测试及构建通过。
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  多标签页同步:关注、观察与通知变化通过浏览器存储事件同步;后台通知轮询先读取最新存档,本地引擎连接状态不再写回整份工作区,避免旧页面覆盖新证据。
145
 
146
  确认任务另在服务端保留最近60条观察,其中最近3条附带证据图;页面打开时恢复这些记录。界面缓存使用版本号与跨标签页同步,刷新后能恢复最新结果。最终75项自动测试及构建通过。
147
+
148
+
149
+ ## HF 在线体验(2026-10-14)
150
+
151
+ - 应用:https://loveaa-onealign.hf.space
152
+ - 源码:https://huggingface.co/spaces/loveaa/OneAlign/tree/main
153
+ - 经用户确认,复用原 OneAlign 免费 CPU Space。76 个旧文件及原提交保存在 `../output/hf-onealign-backup-20261014/`。
154
+ - Kimi 使用 HF Secret;imajev 使用作者公开 GPU Space 的 `/systemone` API,开启 calibration,保留访客的 HF 配额身份。
155
+ - 前端为现有 React 界面;规则引擎在 Node 中运行。每个浏览器的记忆、上传和统计通过随机空间凭据隔离。
156
+ - 云端源码位于 `../hf-space/`,打包与发布工具位于 `../deployment_tools/hf_publish.py`。上传清单排除 `.env.local`、本机记录、下载的权重与原始数据集。
157
+ - 免费空间的服务器文件为临时存储;记录可导出。连续观察期间需要保持观察页打开,共享 GPU 的排队和配额会影响实际采样间隔。
158
+ - 新建 ZeroGPU 被当前 HF 账号的实际 API 权限拒绝。`app_zerogpu.py` 保留将来自有 ZeroGPU 版本。
web/dist/assets/__vite-browser-external-Cgmn0awE-BM-zPBWh.js ADDED
@@ -0,0 +1 @@
 
 
1
+ import{t as r}from"./browser-B_i-TyAz.js";import"./index-B-txyBsD.js";var o=r(((e,t)=>{t.exports={}}));const m=o();export{m as default};
web/dist/assets/browser-B_i-TyAz.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/__vite-browser-external-Cgmn0awE-BM-zPBWh.js","assets/index-B-txyBsD.js","assets/index-BX_yyFR1.css"])))=>i.map(i=>d[i]);
2
+ import{_ as Ce}from"./index-B-txyBsD.js";var xt=Object.create,Xe=Object.defineProperty,Ot=Object.getOwnPropertyDescriptor,jt=Object.getOwnPropertyNames,Pt=Object.getPrototypeOf,Dt=Object.prototype.hasOwnProperty,rr=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Tt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=jt(t),a=0,i=s.length,o;a<i;a++)o=s[a],!Dt.call(e,o)&&o!==n&&Xe(e,o,{get:(l=>t[l]).bind(null,o),enumerable:!(r=Ot(t,o))||r.enumerable});return e},Ae=(e,t,n)=>(n=e==null?{}:xt(Pt(e)),Tt(Xe(n,"default",{value:e,enumerable:!0}),e)),Ct="host",et="queue/data",At="queue/join",Ne="upload",Nt="login",Ie="config",It="info",qt="runtime",Ut="sleeptime",zt="heartbeat",Lt="component_server",Rt="reset",Bt="cancel",Ft="app_id",tt="This application is currently busy. Please try again. ",q="Connection errored out. ",C="Could not resolve app config. ",Mt="Could not get space status. ",qe="Could not get API info. ",W="Space metadata could not be loaded. ",Jt="Invalid URL. A full URL path is required.",Gt="Not authorized to access this space. ",nt="Invalid credentials. Could not login. ",Wt="Could not access this app (received a 401 response). If it is a private Hugging Face Space, pass a valid Hugging Face token to the `token` option of `Client.connect`. You can generate a token at https://huggingface.co/settings/tokens.",Ht=(e,t)=>`Space "${e}" could not be accessed (received a ${t} response from the Hugging Face API). Check that the Space name is spelled correctly and that the Space exists. If the Space is private, pass a valid Hugging Face token to the \`token\` option of \`Client.connect\`. You can generate a token at https://huggingface.co/settings/tokens.`,Yt="No API information is available for this app. This can happen when the app's `/info` endpoint cannot be reached, or when the app is running a legacy version of Gradio that is not supported by this client. ",Zt="This app appears to be running a legacy version of Gradio (3.x or earlier) that communicates over WebSockets, which is not supported by this version of @gradio/client. Please upgrade the app to a newer version of Gradio, or connect to it with @gradio/client version 0.x.",Vt="File system access is only available in Node.js environments",rt="Root URL not found in client config",Kt="Error uploading file";async function Qt(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 st(e){e.hf_token&&!e.token&&(e.token=e.hf_token,console.warn("The `hf_token` option has been renamed to `token`. Support for `hf_token` will be removed in a future version of @gradio/client."))}function Ue(e){let t={};return e.forEach(({api_name:n,id:r})=>{n&&(t[n]=r)}),t}function Xt(e,t,n=!1){let r=new URL(t),s=new URL(e,r),a=s.hostname.endsWith(".colab-user-runtimes.internal")||s.hostname.endsWith(".codatalab-user-runtimes.internal");return n||a?new URL(new URL(e,r).pathname,r).toString().replace(/\/$/,""):s.hostname===r.hostname?(s.protocol=r.protocol,s.host=r.host,s.toString().replace(/\/$/,"")):e}async function en(e,t=!0){let n=this.options.token?{Authorization:`Bearer ${this.options.token}`}:{};if(typeof window<"u"&&window.gradio_config&&location.origin!=="http://localhost:9876"){if(t&&window.gradio_config.current_page&&(e=e.substring(0,e.lastIndexOf("/"))),window.gradio_config.dev_mode||typeof window<"u"&&window?.BUILD_MODE==="dev"){let s=new URL(ue(e,Ie));this.deep_link&&s.searchParams.set("deep_link",this.deep_link),this.page!==null&&s.searchParams.set("page",this.page);let a=await ze(await this.fetch(s,{headers:n,credentials:this.options.credentials??"same-origin"}),!!this.options.auth);a.root=e||a.root,window.gradio_config={...a,current_page:window.gradio_config.current_page}}let r={...window.gradio_config};return r.root=Xt(r.root,location.href,r.is_colab),r}else if(e){let r=new URL(ue(e,Ie));this.deep_link&&r.searchParams.set("deep_link",this.deep_link),this.page!==null&&r.searchParams.set("page",this.page);let s=await ze(await this.fetch(r,{headers:n,credentials:this.options.credentials??"same-origin"}),!!this.options.auth);return s.root||=e,s}throw Error(C)}async function ze(e,t){if(e?.status===401&&!t){let n=null;try{n=await e.json()}catch{throw Error(Wt)}let r=n?.detail?.auth_message;throw Error(r||"Login credentials are required to access this space.")}else if(e?.status===401&&t)throw Error(nt);if(e?.status===200){let n=await e.json();return n.dependencies?.forEach((r,s)=>{r.id===void 0&&(r.id=s)}),n}else if(e?.status===401)throw Error(Gt);throw Error(`${C}(received status ${e?.status} when fetching the app config)`)}async function tn(){let{http_protocol:e,host:t}=await he(this.app_reference,this.options.token);try{if(this.options.auth){let n=await at(e,t,this.options.auth,this.fetch,this.options.token,this.options.credentials);n&&this.set_cookies(n)}}catch(n){throw Error(n.message)}}async function at(e,t,n,r,s,a){let i=new FormData;i.append("username",n?.[0]),i.append("password",n?.[1]);let o={};s&&(o.Authorization=`Bearer ${s}`);let l=await r(`${e}//${t}/${Nt}`,{headers:o,method:"POST",body:i,credentials:a??"same-origin"});if(l.status===200)return l.headers.get("set-cookie");throw l.status===401?Error(nt):Error(W)}function ce(e){if(e.startsWith("http")){let{protocol:t,host:n,pathname:r}=new URL(e);return{ws_protocol:t==="https:"?"wss":"ws",http_protocol:t,host:n+(r==="/"?"":r)}}return{ws_protocol:"wss",http_protocol:"https:",host:new URL(e).host}}var it=e=>{let t=[];return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach(n=>{let[r,s]=n.split(";")[0].split("=");r&&s&&t.push(`${r.trim()}=${s.trim()}`)}),t},de=/^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/,nn=/.*hf\.space\/{0,1}.*$/;async function he(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);let r=e.trim().replace(/\/$/,"");if(de.test(r)){let s;try{s=await fetch(`https://huggingface.co/api/spaces/${r}/${Ct}`,{headers:n})}catch{throw Error(W)}if(s.status===401||s.status===404)throw Error(Ht(r,s.status));let a;try{a=(await s.json()).host}catch{throw Error(W)}if(!a)throw Error(W);return{space_id:r,...ce(a)}}if(nn.test(r)){let{ws_protocol:s,http_protocol:a,host:i}=ce(r);return{space_id:i.split("/")[0].replace(".hf.space",""),ws_protocol:s,http_protocol:a,host:i}}return{space_id:!1,...ce(r)}}var ue=(...e)=>{try{return e.reduce((t,n)=>(t=t.replace(/\/+$/,""),n=n.replace(/^\/+/,""),new URL(n,t+"/").toString()))}catch{throw Error(Jt)}};function rn(e,t,n){let r={named_endpoints:{},unnamed_endpoints:{}};return Object.keys(e).forEach(s=>{(s==="named_endpoints"||s==="unnamed_endpoints")&&(r[s]={},Object.entries(e[s]).forEach(([a,i])=>{let o=i?.parameters??[],l=i?.returns??[],c=t.dependencies.find(f=>f.api_name===a||f.api_name===a.replace("/",""))?.id||n[a.replace("/","")]||-1,u=c===-1?void 0:t.dependencies.find(f=>f.id==c),d=c===-1?{generator:!1,cancel:!1}:u?.types;if(u&&Array.isArray(u.inputs)&&u.inputs.length!==o.length){let f=u.inputs.map($=>t.components.find(_=>_.id===$)?.type);try{f.forEach(($,_)=>{$==="state"&&o.splice(_,0,{component:"state",example:null,parameter_default:null,parameter_has_default:!0,parameter_name:null,hidden:!0})})}catch($){console.error($)}}let m=(f,$,_,U)=>({...f,description:an(f?.type,_),type:sn(f?.type,$,_,U)||""});r[s][a]={parameters:o.map(f=>m(f,f?.component,f?.serializer,"parameter")),returns:l.map(f=>m(f,f?.component,f?.serializer,"return")),type:d,...i?.oauth_token?{oauth_token:i.oauth_token}:{}}}))}),r}function sn(e,t,n,r){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 r==="parameter"?"Blob | File | Buffer":"string";if(n==="FileSerializable")return e?.type==="array"?r==="parameter"?"(Blob | File | Buffer)[]":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]":r==="parameter"?"Blob | File | Buffer":"{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";if(n==="GallerySerializable")return r==="parameter"?"[(Blob | File | Buffer), (string | null)][]":"[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]"}function an(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 Le(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:tt,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,changed_state_ids:e.output.changed_state_ids,eta:e.eta},data:e.output};case"process_completed":return"error"in e.output?{type:"update",status:{queue:!0,title:e.output.title??"Error",message:e.output.error??"An error occurred",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,used_cache:e.used_cache,cache_duration:e.cache_duration,avg_time:e.avg_time},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 on=(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 r=[],s=Object.keys(e);return n.forEach((a,i)=>{if(e.hasOwnProperty(a.parameter_name))r[i]=e[a.parameter_name];else if(a.parameter_has_default)r[i]=a.parameter_default;else throw Error(`No value provided for required parameter: ${a.parameter_name}`)}),s.forEach(a=>{if(!n.some(i=>i.parameter_name===a))throw Error(`Parameter \`${a}\` is not a valid keyword argument. Please refer to the API for usage.`)}),r.forEach((a,i)=>{if(a===void 0&&!n[i].parameter_has_default)throw Error(`No value provided for required parameter: ${n[i].parameter_name}`)}),r};async function cn(){if(this.api_info)return this.api_info;let{token:e}=this.options,{config:t}=this,n={};if(e&&(n.Authorization=`Bearer ${e}`),t)try{let r,s;if(typeof window<"u"&&window.gradio_api_info)s=window.gradio_api_info;else{let a=new URL(ue(t.root,this.api_prefix,It));if(this.page!==null&&a.searchParams.set("page",this.page),r=await this.fetch(a,{headers:n,credentials:this.options.credentials??"same-origin"}),!r.ok)throw Error(q);s=await r.json()}return"api"in s&&(s=s.api),s.named_endpoints["/predict"]&&!s.unnamed_endpoints[0]&&(s.unnamed_endpoints[0]=s.named_endpoints["/predict"]),rn(s,t,this.api_map)}catch(r){throw Error("Could not get API info. "+r.message)}}async function ln(e,t,n){let r={};this?.options?.token&&(r.Authorization=`Bearer ${this.options.token}`);let s=1e3,a=[],i;for(let o=0;o<t.length;o+=s){let l=t.slice(o,o+s),c=new FormData;l.forEach(d=>{c.append("files",d)});try{let d=n?`${e}${this.api_prefix}/${Ne}?upload_id=${n}`:`${e}${this.api_prefix}/${Ne}`;i=await this.fetch(d,{method:"POST",body:c,headers:r,credentials:this.options.credentials??"same-origin"})}catch(d){throw Error(q+d.message)}if(!i.ok){let d=await i.text();return{error:`HTTP ${i.status}: ${d}`}}let u=await i.json();u&&a.push(...u)}return{files:a}}var Re={si:{radix:1e3,unit:["b","kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb"]},iec:{radix:1024,unit:["b","Kib","Mib","Gib","Tib","Pib","Eib","Zib","Yib"]},jedec:{radix:1024,unit:["b","Kb","Mb","Gb","Tb","Pb","Eb","Zb","Yb"]}};function un(e,t=1,n="jedec"){e=Math.abs(e);let{radix:r,unit:s}=Re[n]||Re.jedec,a=0;for(;e>=r;)e/=r,++a;return`${e.toFixed(t)} ${s[a]}`}async function pn(e,t,n,r){let s=(Array.isArray(e)?e:[e]).map(i=>i.blob),a=s.filter(i=>i.size>(r??1/0));if(a.length)throw Error(`File(s) exceed the maximum allowed size of ${un(r||1/0)}: ${a.map(i=>`"${i.name}"`).join(", ")}`);return await Promise.all(await this.upload_files(t,s,n).then(async i=>{if(i.error)throw Error(i.error);return i.files?i.files.map((o,l)=>{let c=o.split("/").map(u=>encodeURIComponent(u)).join("/");return new fe({...e[l],path:o,url:`${t}${this.api_prefix}/file=${c}`})}):[]}))}var fe=class{path;url;orig_name;size;blob;is_stream;mime_type;alt_text;b64;meta={_type:"gradio.FileData"};constructor({path:e,url:t,orig_name:n,size:r,blob:s,is_stream:a,mime_type:i,alt_text:o,b64:l}){this.path=e,this.url=t,this.orig_name=n,this.size=r,this.blob=t?void 0:s,this.is_stream=a,this.mime_type=i,this.alt_text=o,this.b64=l}},dn=class{type;command;meta;fileData;constructor(e,t){this.type="command",this.command=e,this.meta=t}};typeof process<"u"&&process.versions&&process.versions.node;function Be(e,t,n){for(;n.length>1;){let s=n.shift();if(typeof s=="string"||typeof s=="number")e=e[s];else throw Error("Invalid key type")}let r=n.shift();if(typeof r=="string"||typeof r=="number")e[r]=t;else throw Error("Invalid key type")}async function pe(e,t=void 0,n=[],r=!1,s=void 0){if(Array.isArray(e)){let a=[];return await Promise.all(e.map(async(i,o)=>{let l=n.slice();l.push(String(o));let c=await pe(e[o],r?s?.parameters[o]?.component||void 0:t,l,!1,s);a=a.concat(c)})),a}else{if(globalThis.Buffer&&e instanceof globalThis.Buffer||e instanceof Blob)return[{path:n,blob:e instanceof Blob?e:new Blob([e]),type:t}];if(typeof e=="object"&&e){let a=[];for(let i of Object.keys(e)){let o=[...n,i],l=e[i];a=a.concat(await pe(l,void 0,o,!1,s))}return a}}return[]}function Fe(e,t){let n=t?.dependencies?.find(r=>r.id==e)?.queue;return n==null?!t.enable_queue:!n}function hn(e,t){return new Promise((n,r)=>{let s=new MessageChannel;s.port1.onmessage=(({data:a})=>{s.port1.close(),n(a)}),window.parent.postMessage(e,t,[s.port2])})}function J(e,t,n,r,s=!1){if(r==="input"&&!s)throw Error("Invalid code path. Cannot skip state inputs for input.");if(r==="output"&&s)return e;let a=[],i=0,o=r==="input"?t.inputs:t.outputs;for(let l=0;l<o.length;l++){let c=o[l];if(n.find(u=>u.id===c)?.type==="state"){if(s)if(e.length===o.length){let u=e[i];a.push(u),i++}else a.push(null);else{i++;continue}continue}else{let u=e[i];a.push(u),i++}}return a}var fn=["/file=","/file/","/stream/","/proxy="];function ge(e,t,n,r){if(!r||typeof e!="object"||!e)return;let s=r,a=new URL(t),i=a.pathname.replace(/\/+$/,""),o=n?`/${n.replace(/^\/+|\/+$/g,"")}`:"",l=new Set([`${i}${o}`,o]);o||(l.add(`${i}/gradio_api`),l.add("/gradio_api"));function c(u){if(typeof u!="object"||!u)return;let d=u;if(d.meta?._type==="gradio.FileData"&&typeof d.url=="string"){let m=new URL(d.url,`${a.toString().replace(/\/$/,"")}/`),f=[...l].some($=>fn.some(_=>m.pathname.startsWith(`${$}${_}`)));(m.protocol==="http:"||m.protocol==="https:")&&m.origin===a.origin&&f&&(m.searchParams.set("__sign",s),d.url=m.toString())}for(let m of Object.values(d))c(m)}c(e)}function Me(e,t){for(let n of e.components||[])ge(n.props?.value,e.root,e.api_prefix||"",t)}async function gn(e,t,n){let r=this;await _n(r,t);let s=await pe(t,void 0,[],!0,n);return(await Promise.all(s.map(async({path:a,blob:i,type:o})=>{if(!i)return{path:a,type:o};let l=await r.upload_files(e,[i]);return{path:a,file_url:l.files&&l.files[0],type:o,name:typeof File<"u"&&i instanceof File?i?.name:void 0}}))).forEach(({path:a,file_url:i,type:o,name:l})=>{o==="Gallery"?Be(t,i,a):i&&Be(t,new fe({path:i,orig_name:l}),a)}),t}async function _n(e,t){if(!(e.config?.root||e.config?.root_url))throw Error(rt);await ot(e,t)}async function ot(e,t,n=[]){for(let r in t)t[r]instanceof dn?await mn(e,t,r):typeof t[r]=="object"&&t[r]!==null&&await ot(e,t[r],[...n,r])}async function mn(e,t,n){let r=t[n],s=e.config?.root||e.config?.root_url;if(!s)throw Error(rt);try{let a,i;if(typeof process<"u"&&process.versions&&process.versions.node){let u=await Ce(()=>import("./__vite-browser-external-Cgmn0awE-BM-zPBWh.js"),__vite__mapDeps([0,1,2])).then(d=>Ae(d.default,1));i=(await Ce(()=>import("./__vite-browser-external-Cgmn0awE-BM-zPBWh.js"),__vite__mapDeps([0,1,2])).then(d=>Ae(d.default,1))).resolve(process.cwd(),r.meta.path),a=await u.readFile(i)}else throw Error(Vt);let o=new Blob([a],{type:"application/octet-stream"}),l=await e.upload_files(s,[o]),c=l.files&&l.files[0];c&&(t[n]=new fe({path:c,orig_name:r.meta.name||""}))}catch(a){console.error(Kt,a)}}async function wn(e,t,n){let r={"Content-Type":"application/json"};this.options.token&&(r.Authorization=`Bearer ${this.options.token}`);try{var s=await this.fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...r,...n},credentials:this.options.credentials??"same-origin"})}catch{return[{error:q},500]}let a,i;try{a=await s.json(),i=s.status}catch(o){a={error:`Could not parse server response: ${o}`},i=500}return[a,i]}async function yn(e,t={}){let n=!1,r=!1;if(!this.config)throw 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(o=>o.id==this.api_map[i])}let s=this.submit(e,t,null,null,!0),a;for await(let i of s){if(i.type==="data"&&(n=!0,a=i,r))return a;if(i.type==="status"){if(i.stage==="error"){let{message:o,...l}=i,c=Error((typeof o=="string"?o:o&&JSON.stringify(o))||"An unknown error occurred while making a prediction.");throw Object.assign(c,l),c}if(i.stage==="complete"&&(r=!0,n))return a}}return a}async function H(e,t,n){let r=t==="subdomain"?`https://huggingface.co/api/spaces/by-subdomain/${e}`:`https://huggingface.co/api/spaces/${e}`,s,a;try{if(s=await fetch(r),a=s.status,a!==200)throw Error();s=await s.json()}catch{n({status:"error",load_status:"error",message:Mt,detail:"NOT_FOUND"});return}if(!s||a!==200)return;let{runtime:{stage:i},id:o}=s;switch(i){case"STOPPED":case"SLEEPING":n({status:"sleeping",load_status:"pending",message:"Space is asleep. Waking it up...",detail:i}),setTimeout(()=>{H(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:i,discussions_enabled:await Je(o)});break;case"RUNNING":case"RUNNING_BUILDING":n({status:"running",load_status:"complete",message:"Space is running.",detail:i});break;case"BUILDING":n({status:"building",load_status:"pending",message:"Space is building...",detail:i}),setTimeout(()=>{H(e,t,n)},1e3);break;case"APP_STARTING":n({status:"starting",load_status:"pending",message:"Space is starting...",detail:i}),setTimeout(()=>{H(e,t,n)},1e3);break;default:n({status:"space_error",load_status:"error",message:"This space is experiencing an issue.",detail:i,discussions_enabled:await Je(o)});break}}var ct=async(e,t)=>{let n=0;return new Promise(r=>{H(e,de.test(e)?"space_name":"subdomain",s=>{t(s),s.status==="running"||s.status==="error"||s.status==="paused"||s.status==="space_error"?r():(s.status==="sleeping"||s.status==="building")&&(n<12?(n++,setTimeout(()=>{ct(e,t).then(r)},5e3)):r())})})},bn=/^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;async function Je(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&&bn.test(n))}catch{return!1}}async function vn(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);try{let r=await fetch(`https://huggingface.co/api/spaces/${e}/${qt}`,{headers:n});if(r.status!==200)throw Error("Space hardware could not be obtained.");let{hardware:s}=await r.json();return s.current}catch(r){throw Error(r.message)}}async function $n(e,t,n){let r={};n&&(r.Authorization=`Bearer ${n}`);let s={seconds:t};try{let a=await fetch(`https://huggingface.co/api/spaces/${e}/${Ut}`,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(s)});if(a.status!==200)throw 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 Error(a.message)}}var Ge=["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 kn(e,t){st(t);let{token:n,private:r,hardware:s,timeout:a,auth:i}=t;if(s&&!Ge.includes(s))throw Error(`Invalid hardware type provided. Valid types are: ${Ge.map(_=>`"${_}"`).join(",")}.`);let{http_protocol:o,host:l}=await he(e,n),c=null;if(i){let _=await at(o,l,i,fetch,void 0,t.credentials);_&&(c=it(_))}let u={Authorization:`Bearer ${n}`,"Content-Type":"application/json",...c?{Cookie:c.join("; ")}:{}},d=(await(await fetch("https://huggingface.co/api/whoami-v2",{headers:u})).json()).name,m=e.split("/")[1],f={repository:`${d}/${m}`};r&&(f.private=!0);let $;try{s||($=await vn(e,n))}catch(_){throw Error(W+_.message)}f.hardware=s||$||"cpu-basic";try{let _=await fetch(`https://huggingface.co/api/spaces/${e}/duplicate`,{method:"POST",headers:u,body:JSON.stringify(f)});if(_.status===409)try{return await Qe.connect(`${d}/${m}`,t)}catch(Q){throw console.error("Failed to connect Client instance:",Q),Q}else if(_.status!==200)throw Error(_.statusText);let U=await _.json();return await $n(`${d}/${m}`,a||300,n),await Qe.connect(Sn(U.url),t)}catch(_){throw Error(_)}}function Sn(e){let t=e.match(/https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/);if(t)return t[1]}var We="supports-zerogpu-headers",He=!1;function En(){return typeof window<"u"&&typeof document<"u"&&typeof window.addEventListener=="function"}function lt(e){return e.includes(".dev.")?`https://moon-${e.split(".")[1]}.dev.spaces.huggingface.tech`:e.endsWith(".hf.space")?"https://huggingface.co":null}function xn(){if(!En()||He)return;window.addEventListener("message",t=>{t.data===We&&(window.supports_zerogpu_headers=!0)}),He=!0;let e=lt(window.location.hostname);e&&window.parent!==window&&window.parent.postMessage(We,e)}var On=class extends TransformStream{#e="";constructor(e={allowCR:!1}){super({transform:(t,n)=>{for(t=this.#e+t;;){let r=t.indexOf(`
3
+ `),s=e.allowCR?t.indexOf("\r"):-1;if(s!==-1&&s!==t.length-1&&(r===-1||r-1>s)){n.enqueue(t.slice(0,s)),t=t.slice(s+1);continue}if(r===-1)break;let a=t[r-1]==="\r"?r-1:r;n.enqueue(t.slice(0,a)),t=t.slice(r+1)}this.#e=t},flush:t=>{if(this.#e==="")return;let n=e.allowCR&&this.#e.endsWith("\r")?this.#e.slice(0,-1):this.#e;t.enqueue(n)}})}};function jn(e){let t=new TextDecoderStream,n=new On({allowCR:!0});return e.pipeThrough(t).pipeThrough(n)}function Pn(e){let t=/[:]\s*/.exec(e),n=t&&t.index;if(n)return[e.substring(0,n),e.substring(n+t[0].length)]}function Ye(e,t,n){e.get(t)||e.set(t,n)}async function*Dn(e,t){if(!e.body)return;let n=jn(e.body),r,s=n.getReader(),a;for(;;){if(t&&t.aborted)return s.cancel();if(r=await s.read(),r.done)return;if(!r.value){a&&(yield a),a=void 0;continue}let[i,o]=Pn(r.value)||[];i==="data"?(a||={},a[i]=a[i]?a[i]+`
4
+ `+o:o):i==="event"?(a||={},a[i]=o):i==="id"?(a||={},a[i]=String(+o)===o?+o:o):i==="retry"&&(a||={},a[i]=+o||void 0)}}async function Tn(e,t){let n=new Request(e,t);Ye(n.headers,"Accept","text/event-stream"),Ye(n.headers,"Content-Type","application/json");let r=await fetch(n);if(!r.ok)throw r;return Dn(r,n.signal)}async function Cn(){let{event_callbacks:e,unclosed_events:t,pending_stream_messages:n,stream_status:r,config:s,jwt:a}=this,i=this;if(!s)throw Error("Could not resolve app config");r.open=!0;let o=null,l=new URLSearchParams({session_hash:this.session_hash}).toString(),c=new URL(`${s.root}${this.api_prefix}/${et}?${l}`);if(a&&c.searchParams.set("__sign",a),o=this.stream(c),!o){console.warn("Cannot connect to SSE endpoint: "+c.toString());return}o.onmessage=async function(u){let d=JSON.parse(u.data);if(d.msg==="close_stream"){_e(r,i.abort_controller);return}let m=d.event_id;if(!m)await Promise.all(Object.keys(e).map(f=>e[f](d)));else if(e[m]&&s){d.msg==="process_completed"&&["sse","sse_v1","sse_v2","sse_v2.1","sse_v3"].includes(s.protocol)&&t.delete(m);let f=e[m];typeof window<"u"&&typeof document<"u"&&document.visibilityState!=="hidden"?setTimeout(f,0,d):f(d)}else n[m]||(n[m]=[]),n[m].push(d)},o.onerror=async function(u){console.error(u),await Promise.all(Object.keys(e).map(d=>e[d]({msg:"broken_connection",message:q})))}}function _e(e,t){e&&(e.open=!1,t?.abort())}function An(e,t,n){e[t]?n.data.forEach((r,s)=>{let a=Nn(s<e[t].length?e[t][s]:null,r);e[t][s]=a,n.data[s]=a}):(e[t]=[],n.data.forEach((r,s)=>{e[t][s]=r}))}function Nn(e,t){return t.forEach(([n,r,s])=>{e=In(e,r,n,s)}),e}function In(e,t,n,r){if(t.length===0){if(n==="replace")return r;if(n==="append")return e+r;throw Error(`Unsupported action: ${n}`)}let s=e;for(let i=0;i<t.length-1;i++)s=s[t[i]];let a=t[t.length-1];switch(n){case"replace":s[a]=r;break;case"append":s[a]+=r;break;case"add":Array.isArray(s)?s.splice(Number(a),0,r):s[a]=r;break;case"delete":Array.isArray(s)?s.splice(Number(a),1):delete s[a];break;default:throw Error(`Unknown action: ${n}`)}return e}function qn(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 Error("Method not implemented.")},dispatchEvent:()=>{throw Error("Method not implemented.")},removeEventListener:()=>{throw Error("Method not implemented.")}};return Tn(e,t).then(async r=>{n.readyState=n.OPEN;try{for await(let s of r)n.onmessage&&n.onmessage(s);n.readyState=n.CLOSED}catch(s){n.onerror&&n.onerror(s),n.readyState=n.CLOSED}}).catch(r=>{console.error(r),n.onerror&&n.onerror(r),n.readyState=n.CLOSED}),n}var ne="gradio:run-history:",Y=`${ne}v2:`,Ze=`${ne}replay:v2:`,ut=`${ne}destination:v1:`,Un=100,zn=8;function V(e,t){try{return e()}catch(n){return console.warn("Could not update the run history.",n),t}}function K(e){if(typeof window>"u")return null;let t=e?.app_id;if(t==null||t==="")return null;try{return window.localStorage?`${Y}${t}${e?.username?`:user:${encodeURIComponent(e.username)}`:""}`:null}catch{return null}}function Ln(e){let t=K(e);return t?t.replace(Y,ut):null}function pt(e){let t=Ln(e);if(!t)return{type:"browser"};try{let n=JSON.parse(window.localStorage.getItem(t)||"null");return typeof n?.bucket_id=="string"?n.type==="bucket"?{type:"bucket",bucket_id:n.bucket_id}:{type:"browser",bucket_id:n.bucket_id}:{type:"browser"}}catch{return{type:"browser"}}}function Ve(e){try{let t=JSON.parse(window.localStorage.getItem(e)||"[]");return Array.isArray(t)&&t.length&&Date.parse(t[0]?.started_at)||0}catch{return 0}}function dt(e){let t=Object.keys(window.localStorage).filter(r=>r.startsWith(ne)),n=[...t.filter(r=>!r.startsWith(Y)&&!r.startsWith(Ze)&&!r.startsWith(ut)),...t.filter(r=>r.startsWith(Y)&&r!==e).sort((r,s)=>Ve(s)-Ve(r)).slice(zn-1)];for(let r of n)try{window.localStorage.removeItem(r),window.sessionStorage.removeItem(r.replace(Y,Ze))}catch{}}function Rn(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function Z(e){let t=new WeakSet;try{return JSON.parse(JSON.stringify(e,(n,r)=>{if(typeof r=="bigint")return r.toString();if(typeof r=="object"&&r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch{return"[Unserializable value]"}}function me(e){let t=K(e);if(!t)return[];try{let n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n:[]}catch{return[]}}function we(e,t){let n=K(e);if(!n)return;let r=t.slice(0,Un),s=!1;for(;r.length>0;)try{window.localStorage.setItem(n,JSON.stringify(r));return}catch{if(!s){s=!0,dt(n);continue}r=r.slice(0,-1)}try{window.localStorage.removeItem(n)}catch{}}function Bn(e){let t=K(e);if(t){try{window.localStorage.removeItem(t)}catch{}ht()}}var Fn="gradio:run-history-change";function ht(){if(!(typeof window>"u"))try{window.dispatchEvent(new Event(Fn))}catch{}}function Mn(e){if(pt(e).type==="bucket")return null;let t=K(e);if(!t)return null;dt(t);let n={id:Rn(),endpoint:e.endpoint,api_name:e.api_name,fn_index:e.fn_index,page:`${window.location.pathname}${window.location.search}`,inputs:Z(e.inputs),outputs:null,...e.input_components?{input_components:Z(e.input_components)}:{},...e.output_components?{output_components:Z(e.output_components)}:{},status:"running",started_at:new Date().toISOString()};return we(e,[n,...me(e)]),ht(),n.id}function Jn(e,t,n){if(!t)return;let r=me(e),s=r.find(a=>a.id===t);s&&(s.inputs=Z(n),we(e,r))}function Gn(e,t,n){if(!t)return;let r=me(e),s=r.find(i=>i.id===t);if(!s)return;let a=!1;if(n.type==="data")s.outputs=Z(n.data),G.set(t,s.outputs);else if(n.type==="status"&&n.original_msg==="process_starts")Hn(s,n.time);else if(n.type==="status"&&(n.stage==="generating"||n.stage==="streaming"))s.streamed=!0;else if(n.type==="status"&&n.stage==="complete")s.status="completed",Ke(s,n),a=!0;else if(n.type==="status"&&n.stage==="error")s.status="failed",s.error=typeof n.message=="string"?n.message:JSON.stringify(n.message||"Unknown error"),Ke(s,n),a=!0;else return;if(a)G.has(t)&&(s.outputs=G.get(t)),G.delete(t),le.delete(t);else if(s.streamed){if(Date.now()-(le.get(t)??0)<Wn)return;le.set(t,Date.now()),G.delete(t)}we(e,r)}var Wn=500,le=new Map,G=new Map;function Hn(e,t){if(e.process_started_at)return;let n=t||new Date;e.process_started_at=n.toISOString(),e.queued_ms=Math.max(0,n.getTime()-Date.parse(e.started_at))}function Ke(e,t){let n=t.time||new Date;e.completed_at=n.toISOString(),e.duration_ms=(!e.streamed&&typeof t.cache_duration=="number"&&t.cache_duration>=0?t.cache_duration*1e3:null)??Math.max(0,n.getTime()-Date.parse(e.process_started_at||e.started_at))}function Yn(e){return V(()=>pt(e),{type:"browser"})}function Zn(e){V(()=>Bn(e),void 0)}function Vn(e){return V(()=>Mn(e),null)}function Kn(e,t,n){V(()=>Jn(e,t,n),void 0)}function Qn(e,t,n){V(()=>Gn(e,t,n),void 0)}function Xn(e,t={},n,r,s,a){try{let w=function(p){Qn(X,Se,p),(p.type==="data"||p.type==="render")&&ge(p.data,gt,A,ye.jwt),(s||yt[p.type])&&kt(p)},O=function(){for(Oe=!0;F.length>0;)F.shift()({value:void 0,done:!0})},je=function(p){F.length>0?F.shift()(p):oe.push(p)},$t=function(p){je(er(p)),O()},kt=function(p){je({value:p,done:!1})},Pe=function(){return oe.length>0?Promise.resolve(oe.shift()):Oe?Promise.resolve({value:void 0,done:!0}):new Promise(p=>F.push(p))},{token:i}=this.options,{fetch:o,app_reference:l,config:c,session_hash:u,api_info:d,api_map:m,stream_status:f,pending_stream_messages:$,pending_diff_streams:_,event_callbacks:U,unclosed_events:Q,post_data:re,options:z,api_prefix:A}=this,ft=a||{"x-gradio-user":"api"},ye=this;if(!d)throw Error(Yt);if(!c)throw Error("Could not resolve app config");let gt=c.root,{fn_index:h,endpoint_info:se,dependency:x}=tr(d,e,m,c),be=on(t,se),N=c.protocol??"ws";if(N==="ws")throw Error(Zt);let _t=typeof x.api_name=="string"?`/${x.api_name}`:e,mt=typeof x.api_name=="string"?`/${x.api_name}`:`Function ${h}`,ve=p=>{let b=c.components.find(M=>M.id===p);return b?{type:b.type,component_class_id:b.component_class_id,props:b.props}:null},wt=x.api_visibility==="public",$e=c.run_history!==!1&&this.options.record_history!==!1,X={app_id:c.app_id,username:c.username},ke=Yn(X),ae={...ft,...$e&&ke.type==="bucket"?{"x-gradio-history-bucket":ke.bucket_id}:{}},Se=!$e||!wt?null:Vn({...X,endpoint:_t,api_name:mt,fn_index:h,inputs:J(be,x,c.components,"input",!0),input_components:x.inputs.map(ve),output_components:x.outputs.map(ve)}),L,R="",g=typeof e=="number"?"/predict":e,ee,k=null,I=!1,Ee={},B=typeof window<"u"&&typeof document<"u"?new URLSearchParams(window.location.search).toString():"",yt=z?.events?.reduce((p,b)=>(p[b]=!0,p),{})||{};async function bt(){let p={},b={};p={event_id:k},b={event_id:k,session_hash:u,fn_index:h};try{if(!c)throw Error("Could not resolve app config");"event_id"in b&&await o(`${c.root}${A}/${Bt}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(b)}),await o(`${c.root}${A}/${Rt}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify(p)})}catch{console.warn("The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable.")}}let vt=async p=>{await this._resolve_heartbeat(p)};async function xe(p){if(!c)return;let b=p.render_id;c.components=[...c.components.filter(E=>E.props.rendered_in!==b),...p.components],c.dependencies=[...c.dependencies.filter(E=>E.rendered_in!==b),...p.dependencies];let M=c.components.some(E=>E.type==="state"),v=c.dependencies.some(E=>E.targets.some(y=>y[1]==="unload"));c.connect_heartbeat=M||v,await vt(c),w({type:"render",data:p,endpoint:g,fn_index:h})}let ie=this.handle_blob(c.root,be,se).then(async p=>{let b=J(p,x,c.components,"input",!0);if(Kn(X,Se,b||[]),ee={data:b||[],event_data:n,fn_index:h,trigger_id:r,...z.oauth_token&&se?.oauth_token?{oauth_token:z.oauth_token}:{}},Fe(h,c))w({type:"status",endpoint:g,stage:"pending",queue:!1,fn_index:h,time:new Date}),re(`${c.root}${A}/run${g.startsWith("/")?g:`/${g}`}${B?"?"+B:""}`,{...ee,session_hash:u},ae).then(async([v,E])=>{let y=v.data;if(E==200)w({type:"data",endpoint:g,fn_index:h,data:J(y,x,c.components,"output",z.with_null_state),time:new Date,event_data:n,trigger_id:r}),v.render_config&&await xe(v.render_config),w({type:"status",endpoint:g,fn_index:h,stage:"complete",eta:v.average_duration,queue:!1,time:new Date});else{let S=v?.error===q;w({type:"status",stage:"error",endpoint:g,fn_index:h,message:v.error,broken:S,queue:!1,time:new Date})}}).catch(v=>{w({type:"status",stage:"error",message:v.message,endpoint:g,fn_index:h,queue:!1,time:new Date})});else if(N=="sse"){w({type:"status",stage:"pending",queue:!0,endpoint:g,fn_index:h,time:new Date});var M=new URLSearchParams({fn_index:h.toString(),session_hash:u}).toString();let v=new URL(`${c.root}${A}/${et}?${B?B+"&":""}${M}`);if(this.jwt&&v.searchParams.set("__sign",this.jwt),L=this.stream(v),!L)return Promise.reject(Error("Cannot connect to SSE endpoint: "+v.toString()));L.onmessage=async function(E){let{type:y,status:S,data:j}=Le(JSON.parse(E.data),Ee[h]);if(y==="update"&&S&&!I)w({type:"status",endpoint:g,fn_index:h,time:new Date,...S}),S.stage==="error"&&(L?.close(),O());else if(y==="data"){let[te,P]=await re(`${c.root}${A}/queue/data`,{...ee,session_hash:u,event_id:k},ae);P!==200&&(w({type:"status",stage:"error",message:q,queue:!0,endpoint:g,fn_index:h,time:new Date}),L?.close(),O())}else y==="complete"?I=S:y==="log"?w({type:"log",title:j.title,log:j.log,level:j.level,endpoint:g,duration:j.duration,visible:j.visible,fn_index:h}):(y==="generating"||y==="streaming")&&w({type:"status",time:new Date,...S,stage:S?.stage,queue:!0,endpoint:g,fn_index:h});j&&(w({type:"data",time:new Date,data:J(j.data,x,c.components,"output",z.with_null_state),endpoint:g,fn_index:h,event_data:n,trigger_id:r}),I&&(w({type:"status",time:new Date,...I,stage:S?.stage,queue:!0,endpoint:g,fn_index:h}),L?.close(),O()))}}else if(N=="sse_v1"||N=="sse_v2"||N=="sse_v2.1"||N=="sse_v3"){w({type:"status",stage:"pending",queue:!0,endpoint:g,fn_index:h,time:new Date});let v="";typeof window<"u"&&typeof document<"u"&&(v=window?.location?.hostname);let E=lt(v);return(typeof window<"u"&&typeof document<"u"&&window.parent!=window&&E&&window.supports_zerogpu_headers?hn("zerogpu-headers",E):Promise.resolve(null)).then(y=>{let S={...ae,...y||{}};return re(`${c.root}${A}/${At}?${B}`,{...ee,session_hash:u},S)}).then(async([y,S])=>{if(y.event_id&&(R=y.event_id),S===503)w({type:"status",stage:"error",message:tt,queue:!0,endpoint:g,fn_index:h,time:new Date,visible:!0}),O();else if(S===422)w({type:"status",stage:"error",message:y.detail,queue:!0,endpoint:g,fn_index:h,code:"validation_error",time:new Date,visible:!0}),O();else if(S!==200){let j=y?.error===q;w({type:"status",stage:"error",broken:j,message:j?q:y.detail||y.error,queue:!0,endpoint:g,fn_index:h,time:new Date,visible:!0}),O()}else{k=y.event_id,R=k;let j=async function(te){try{let{type:P,status:D,data:T,original_msg:St}=Le(te,Ee[h]);if(P=="heartbeat")return;if(P==="update"&&D&&!I)w({type:"status",endpoint:g,fn_index:h,time:new Date,original_msg:St,...D});else if(P==="complete")I=D;else if(P=="unexpected_error"||P=="broken_connection"){console.error("Unexpected error",D?.message);let Et=P==="broken_connection";w({type:"status",stage:"error",message:D?.message||"An Unexpected Error Occurred!",queue:!0,endpoint:g,broken:Et,session_not_found:D?.session_not_found,fn_index:h,time:new Date})}else if(P==="log"){w({type:"log",title:T.title,log:T.log,level:T.level,endpoint:g,duration:T.duration,visible:T.visible,fn_index:h});return}else(P==="generating"||P==="streaming")&&(w({type:"status",time:new Date,...D,stage:D?.stage,queue:!0,endpoint:g,fn_index:h}),T&&x.connection!=="stream"&&["sse_v2","sse_v2.1","sse_v3"].includes(N)&&An(_,k,T));T&&(w({type:"data",time:new Date,data:J(T.data,x,c.components,"output",z.with_null_state),endpoint:g,fn_index:h}),T.render_config&&await xe(T.render_config),I&&(w({type:"status",time:new Date,...I,stage:D?.stage,queue:!0,endpoint:g,fn_index:h}),O())),(D?.stage==="complete"||D?.stage==="error")&&(U[k]&&delete U[k],k in _&&delete _[k],O())}catch(P){console.error("Unexpected client exception",P),w({type:"status",stage:"error",message:"An Unexpected Error Occurred!",queue:!0,endpoint:g,fn_index:h,time:new Date}),["sse_v2","sse_v2.1","sse_v3"].includes(N)&&(_e(f,ye.abort_controller),f.open=!1,O())}};k in $&&($[k].forEach(te=>j(te)),delete $[k]),U[k]=j,Q.add(k),f.open||await this.open_stream()}})}});ie.catch(p=>{w({type:"status",stage:"error",message:p instanceof Error?p.message:String(p),queue:!Fe(h,c),endpoint:g,fn_index:h,time:new Date}),O()});let Oe=!1,oe=[],F=[],De=(p,b)=>{ie.then(()=>{R&&this.post_data(`${c.root}${A}/stream/${R}${p}`,b)},()=>{})},Te={[Symbol.asyncIterator]:()=>Te,next:Pe,throw:async p=>($t(p),Pe()),return:async()=>(O(),{value:void 0,done:!0}),cancel:bt,send_chunk:p=>{De("",{...p,session_hash:this.session_hash})},close_stream:()=>{O(),De("/close",{})},event_id:()=>R,wait_for_id:async()=>(await ie,k)};return Te}catch(i){throw console.error("Submit function encountered an error:",i),i}}function er(e){return{then:(t,n)=>n(e)}}function tr(e,t,n,r){let s,a,i;if(typeof t=="number")s=t,a=e.unnamed_endpoints[s],i=r.dependencies.find(o=>o.id==t);else{let o=t.replace(/^\//,"");s=n[o],a=e.named_endpoints[t.trim()]??e.named_endpoints[`/${o}`],i=r.dependencies.find(l=>l.id==n[o])}if(typeof s!="number"||!i){let o=r.dependencies.filter(l=>l.api_name).map(l=>`"/${l.api_name}"`).join(", ");throw Error(`No endpoint matching ${JSON.stringify(t)} was found. `+(o?`Valid named endpoints are: ${o}. `:"This app exposes no named endpoints. ")+"An fn_index (number) of an existing dependency can also be used.")}return{fn_index:s,endpoint_info:a,dependency:i}}var Qe=class{app_reference;options;deep_link=null;page=null;config;api_prefix="";api_info;api_map={};session_hash=Math.random().toString(36).substring(2);jwt=!1;last_status={};cookies=null;stream_status={open:!1};closed=!1;pending_stream_messages={};pending_diff_streams={};event_callbacks={};unclosed_events=new Set;heartbeat_event=null;abort_controller=null;stream_instance=null;current_payload;get_url_config(e=null){if(!this.config)throw Error(C);e===null&&(e=window.location.href);let t=a=>a.replace(/^\/+|\/+$/g,""),n=t(new URL(this.config.root).pathname),r=t(new URL(e).pathname),s;return s=r.startsWith(n)?t(r.substring(n.length)):"",this.get_page_config(s)}get_page_config(e){if(!this.config)throw Error(C);let t=this.config;return e in t.page||(e=""),{...t,current_page:e,layout:t.page[e].layout,components:t.components.filter(n=>t.page[e].components.includes(n.id)),dependencies:this.config.dependencies.filter(n=>t.page[e].dependencies.includes(n.id))}}fetch(e,t){let n=new Headers(t?.headers||{});return this&&this.cookies&&n.append("Cookie",this.cookies),this&&this.options.headers&&new Headers(this.options.headers).forEach((r,s)=>{n.append(s,r)}),fetch(e,{...t,headers:n})}stream(e){let t=new Headers;return this&&this.cookies&&t.append("Cookie",this.cookies),this&&this.options.headers&&new Headers(this.options.headers).forEach((n,r)=>{t.append(r,n)}),this&&this.options.token&&t.append("Authorization",`Bearer ${this.options.token}`),this.abort_controller=new AbortController,this.stream_instance=qn(e.toString(),{credentials:this.options.credentials??"same-origin",headers:t,signal:this.abort_controller.signal}),this.stream_instance}view_api;upload_files;upload;handle_blob;post_data;submit;predict;open_stream;resolve_config;resolve_cookies;constructor(e,t={events:["data"]}){this.app_reference=e,this.deep_link=t.query_params?.deep_link||null,this.page=t.query_params?.page??null,t.events||=["data"],st(t),this.options=t,this.current_payload={},t.cookies&&(this.cookies=t.cookies),this.view_api=cn.bind(this),this.upload_files=ln.bind(this),this.handle_blob=gn.bind(this),this.post_data=wn.bind(this),this.submit=Xn.bind(this),this.predict=yn.bind(this),this.open_stream=Cn.bind(this),this.resolve_config=en.bind(this),this.resolve_cookies=tn.bind(this),this.upload=pn.bind(this),this.fetch=this.fetch.bind(this),this.handle_space_success=this.handle_space_success.bind(this),this.stream=this.stream.bind(this)}async init(){xn(),this.options.auth&&await this.resolve_cookies(),await this._resolve_config().then(e=>e?.config&&this._resolve_heartbeat(e.config));try{this.api_info=await this.view_api()}catch(e){console.error(e.message)}this.api_map=Ue(this.config?.dependencies||[])}async _resolve_heartbeat(e){if(this.config=e,this.api_prefix=e.api_prefix||"",e.space_id&&this.options.token&&(this.jwt=await Qt(e.space_id,this.options.token,this.cookies)),Me(this.config,this.jwt),this.config&&this.config.connect_heartbeat){let t=new URL(`${this.config.root}${this.api_prefix}/${zt}/${this.session_hash}`);this.jwt&&t.searchParams.set("__sign",this.jwt),this.heartbeat_event||=this.stream(t)}}static async connect(e,t={events:["data"]}){let n=new this(e,t);return t.session_hash&&(n.session_hash=t.session_hash),await n.init(),n}async reconnect(){let e=new URL(`${this.config.root}${this.api_prefix}/${Ft}`),t;try{let n=await this.fetch(e);if(!n.ok)throw Error();t=(await n.json()).app_id}catch{return"broken"}return t===this.config.app_id?"connected":"changed"}close(){this.closed=!0,_e(this.stream_status,this.abort_controller)}async refresh(){if(!this.config)throw Error(C);let e=await this.resolve_config(this.config.root,!1);if(!e)throw Error(C);this.config=e,this.api_prefix=e.api_prefix||"",this.api_map=Ue(e.dependencies||[]),Me(this.config,this.jwt);try{this.api_info=await this.view_api()}catch(t){console.error(qe+t.message)}return this.get_url_config()}set_current_payload(e){this.current_payload=e}static async duplicate(e,t={events:["data"]}){return kn(e,t)}async _resolve_config(){let{http_protocol:e,host:t,space_id:n}=await he(this.app_reference,this.options.token),{status_callback:r}=this.options;n&&r&&await ct(n,r);let s;try{let a=`${e}//${t}`;if(s=await this.resolve_config(a),!s)throw Error(C);return this.config_success(s)}catch(a){if(n&&r)H(n,de.test(n)?"space_name":"subdomain",this.handle_space_success);else throw r&&r({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),a instanceof Error?a:Error(String(a))}}async config_success(e){if(this.config=e,this.api_prefix=e.api_prefix||"",e.run_history===!1&&Zn({app_id:e.app_id,username:e.username}),this.config.auth_required)return this.prepare_return_obj();try{this.api_info=await this.view_api()}catch(t){console.error(qe+t.message)}return this.prepare_return_obj()}async handle_space_success(e){if(!this)throw Error(C);let{status_callback:t}=this.options;if(t&&t(e),e.status==="running")try{if(this.config=await this._resolve_config(),this.api_prefix=this?.config?.api_prefix||"",!this.config)throw Error(C);return await this.config_success(this.config)}catch(n){throw t&&t({status:"error",message:"Could not load this space.",load_status:"error",detail:"NOT_FOUND"}),n}}async component_server(e,t,n){if(!this.config)throw Error(C);let r={},{token:s}=this.options,{session_hash:a}=this;s&&(r.Authorization=`Bearer ${this.options.token}`);let i,o=this.config.components.find(c=>c.id===e);i=o?.props?.root_url?o.props.root_url:this.config.root;let l;if(typeof n=="object"&&n&&"binary"in n){let c=n;l=new FormData;for(let u in c.data)u!=="binary"&&l.append(u,c.data[u]);l.set("component_id",e.toString()),l.set("fn_name",t),l.set("session_hash",a)}else l=JSON.stringify({data:n,component_id:e,fn_name:t,session_hash:a}),r["Content-Type"]="application/json";s&&(r.Authorization=`Bearer ${s}`);try{let c=await this.fetch(`${i}${this.api_prefix}/${Lt}/`,{method:"POST",body:l,headers:r,credentials:this.options.credentials??"same-origin"});if(!c.ok)throw Error("Could not connect to component server: "+c.statusText);let u=await c.json();return ge(u,this.config.root,this.config.api_prefix||"",this.jwt),u}catch(c){console.warn(c)}}set_cookies(e){this.cookies=it(e).join("; ")}prepare_return_obj(){return{config:this.config,predict:this.predict,submit:this.submit,view_api:this.view_api,component_server:this.component_server}}};export{Qe as Client,fe as FileData,Zn as clear_run_history,yn as predict,Yn as read_run_history_storage,Xn as submit,rr as t,pn as upload,ln as upload_files};
web/dist/assets/index-B-txyBsD.js ADDED
The diff for this file is too large to render. See raw diff
 
web/dist/index.html CHANGED
@@ -1,4 +1,4 @@
1
  <!doctype html>
2
- <html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="#101A14"/><meta name="description" content="Home Pulse,让家的消息刚刚好。关注你在意的日常,留意有意义的变化。"/><title>Home Pulse · 家的消息,刚刚好</title><link rel="icon" type="image/svg+xml" href="/favicon.svg"/> <script type="module" crossorigin src="/assets/index-y-Pjsava.js"></script>
3
  <link rel="stylesheet" crossorigin href="/assets/index-BX_yyFR1.css">
4
  </head><body><div id="root"></div></body></html>
 
1
  <!doctype html>
2
+ <html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta name="theme-color" content="#101A14"/><meta name="description" content="Home Pulse,让家的消息刚刚好。关注你在意的日常,留意有意义的变化。"/><title>Home Pulse · 家的消息,刚刚好</title><link rel="icon" type="image/svg+xml" href="/favicon.svg"/> <script type="module" crossorigin src="/assets/index-B-txyBsD.js"></script>
3
  <link rel="stylesheet" crossorigin href="/assets/index-BX_yyFR1.css">
4
  </head><body><div id="root"></div></body></html>
web/src/pages/Insights.tsx CHANGED
@@ -1,25 +1,25 @@
1
- import { useState } from 'react'
2
- import { Activity,ArrowDownToLine,ChevronDown,Cpu,Search } from 'lucide-react'
3
- import { PageHead,Metric,Badge,SectionHead,SparkBars,Empty } from '@/components/Design'
4
- import { useMetrics,useHealth,num,ms,type Trace } from '@/lib/metrics'
5
- import { downloadJSON } from '@/lib/engine'
6
- import { formatTime } from '@/lib/domain'
7
- const STATUS={success:{label:'已返回',tone:'green'},unknown:{label:'无法确认',tone:'amber'},error:{label:'请求失败',tone:'red'},running:{label:'处理中',tone:'muted'}}
8
- function TraceRow({r}:{r:Trace}){const [open,setOpen]=useState(false);return <><tr onClick={()=>setOpen(!open)} className="trace-row"><td className="mono">{formatTime(r.startedAt,true)}</td><td><b>{r.itemName||'画面取证'}</b><small>{r.kind==='grounding'?'视野校验':r.source} · {r.camera}</small></td><td><Badge tone={STATUS[r.status].tone}>{STATUS[r.status].label}</Badge></td><td className="mono">{ms(r.latencyMs)}</td><td className="trace-verdict">{r.error||r.verdict||r.choice||'等待结果'}</td><td><button className="icon-btn" aria-label="展开决策记录" aria-expanded={open} onClick={e=>{e.stopPropagation();setOpen(!open)}}><ChevronDown size={15} className={open?'rotate':''}/></button></td></tr>{open&&<tr className="trace-expanded"><td colSpan={6}><div className="trace-detail-grid"><div><span>请求编号</span><code>{r.id}</code></div><div><span>模型处理</span><b>{ms(r.inferenceMs)}</b></div><div><span>队列等待</span><b>{ms(r.queueMs)}</b></div><div><span>状态裁决</span><b>{r.engineMs!=null?r.engineMs.toFixed(2)+' ms':'—'}</b></div><div><span>画面来源</span><b>{r.sourceName||'未记录'}{r.mediaTime!=null?' · '+r.mediaTime.toFixed(1)+'s':''}</b></div><div><span>消息投递</span><b>{r.notified?'已生成消息':'静默记录'}</b></div></div></td></tr>}</>}
9
- export default function Insights(){
10
- const [range,setRange]=useState('today'),[status,setStatus]=useState('all'),[search,setSearch]=useState('')
11
- const {data:m,error}=useMetrics(range),health=useHealth()
12
- const rows=m?.records.filter(r=>(status==='all'||r.status===status)&&(r.itemName+r.camera+r.source).includes(search))||[]
13
- const latency=m?.records.filter(r=>r.status==='success'||r.status==='unknown').slice(0,24).reverse()||[],max=Math.max(1,...latency.map(r=>r.latencyMs||0))
14
- return <div className="page"><PageHead eyebrow="OBSERVABILITY / EVERY DECISION COUNTS" title="每一步判断,都清晰可见。" description="从画面捕获到消息送达,了解 Home Pulse 的运行节奏。" action={<button className="button secondary" onClick={()=>m&&downloadJSON(m,'home-pulse-'+range+'.json')} disabled={!m}><ArrowDownToLine size={16}/>导出记录</button>}/>
15
- <div className="toolbar"><div className="segmented">{[['today','今天'],['week','近 7 天'],['all','全部记录']].map(([v,l])=><button key={v} className={range===v?'active':''} onClick={()=>setRange(v)}>{l}</button>)}</div><Badge tone={health?.ready?'green':'muted'}>{health?.ready?'引擎在线':'引擎待连接'} · {m?.inFlight||0} 个处理中</Badge></div>
16
- {error&&<div className="inline-error">运行数据暂未连接,正在重试。</div>}
17
- <div className="metrics-row insights-metrics"><Metric label="捕获画面" value={num(m?.captures)} unit="帧" note={m?m.requests+' 次模型请求':'—'}/><Metric label="决策耗时 · P50" value={num(m?.p50)} unit="ms" note={'P95 '+ms(m?.p95)}/><Metric label="请求成功率" value={num(m?.successRate)} unit="%" note={<span title="有效模型响应 / 已完成请求;包含无法确认的响应">{m?m.succeeded+' / '+m.completed+' 次请求':'等待请求'}</span>} accent/><Metric label="请求失败率" value={num(m?.failureRate)} unit="%" note={m?m.failed+' 次请求失败 · '+m.captureFailures+' 次取帧失败':'等待请求'}/></div>
18
- <div className="charts-grid"><section className="surface chart-panel"><SectionHead title="捕获节奏" sub={range==='today'?'24 HOURS':'按小时聚合'}><span className="chart-legend"><i/>画面捕获</span></SectionHead><SparkBars values={m?.hourly.map(h=>h.captures)||Array(24).fill(0)}/><div className="chart-axis"><span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>23:00</span></div></section>
19
- <section className="surface chart-panel latency-panel"><SectionHead title="决策响应" sub="最近 24 次有效响应"><span className="mono">{ms(m?.average)} <small>均值</small></span></SectionHead>{latency.length?<div className="latency-chart"><div className="latency-guides"><span>{ms(max)}</span><span>0 ms</span></div><svg viewBox="0 0 560 120" preserveAspectRatio="none" role="img" aria-label="决策耗时趋势"><defs><linearGradient id="latency-fill" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#749076" stopOpacity=".22"/><stop offset="100%" stopColor="#749076" stopOpacity="0"/></linearGradient></defs><path d={'M 8 115 '+latency.map((r,i)=>'L '+(8+i*544/Math.max(1,latency.length-1))+' '+(110-(r.latencyMs||0)/max*98)).join(' ')+' L '+(8+(latency.length-1)*544/Math.max(1,latency.length-1))+' 115 Z'} fill="url(#latency-fill)"/><polyline points={latency.map((r,i)=>(8+i*544/Math.max(1,latency.length-1))+','+(110-(r.latencyMs||0)/max*98)).join(' ')} fill="none" stroke="#486a50" strokeWidth="2" vectorEffect="non-scaling-stroke"/>{latency.map((r,i)=><circle key={r.id} cx={8+i*544/Math.max(1,latency.length-1)} cy={110-(r.latencyMs||0)/max*98} r="3.5" fill="#486a50"><title>{formatTime(r.startedAt,true)+' · '+ms(r.latencyMs)}</title></circle>)}</svg></div>:<div className="chart-placeholder"><Activity size={23} strokeWidth={1.2}/><span>第一条决策完成后,曲线会从这里开始。</span></div>}<div className="chart-axis"><span>较早</span><span>端到端请求耗时</span><span>最近</span></div></section></div>
20
- <div className="insights-mid"><section className="surface funnel-panel"><SectionHead title="从看见,到值得告诉你"/><div className="funnel-flow">{[[m?.captures,'捕获画面'],[m?.decisions,'观察决策'],[m?.stateChanges,'状态变化'],[m?.notifications,'重要消息']].map(([v,l],i)=><div key={String(l)}><span>{String(i+1).padStart(2,'0')}</span><strong>{num(v as number|undefined)}</strong><p>{l}</p></div>)}</div></section><section className="engine-panel"><div><Cpu size={20}/><Badge tone={health?.ready?'green':'muted'}>{health?.ready?'ONLINE':'STANDBY'}</Badge></div><h3>imajev <em>4B</em></h3><p>{health?.runtime?.gpu||'本地视觉引擎'}</p><div className="engine-meta"><span>{health?.runtime?.quantization||'NF4 · 4-bit'}</span><span>{health?.runtime?.memoryGiB?.toFixed(2)||'—'} GB <small>加载占用</small></span></div></section></div>
21
- <section className="surface trace-panel"><SectionHead title="每一次决策" sub={m?m.totalRecords+' 条记录':''}><select aria-label="筛选决策状态" value={status} onChange={e=>setStatus(e.target.value)}><option value="all">所有状态</option><option value="success">已返回</option><option value="unknown">无法确认</option><option value="error">请求失败</option></select></SectionHead><div className="trace-search"><label className="search-field"><Search size={15}/><input placeholder="搜索事项、空间或触发来源" aria-label="搜索决策记录" value={search} onChange={e=>setSearch(e.target.value)}/></label><span>{m?.unknown||0} 次无法确认</span></div><div className="table-scroll"><table className="trace-table"><thead><tr><th>时间</th><th>关注事项 / 来源</th><th>响应状态</th><th>决策耗时</th><th>处理结果</th><th/></tr></thead><tbody>{rows.map(r=><TraceRow key={r.id} r={r}/>)}</tbody></table></div>{!rows.length&&<Empty icon="activity" title={search||status!=='all'?'没有匹配的记录':'等待第一条决策'} description="完成一次取证,耗时与处理结果会同步到这里。"/>}{m&&m.totalRecords>300&&<p className="table-note">显示最近 300 条,完整记录可在隐私与数据中导出。</p>}</section>
22
- {m&&m.failures.length>0&&<section className="surface failure-list"><SectionHead title="需要留意的请求"/>{m.failures.map(f=><div key={f.reason}><span>{f.reason}</span><Badge tone="red">{f.count} 次</Badge></div>)}</section>}
23
- </div>
24
- }
25
 
 
1
+ import { useState } from 'react'
2
+ import { Activity,ArrowDownToLine,ChevronDown,Cpu,Search } from 'lucide-react'
3
+ import { PageHead,Metric,Badge,SectionHead,SparkBars,Empty } from '@/components/Design'
4
+ import { useMetrics,useHealth,num,ms,type Trace } from '@/lib/metrics'
5
+ import { downloadJSON } from '@/lib/engine'
6
+ import { formatTime } from '@/lib/domain'
7
+ const STATUS={success:{label:'已返回',tone:'green'},unknown:{label:'无法确认',tone:'amber'},error:{label:'请求失败',tone:'red'},running:{label:'处理中',tone:'muted'}}
8
+ function TraceRow({r}:{r:Trace}){const [open,setOpen]=useState(false);return <><tr onClick={()=>setOpen(!open)} className="trace-row"><td className="mono">{formatTime(r.startedAt,true)}</td><td><b>{r.itemName||'画面取证'}</b><small>{r.kind==='grounding'?'视野校验':r.source} · {r.camera}</small></td><td><Badge tone={STATUS[r.status].tone}>{STATUS[r.status].label}</Badge></td><td className="mono">{ms(r.latencyMs)}</td><td className="trace-verdict">{r.error||r.verdict||r.choice||'等待结果'}</td><td><button className="icon-btn" aria-label="展开决策记录" aria-expanded={open} onClick={e=>{e.stopPropagation();setOpen(!open)}}><ChevronDown size={15} className={open?'rotate':''}/></button></td></tr>{open&&<tr className="trace-expanded"><td colSpan={6}><div className="trace-detail-grid"><div><span>请求编号</span><code>{r.id}</code></div><div><span>模型处理</span><b>{ms(r.inferenceMs)}</b></div><div><span>队列等待</span><b>{ms(r.queueMs)}</b></div><div><span>状态裁决</span><b>{r.engineMs!=null?r.engineMs.toFixed(2)+' ms':'—'}</b></div><div><span>画面来源</span><b>{r.sourceName||'未记录'}{r.mediaTime!=null?' · '+r.mediaTime.toFixed(1)+'s':''}</b></div><div><span>消息投递</span><b>{r.notified?'已生成消息':'静默记录'}</b></div></div></td></tr>}</>}
9
+ export default function Insights(){
10
+ const [range,setRange]=useState('today'),[status,setStatus]=useState('all'),[search,setSearch]=useState('')
11
+ const {data:m,error}=useMetrics(range),health=useHealth()
12
+ const rows=m?.records.filter(r=>(status==='all'||r.status===status)&&(r.itemName+r.camera+r.source).includes(search))||[]
13
+ const latency=m?.records.filter(r=>r.status==='success'||r.status==='unknown').slice(0,24).reverse()||[],max=Math.max(1,...latency.map(r=>r.latencyMs||0))
14
+ return <div className="page"><PageHead eyebrow="OBSERVABILITY / EVERY DECISION COUNTS" title="每一步判断,都清晰可见。" description="从画面捕获到消息送达,了解 Home Pulse 的运行节奏。" action={<button className="button secondary" onClick={()=>m&&downloadJSON(m,'home-pulse-'+range+'.json')} disabled={!m}><ArrowDownToLine size={16}/>导出记录</button>}/>
15
+ <div className="toolbar"><div className="segmented">{[['today','今天'],['week','近 7 天'],['all','全部记录']].map(([v,l])=><button key={v} className={range===v?'active':''} onClick={()=>setRange(v)}>{l}</button>)}</div><Badge tone={health?.ready?'green':'muted'}>{health?.ready?'引擎在线':'引擎待连接'} · {m?.inFlight||0} 个处理中</Badge></div>
16
+ {error&&<div className="inline-error">运行数据暂未连接,正在重试。</div>}
17
+ <div className="metrics-row insights-metrics"><Metric label="捕获画面" value={num(m?.captures)} unit="帧" note={m?m.requests+' 次模型请求':'—'}/><Metric label="决策耗时 · P50" value={num(m?.p50)} unit="ms" note={'P95 '+ms(m?.p95)}/><Metric label="请求成功率" value={num(m?.successRate)} unit="%" note={<span title="有效模型响应 / 已完成请求;包含无法确认的响应">{m?m.succeeded+' / '+m.completed+' 次请求':'等待请求'}</span>} accent/><Metric label="请求失败率" value={num(m?.failureRate)} unit="%" note={m?m.failed+' 次请求失败 · '+m.captureFailures+' 次取帧失败':'等待请求'}/></div>
18
+ <div className="charts-grid"><section className="surface chart-panel"><SectionHead title="捕获节奏" sub={range==='today'?'24 HOURS':'按小时聚合'}><span className="chart-legend"><i/>画面捕获</span></SectionHead><SparkBars values={m?.hourly.map(h=>h.captures)||Array(24).fill(0)}/><div className="chart-axis"><span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>23:00</span></div></section>
19
+ <section className="surface chart-panel latency-panel"><SectionHead title="决策响应" sub="最近 24 次有效响应"><span className="mono">{ms(m?.average)} <small>均值</small></span></SectionHead>{latency.length?<div className="latency-chart"><div className="latency-guides"><span>{ms(max)}</span><span>0 ms</span></div><svg viewBox="0 0 560 120" preserveAspectRatio="none" role="img" aria-label="决策耗时趋势"><defs><linearGradient id="latency-fill" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#749076" stopOpacity=".22"/><stop offset="100%" stopColor="#749076" stopOpacity="0"/></linearGradient></defs><path d={'M 8 115 '+latency.map((r,i)=>'L '+(8+i*544/Math.max(1,latency.length-1))+' '+(110-(r.latencyMs||0)/max*98)).join(' ')+' L '+(8+(latency.length-1)*544/Math.max(1,latency.length-1))+' 115 Z'} fill="url(#latency-fill)"/><polyline points={latency.map((r,i)=>(8+i*544/Math.max(1,latency.length-1))+','+(110-(r.latencyMs||0)/max*98)).join(' ')} fill="none" stroke="#486a50" strokeWidth="2" vectorEffect="non-scaling-stroke"/>{latency.map((r,i)=><circle key={r.id} cx={8+i*544/Math.max(1,latency.length-1)} cy={110-(r.latencyMs||0)/max*98} r="3.5" fill="#486a50"><title>{formatTime(r.startedAt,true)+' · '+ms(r.latencyMs)}</title></circle>)}</svg></div>:<div className="chart-placeholder"><Activity size={23} strokeWidth={1.2}/><span>第一条决策完成后,曲线会从这里开始。</span></div>}<div className="chart-axis"><span>较早</span><span>端到端请求耗时</span><span>最近</span></div></section></div>
20
+ <div className="insights-mid"><section className="surface funnel-panel"><SectionHead title="从看见,到值得告诉你"/><div className="funnel-flow">{[[m?.captures,'捕获画面'],[m?.decisions,'观察决策'],[m?.stateChanges,'状态变化'],[m?.notifications,'重要消息']].map(([v,l],i)=><div key={String(l)}><span>{String(i+1).padStart(2,'0')}</span><strong>{num(v as number|undefined)}</strong><p>{l}</p></div>)}</div></section><section className="engine-panel"><div><Cpu size={20}/><Badge tone={health?.ready?'green':'muted'}>{health?.ready?'ONLINE':'STANDBY'}</Badge></div><h3>imajev <em>4B</em></h3><p>{health?.runtime?.gpu||'视觉引擎'}</p><div className="engine-meta"><span>{health?.runtime?.quantization||'—'}</span><span>{health?.runtime?.memoryGiB?.toFixed(2)||'—'} GB <small>加载占用</small></span></div></section></div>
21
+ <section className="surface trace-panel"><SectionHead title="每一次决策" sub={m?m.totalRecords+' 条记录':''}><select aria-label="筛选决策状态" value={status} onChange={e=>setStatus(e.target.value)}><option value="all">所有状态</option><option value="success">已返回</option><option value="unknown">无法确认</option><option value="error">请求失败</option></select></SectionHead><div className="trace-search"><label className="search-field"><Search size={15}/><input placeholder="搜索事项、空间或触发来源" aria-label="搜索决策记录" value={search} onChange={e=>setSearch(e.target.value)}/></label><span>{m?.unknown||0} 次无法确认</span></div><div className="table-scroll"><table className="trace-table"><thead><tr><th>时间</th><th>关注事项 / 来源</th><th>响应状态</th><th>决策耗时</th><th>处理结果</th><th/></tr></thead><tbody>{rows.map(r=><TraceRow key={r.id} r={r}/>)}</tbody></table></div>{!rows.length&&<Empty icon="activity" title={search||status!=='all'?'没有匹配的记录':'等待第一条决策'} description="完成一次取证,耗时与处理结果会同步到这里。"/>}{m&&m.totalRecords>300&&<p className="table-note">显示最近 300 条,完整记录可在隐私与数据中导出。</p>}</section>
22
+ {m&&m.failures.length>0&&<section className="surface failure-list"><SectionHead title="需要留意的请求"/>{m.failures.map(f=><div key={f.reason}><span>{f.reason}</span><Badge tone="red">{f.count} 次</Badge></div>)}</section>}
23
+ </div>
24
+ }
25
 
web/src/pages/Landing.tsx CHANGED
@@ -1,22 +1,23 @@
1
- import { Link } from 'react-router'
2
- import { ArrowRight,ArrowUpRight,Check,ShieldCheck } from 'lucide-react'
3
- import { Brand } from '@/components/Design'
4
- export default function Landing(){return <div className="landing">
5
- <header><Brand/><Link className="button secondary" to="/home">进入我的家<ArrowUpRight size={15}/></Link></header>
6
- <main>
7
- <div className="landing-copy">
8
- <div className="eyebrow"><span className="tiny-line"/>A QUIETER KIND OF CARE</div>
9
- <h1>人在外,<br/>心<span>有着落。</span></h1>
10
- <p>包裹到了,小家伙在玩。<br/>把家的小事放在这里,把时间留给生活。</p>
11
- <div className="landing-cta"><Link to="/home" className="button primary">看看我的家<ArrowRight size={17}/></Link><Link to="/events" className="text-link">看它如何判断</Link></div>
12
- <div className="landing-points"><span><Check size={13}/>重要变化,及时知道</span><span><ShieldCheck size={13}/>本地处理,自在安心</span></div>
13
- </div>
14
- <div className="landing-visual">
15
- <img src="/media/posters/cat-active.jpg" alt="家中宠物在客厅活动"/>
16
- <div className="landing-picture-label"><span className="eyebrow">A LITTLE MOMENT AT HOME</span><h2>平常的一刻,<br/>也是牵挂的全部。</h2></div>
17
- <div className="landing-note"><span><Check size={16}/></span><div><b>关心,刚刚好。</b><p>每一次回应,都有画面可循。</p></div></div>
18
- <div className="landing-chip"><b>≈ 0.6 s</b><small>一次观察的耗时 · 全程本地</small></div>
19
- </div>
20
- </main>
21
- <footer><span>HOME PULSE · 家的消息,刚刚好。</span><span>Made for the moments that matter.</span></footer>
22
- </div>}
 
 
1
+ import {isCloud} from '@/lib/cloud-client'
2
+ import { Link } from 'react-router'
3
+ import { ArrowRight,ArrowUpRight,Check,ShieldCheck } from 'lucide-react'
4
+ import { Brand } from '@/components/Design'
5
+ export default function Landing(){return <div className="landing">
6
+ <header><Brand/><Link className="button secondary" to="/home">进入我的家<ArrowUpRight size={15}/></Link></header>
7
+ <main>
8
+ <div className="landing-copy">
9
+ <div className="eyebrow"><span className="tiny-line"/>A QUIETER KIND OF CARE</div>
10
+ <h1>人在外,<br/>心<span>有着落。</span></h1>
11
+ <p>包裹到了,小家伙在玩。<br/>把家的小事放在这里,把时间留给生活。</p>
12
+ <div className="landing-cta"><Link to="/home" className="button primary">看看我的家<ArrowRight size={17}/></Link><Link to="/events" className="text-link">看它如何判断</Link></div>
13
+ <div className="landing-points"><span><Check size={13}/>重要变化,及时知道</span><span><ShieldCheck size={13}/>{isCloud()?'云端观察,随时打开':'本地处理,自在安心'}</span></div>
14
+ </div>
15
+ <div className="landing-visual">
16
+ <img src="/media/posters/cat-active.jpg" alt="家中宠物在客厅活动"/>
17
+ <div className="landing-picture-label"><span className="eyebrow">A LITTLE MOMENT AT HOME</span><h2>平常的一刻,<br/>也是牵挂的全部。</h2></div>
18
+ <div className="landing-note"><span><Check size={16}/></span><div><b>关心,刚刚好。</b><p>每一次回应,都有画面可循。</p></div></div>
19
+ <div className="landing-chip"><b>{isCloud()?'HF GPU':'≈ 0.6 s'}</b><small>{isCloud()?'按需观察 · 共享免费算力':'一次观察的耗时 · 全程本地'}</small></div>
20
+ </div>
21
+ </main>
22
+ <footer><span>HOME PULSE · 家的消息,刚刚好。</span><span>Made for the moments that matter.</span></footer>
23
+ </div>}