Deploy Home Pulse: grounded setup, isolated workspaces and shared HF visual inference
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+6-35
- MEDIA-SOURCES.mdAdded+61
- README.md+42-9
- app.py+136-95
- app_zerogpu.pyAdded+115
- fig/10102107193.mp4 → media-library/clips/S01.mp4Renamed+2-2
- fig/10244479353.mp4 → media-library/clips/S02.mp4Renamed+2-2
- fig/eiffel_a.jpg → media-library/clips/S03.mp4Renamed+2-2
- fig/longgang_nightblur.png → media-library/clips/S04.mp4Renamed+2-2
- media-library/clips/S05.mp4Added+3
- fig/none.png → media-library/clips/S06.mp4Renamed+2-2
- media-library/clips/S07.mp4Added+3
- media-library/clips/S08.mp4Added+3
- media-library/clips/S09.mp4Added+3
- media-library/clips/S10.mp4Added+3
- media-library/clips/S11.mp4Added+3
- fig/onescorer.png → media-library/clips/S12.mp4Renamed+2-2
- media-library/clips/S13.mp4Added+3
- media-library/clips/S14.mp4Added+3
- fig/singapore_flyer_2.jpg → media-library/clips/S15.mp4Renamed+2-2
- media-library/clips/S16.mp4Added+3
- media-library/clips/S17.mp4Added+3
- media-library/clips/S18.mp4Added+3
- media-library/clips/S19.mp4Added+3
- media-library/clips/S20.mp4Added+3
- media-library/clips/S21.mp4Added+3
- media-library/clips/S22.mp4Added+3
- media-library/clips/S23.mp4Added+3
- media-library/clips/S24.mp4Added+3
- media-library/clips/S25.mp4Added+3
- media-library/clips/S26.mp4Added+3
- media-library/clips/S27.mp4Added+3
- media-library/clips/S28.mp4Added+3
- media-library/clips/S29.mp4Added+3
- media-library/clips/S30.mp4Added+3
- media-library/clips/S31.mp4Added+3
- media-library/clips/S32.mp4Added+3
- media-library/clips/S33.mp4Added+3
- media-library/clips/negative_01.mp4Added
- media-library/clips/negative_02.mp4Added
- media-library/clips/negative_03.mp4Added+3
- media-library/clips/negative_04.mp4Added+3
- media-library/clips/negative_05.mp4Added+3
- media-library/clips/negative_06.mp4Added+3
- media-library/clips/smartbench_0007.mp4Added+3
- media-library/clips/smartbench_0036.mp4Added+3
- media-library/clips/smartbench_0058.mp4Added+3
- media-library/clips/smartbench_0083.mp4Added+3
- media-library/clips/smartbench_0094.mp4Added+3
- media-library/clips/smartbench_0133.mp4Added+3
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textweb/dist/media/posters/cat-active.jpg filter=lfs diff=lfs merge=lfs -textweb/dist/media/posters/pkg-arrive.jpg filter=lfs diff=lfs merge=lfs -textweb/dist/media/posters/pkg-taken.jpg filter=lfs diff=lfs merge=lfs -textweb/dist/media/posters/porch-empty.jpg filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061# Sample video sources
Short clips supplied for this household-observation evaluation. Source links are retained for attribution. Original videos and datasets have not been modified.
| Clip | Title | Source |
|---|---|---|
| smartbench_0133 | 宠物在客厅活动 | https://www.youtube.com/watch?v=jR4r4-sV5sU |
| smartbench_0880 | 空客厅后宠物进入 | https://www.youtube.com/watch?v=v5aU-eSFzK4 |
| smartbench_0036 | 人与宠物日常互动 | https://www.youtube.com/watch?v=c4BiMNV5dME |
| smartbench_0188 | 幼犬翻越围栏 | https://www.youtube.com/watch?v=uUsuo2hKqnQ |
| smartbench_0630 | 宠物撕咬纸巾 | https://www.youtube.com/watch?v=IAUXOVtZqNk |
| smartbench_0276 | 配送员放下包裹 | https://www.youtube.com/watch?v=_iV2anL2SKE |
| smartbench_0266 | 住户取走包裹 | https://www.youtube.com/watch?v=_xg3SH6qu1c |
| smartbench_0551 | 门口人员拆开包裹 | https://www.youtube.com/watch?v=EXEg6CfzW70 |
| smartbench_0216 | 住户离开后空门廊 | https://www.youtube.com/watch?v=OvBzOodJ31E |
| smartbench_0321 | 人与宠物回屋后空门廊 | https://www.youtube.com/watch?v=FuDb8E9G6q4 |
| smartbench_0083 | 夜间人员进入后院 | https://www.youtube.com/watch?v=yT7qfBXOGLw |
| smartbench_0094 | 夜间人员进入围栏庭院 | https://www.youtube.com/watch?v=ArFLLlLjfXw |
| smartbench_0007 | 熊进入后院翻垃圾桶 | https://www.youtube.com/watch?v=GfNH24LsSh8 |
| smartbench_0058 | 人与狗在院内活动 | https://www.youtube.com/watch?v=TnjOgP6IvU8 |
| smartbench_0290 | 后院鸟类在喂食器活动 | https://www.youtube.com/watch?v=XWCCEksks5U |
| smartbench_0643 | 住户回屋后空庭院门口 | https://www.youtube.com/watch?v=5Xy1MJ6hXKc |
| negative_01 | 沙发区无人活动_纸袋与箱子保持不变 | https://changedetection.net/dataset2014/ |
| negative_02 | 沙发区无人活动_箱子保持不变 | https://changedetection.net/dataset2014/ |
| negative_03 | 人和宠物回屋后空门廊 | https://www.youtube.com/watch?v=FuDb8E9G6q4 |
| negative_04 | 夜间人员离开后空庭院 | https://www.youtube.com/watch?v=ArFLLlLjfXw |
| negative_05 | 白天住户回屋后空庭院 | https://www.youtube.com/watch?v=5Xy1MJ6hXKc |
| negative_06 | 室外入口无人员_树影自然变化 | https://changedetection.net/dataset2014/ |
| S01 | 住户带包离家与门边钥匙动作 | https://www.youtube.com/watch?v=jNsO1K0mRwI |
| S02 | 住户带包靠近门并进屋 | https://www.youtube.com/watch?v=fyeQn4V8cHU |
| S03 | 孩子背书包离家_到家反例 | https://www.youtube.com/watch?v=z-TMWr0axSo |
| S04 | 放学儿童在门口交谈 | https://www.youtube.com/watch?v=CSM5AuDQzwc |
| S05 | 校车旁儿童回到门廊 | https://www.youtube.com/watch?v=X5sIOHuLyAw |
| S06 | 背书包儿童进入室内 | https://www.youtube.com/watch?v=-3yHkj7dPvA |
| S07 | 儿童入户后受惊跌倒_终态反例 | https://www.youtube.com/watch?v=-3yHkj7dPvA |
| S08 | 门廊清扫过程 | https://www.youtube.com/watch?v=sZ9ij4A0REg |
| S09 | 远处吸尘动作_微小目标无法确认 | https://www.youtube.com/watch?v=_Psi3NnuNiw |
| S10 | 宠物休息与扫地机器人活动 | https://www.youtube.com/watch?v=6xZVT_HphuM |
| S11 | 夜视猫进食并间歇抬头 | https://www.youtube.com/watch?v=17_N3EJXNwg |
| S12 | 猫在食盆旁抬头暂停_进食对照 | https://www.youtube.com/watch?v=17_N3EJXNwg |
| S13 | 两只猫在食盆附近互动 | https://www.youtube.com/watch?v=bK0HH-YZTQ4 |
| S14 | 松鼠翻动门口零食篮 | https://www.youtube.com/watch?v=M-R95X8bk94 |
| S15 | 狗咬鞋_与玩具区分 | https://www.youtube.com/watch?v=qPVd5EP6vRQ |
| S16 | 宠物贴近镜头造成遮挡 | https://www.youtube.com/watch?v=qPVd5EP6vRQ |
| S17 | 猫在玩具旁休息 | https://www.youtube.com/watch?v=nVkLviQSlcY |
| S18 | 猫贴镜头_视野与夜视切换 | https://www.youtube.com/watch?v=nVkLviQSlcY |
| S19 | 夜间蜘蛛靠近镜头 | https://www.youtube.com/watch?v=BiE85wTQvpE |
| S20 | 狗下桌后遮挡镜头 | https://www.youtube.com/watch?v=3AwEol8eZ0M |
| S21 | 院内晾衣被逐件收下 | https://www.youtube.com/watch?v=Kdefe5JM0xM |
| S22 | 乌龟推开庭院门后离开 | https://www.youtube.com/watch?v=lPfU3YZaCes |
| S23 | 宠物店监控_手部遮住微小乌龟 | https://www.youtube.com/watch?v=FPgvMrguuPs |
| S24 | 厨房窗户开关动作 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip |
| S25 | 逆光窗户动作与携包经过 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip |
| S26 | 收拾衣物与篮子 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip |
| S27 | 厨房扫地_局部视野 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip |
| S28 | 门边手部小物体_钥匙可观察性 | https://www.youtube.com/watch?v=jNsO1K0mRwI |
| S29 | 狗打开柜门并拉扯垃圾袋 | https://www.youtube.com/watch?v=-82STtPbfEc |
| S30 | 人员拿包裹时身体遮挡 | https://www.youtube.com/watch?v=Xl-R3YCQRkY |
| S31 | 离家后短暂返回门口 | https://www.youtube.com/watch?v=WRnhem3hsxc |
| S32 | 清理桌面并擦拭_表演采集 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip |
| S33 | 固定机位车库清扫 | https://ai2-public-datasets.s3-us-west-2.amazonaws.com/charades/Charades_v1_480.zip |12345678910111213141516---title: OneAlign (Visual Quality/Aesthetic Scorer)emoji: ⚖️colorFrom: greencolorTo: redsdk: gradiosdk_version: 4.12.0app_file: app.pypinned: truelicense: mitpython_version: 3.10.14---arxiv.org/abs/2312.17090Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849---title: Home Pulseemoji: 🏡colorFrom: greencolorTo: yellowsdk: gradiosdk_version: 6.30.0python_version: 3.12app_file: app.pypinned: falseshort_description: 用一句话设置家庭关注,确认对象,再交给视觉 AI 观察。tags:- zerogpu- computer-vision- smart-homemodels:- mohit67890/imajev-4b- Qwen/Qwen3.5-4B---# Home Pulse家的消息,刚刚好。**说明需求 → 看图确认对象与范围 → 澄清触发条件 → jev 试观察 → 启用 → 记忆复用。**This Space keeps the custom React interface and deterministic Node.js contract engine on free CPU hardware. Kimi handles user intent and visual grounding; visual decisions use the documented API of [the author's imajev Space](https://huggingface.co/spaces/mohit67890/imajev), running on HF ZeroGPU. The browser calls Gradio and the gateway forwards the visitor's `x-ip-token` to the model Space, following HF's cross-Space quota protocol. A short-lived authenticated loopback bridge connects visual responses to the rule engine.## Run and configure- `ANKER_KIMI_API_KEY`: server-side Space Secret for the competition Kimi API.- Web hardware: **CPU Basic**. Visual backend: shared **ZeroGPU**. No paid hardware is requested.- Open the direct `.hf.space` address to use the complete app on desktop or mobile browsers.- Each browser has its own random workspace credential. Its memories, uploads, contracts and metrics are isolated from other visitors. Clearing browser storage also removes that browser's workspace credential.- Free GPU allocation may queue and is subject to Hugging Face's visitor quota. Continuous observation runs while the observation page is open.- Application data lives on the Space's temporary disk. Export important records before a rebuild; free Space storage is not a durable database.- Task setup uses Kimi; images used for visual execution go to the HF Space. Secrets, local personal memories and local execution logs are excluded from the repository.## Models and attribution- [Imajev](https://github.com/mohit67890/imajev), by Mohit Garg, Apache-2.0. Only the required unmodified inference source is included under `upstream/`; its license is retained.- [mohit67890/imajev-4b](https://huggingface.co/mohit67890/imajev-4b), adapter revision `f8d8234cebc6c99065c07731e59716dc0a6e27ab`.- [Qwen/Qwen3.5-4B](https://huggingface.co/Qwen/Qwen3.5-4B), revision `851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a`, Apache-2.0.- The shared model service manages its own model revision; requests enable its calibration and resize images to 640 pixels. It can update or be temporarily unavailable. Local NF4 results are not a claim about this hosted runtime.- `app_zerogpu.py` and `requirements-zerogpu.txt` retain the separate own-GPU deployment option. That variant downloads the pinned revisions above from HF and uses BF16. It requires an account with ZeroGPU hosting access.- Original model files are not modified or republished.- Sample video source attribution is preserved in `media-library/说明与索引/完整素材索引.json` and `MEDIA-SOURCES.md`.The app provides image/video observation, bounded rule execution, on-page notifications, memories and operational metrics. Hardware camera events and phone push notifications are not connected.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import gradio as grimport argparseimport datetimeimport jsonimport osimport timeimport gradio as grimport requestsfrom PIL import Imagefrom q_align.model.builder import load_pretrained_modelfrom q_align.conversation import (default_conversation, conv_templates,SeparatorStyle)from q_align.constants import LOGDIRfrom q_align.utils import (build_logger, server_error_msg,violates_moderation, moderation_msg)from q_align.evaluate.scorer import QAlignScorer, QAlignAestheticScorer, QAlignVideoScorerimport gradio as grdef load_video(video_file):from decord import VideoReadervr = VideoReader(video_file)# Get video frame ratefps = vr.get_avg_fps()# Calculate frame indices for 1fpsframe_indices = [int(fps * i) for i in range(int(len(vr) / fps))]frames = vr.get_batch(frame_indices).asnumpy()return [Image.fromarray(frames[i]) for i in range(int(len(vr) / fps))]pretrained="q-future/one-align"device="cuda:0"tokenizer, model, image_processor, _ = load_pretrained_model(pretrained, None, "mplug_owl2", device=device)iqa_scorer = QAlignScorer(tokenizer=tokenizer, model=model, image_processor=image_processor)iaa_scorer = QAlignAestheticScorer(tokenizer=tokenizer, model=model, image_processor=image_processor)vqa_scorer = QAlignVideoScorer(tokenizer=tokenizer, model=model, image_processor=image_processor)scorers = {"Image Aesthetics (IAA)": iaa_scorer, "Image Quality (IQA)": iqa_scorer, "Video Quality (VQA)": vqa_scorer}LEVELS = ["excellent (5)", "good (4)", "fair (3)", "poor (2)", "bad (1)"]scores = [5,4,3,2,1]def image_classifier(input_img, input_vid, scorer_type):if scorer_type is None:scorer_type = "Image Quality (IQA)"this_scorer = scorers[scorer_type]if input_vid is not None:input_ = load_video(input_vid)elif input_img is not None:input_ = [input_img]if "Video" in scorer_type:input_ = [input_]probs = this_scorer(input_).mean(0).tolist()prob_dict = {LEVEL: prob for LEVEL, prob in zip(LEVELS, probs)}score = sum([prob * score for score, prob in zip(scores, probs)])return prob_dict, scoretitle_markdown = ("""<div style="width: 100%; text-align: center; margin:auto;"><img style="width: 100%" src="https://raw.githubusercontent.com/Q-Future/Q-Align/main/fig/onescorer.png"></div><h4 align="center"> If you like the OneScorer, please give us a star ✨ on <a href='https://github.com/Q-Future/Q-Align'>[GitHub]</a> for latest update. </h4><h5 align="center"><div style="display:flex; gap: 0.25rem;" align="center"><a href='https://q-align.github.io'><img src='https://img.shields.io/badge/Homepage-green'></a><a href='https://github.com/Q-Future/Q-Align'><img src='https://img.shields.io/badge/Github-Code-blue'></a><a href="https://Q-Future.github.io/Q-Align/fig/Q_Align_v0_1_preview.pdf"><img src="https://img.shields.io/badge/Technical-Report-red"></a><a href='https://github.com/Q-Future/Q-Align/stargazers'><img src='https://img.shields.io/github/stars/Q-Future/Q-Align.svg?style=social'></a></div></h5>""")input_img = gr.Image(type='pil', label="Upload an Image")input_vid = gr.Video(label="Upload a Video (will INGORE the image if a video is uploaded)",sources=["upload"])radio = gr.Radio(["Image Aesthetics (IAA)", "Image Quality (IQA)", "Video Quality (VQA)"], label="Task", info="Which Scorer will you need?")input_img = gr.Image(type='pil', label="Upload an Image")labels = gr.Label(label="Probabilities of rating levels:")number = gr.Number(label="Output score:", info="Range in [1,5]. Higher is better.", precision=4)demo = gr.Interface(fn=image_classifier, inputs=[input_img, input_vid, radio], outputs=[labels, number], description=title_markdown, examples=[["fig/eiffel_a.jpg", None, "Image Aesthetics (IAA)"], ["fig/singapore_flyer_2.jpg", None, "Image Quality (IQA)"], ["fig/none.png", "fig/10244479353.mp4", "Video Quality (VQA)"]], article="This is the Scorer Demo as Proposed by Paper: 'Q-Align: Teaching LMMs for Visual Scoring via Discrete Text-Defined Levels'. The proposed Q-Align achieves state-of-the-art performance on image quality assessment (IQA), image aesthetic assessment (IAA), as well as video quality assessment (VQA) tasks under the original LMM structure. With the syllabus, we further unify the three tasks into one model, termed the **OneAlign**, to which the demo corresponds.")demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""Home Pulse's React UI and Node contracts, with the public HF imajev GPU API."""from gradio_client import Clientimport atexitimport jsonimport osfrom pathlib import Pathimport reimport secretsimport shutilimport subprocessimport threadingimport base64import ioimport timefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerimport gradio as grimport httpxfrom fastapi import Requestfrom fastapi.responses import HTMLResponse, JSONResponse, StreamingResponsefrom fastapi.staticfiles import StaticFilesfrom starlette.background import BackgroundTaskROOT=Path(__file__).resolve().parentDATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse'))INTERNAL_KEY=secrets.token_hex(32)NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','7861'))PORT=int(os.getenv('PORT','7860'))WORKSPACE=re.compile(r'^[a-f0-9]{64}$')VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')os.environ.setdefault('TOKENIZERS_PARALLELISM','false')os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY,HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model')node=shutil.which('node')if not node: raise RuntimeError('Node.js is unavailable')node_process=subprocess.Popen([node,str(ROOT/'web/server-bundle.mjs')],cwd=ROOT/'web')atexit.register(node_process.terminate)REMOTE_SPACE=os.getenv('HOME_PULSE_REMOTE_SPACE','mohit67890/imajev')app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None)class ModelBridge(BaseHTTPRequestHandler):def do_POST(self):if self.path!='/v1/systemone' or self.headers.get('X-Bridge-Key')!=INTERNAL_KEY:self.send_error(403);returntry:length=int(self.headers.get('Content-Length','0'))if not 0<length<=6*1024*1024: raise ValueError('Invalid request size')payload=json.loads(self.rfile.read(length))payload['calibrated']=Truefrom PIL import Imageresized=[]for item in payload.get('images',[]):with Image.open(io.BytesIO(base64.b64decode(item.split(',',1)[1],validate=True))) as original:if original.width*original.height>16_000_000:raise ValueError('Image dimensions too large')image=original.convert('RGB');image.thumbnail((640,640));data=io.BytesIO();image.save(data,format='JPEG',quality=90)resized.append('data:image/jpeg;base64,'+base64.b64encode(data.getvalue()).decode())payload['images']=resizedvalue=self.remote_client.predict(payload,api_name='/systemone')body=json.dumps(value).encode();self.send_response(200)except Exception as exc:print('Visual request failed:',type(exc).__name__,str(exc)[:200],flush=True)message='HF 免费 GPU 额度暂时用完,请在额度恢复后再观察。' if re.search('quota|exceeded',str(exc),re.I) else 'HF 视觉服务暂时未返回结果,请稍后重试。'body=json.dumps({'error':message}).encode();self.send_response(503)self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)def log_message(self,*args): pass@app.api(name='visual',concurrency_limit=1,api_visibility='undocumented')def visual(route:str,body:str,workspace:str,request:gr.Request)->dict:if not VISUAL.fullmatch(route) or not WORKSPACE.fullmatch(workspace):return {'status':400,'body':{'error':'观察请求无效'}}if len(body.encode())>6*1024*1024:return {'status':413,'body':{'error':'画面过大'}}# HF's documented cross-Space protocol preserves the visiting user's quota.token=request.headers.get('x-ip-token','') if request else ''remote=Client(REMOTE_SPACE,headers={'x-ip-token':token} if token else {},verbose=False)class VisitorBridge(ModelBridge):remote_client=remotebridge=ThreadingHTTPServer(('127.0.0.1',0),VisitorBridge)thread=threading.Thread(target=bridge.serve_forever,daemon=True);thread.start()try:with httpx.Client(trust_env=False,timeout=210) as client:response=client.post(f'http://127.0.0.1:{NODE_PORT}'+route,content=body,headers={'Content-Type':'application/json','X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace,'X-Home-Pulse-Vision-Port':str(bridge.server_port)})return {'status':response.status_code,'body':response.json()}finally:bridge.shutdown();bridge.server_close()@app.get('/_model/v1/models')def models():global model_healthif time.monotonic()-model_health[0]>45:try:info=httpx.get('https://huggingface.co/api/spaces/'+REMOTE_SPACE,timeout=5).json()model_health=(time.monotonic(),info.get('runtime',{}).get('stage')=='RUNNING')except Exception:model_health=(time.monotonic(),False)if not model_health[1]:return JSONResponse({'error':'HF 视觉服务正在连接'},status_code=503)return {'data':[{'id':'imajev-4b-hf-shared'}],'runtime':{'model':'imajev-4b-hf-shared','gpu':'HF ZeroGPU · 共享算力','memoryGiB':None,'quantization':'BF16 · 共享服务','maxImageSide':640}}model_health=(0,False)@app.api_route('/api/{path:path}',methods=['GET','POST'])async def api_proxy(path:str,request:Request):workspace=request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')if not WORKSPACE.fullmatch(workspace):return JSONResponse({'error':'请刷新页面,重新连接你的空间'},status_code=401)if request.method=='POST' and VISUAL.fullmatch('/api/'+path):return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host')}headers.update({'X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace})client=httpx.AsyncClient(trust_env=False,timeout=220)try:target=f'http://127.0.0.1:{NODE_PORT}/api/'+path+('?' + request.url.query if request.url.query else '')outbound=client.build_request(request.method,target,headers=headers,content=request.stream())response=await client.send(outbound,stream=True)except Exception:await client.aclose();return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502)async def close(): await response.aclose();await client.aclose()kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')}return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close))app.mount('/assets',StaticFiles(directory=ROOT/'web/dist/assets'),name='assets')app.mount('/media',StaticFiles(directory=ROOT/'web/dist/media'),name='media')html=(ROOT/'web/dist/index.html').read_text(encoding='utf-8').replace('<head>','<head><script>window.__HOME_PULSE_CLOUD__=true</script>')async def page():return HTMLResponse(html,headers={'Cache-Control':'no-cache'})for route in ('/','/home','/watches','/create','/memories','/events','/review','/insights','/privacy','/watch/{item_id}','/observe/{item_id}'):app.add_api_route(route,page,methods=['GET'],include_in_schema=False)@app.get('/favicon.svg')def favicon():from fastapi.responses import FileResponsereturn FileResponse(ROOT/'web/dist/favicon.svg')if __name__=='__main__':app.launch(server_name='0.0.0.0',server_port=PORT,show_error=False)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Home Pulse's React UI + Node contracts + Gradio/ZeroGPU visual execution."""
import spaces # Must precede torch and model imports for ZeroGPU CUDA emulation.
import atexit
import json
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import gradio as gr
import httpx
from fastapi import Request
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from starlette.background import BackgroundTask
from model_runtime import load_model, predict
ROOT=Path(__file__).resolve().parent
DATA=Path(os.getenv('HOME_PULSE_DATA_DIR','/tmp/home-pulse'))
INTERNAL_KEY=secrets.token_hex(32)
NODE_PORT=int(os.getenv('HOME_PULSE_API_PORT','7861'))
PORT=int(os.getenv('PORT','7860'))
WORKSPACE=re.compile(r'^[a-f0-9]{64}$')
VISUAL=re.compile(r'^/api/(?:setup/trial|analyze|contracts/observe)$')
os.environ.setdefault('TOKENIZERS_PARALLELISM','false')
os.environ.setdefault('HF_HUB_DISABLE_IMPLICIT_TOKEN','1')
os.environ.setdefault('GRADIO_ANALYTICS_ENABLED','False')
os.environ.update(HOME_PULSE_DATA_DIR=str(DATA), HOME_PULSE_CLOUD='1', HOME_PULSE_INTERNAL_KEY=INTERNAL_KEY,
HOME_PULSE_MEDIA_ROOT=str(ROOT/'media-library'),HOME_PULSE_MODEL_URL=f'http://127.0.0.1:{PORT}/_model')
node=shutil.which('node')
if not node: raise RuntimeError('Node.js is unavailable')
node_process=subprocess.Popen([node,str(ROOT/'web/server-bundle.mjs')],cwd=ROOT/'web')
atexit.register(node_process.terminate)
backend,calibration=load_model()
app=gr.Server(title='Home Pulse',docs_url=None,redoc_url=None)
class ModelBridge(BaseHTTPRequestHandler):
def do_POST(self):
if self.path!='/v1/systemone' or self.headers.get('X-Bridge-Key')!=INTERNAL_KEY:
self.send_error(403);return
try:
length=int(self.headers.get('Content-Length','0'))
if not 0<length<=6*1024*1024: raise ValueError('Invalid request size')
value=predict(backend,calibration,json.loads(self.rfile.read(length)))
body=json.dumps(value).encode();self.send_response(200)
except Exception as exc:
print('Visual request failed:',type(exc).__name__,str(exc)[:200],flush=True)
body=json.dumps({'error':'视觉判断暂时未完成,请重试'}).encode();self.send_response(422)
self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
def log_message(self,*args): pass
def gpu_duration(route,body,workspace):
return 40 if route=='/api/setup/trial' else 12
@app.api(name='visual',concurrency_limit=1,api_visibility='undocumented')
@spaces.GPU(duration=gpu_duration)
def visual(route:str,body:str,workspace:str)->dict:
if not VISUAL.fullmatch(route) or not WORKSPACE.fullmatch(workspace):
return {'status':400,'body':{'error':'观察请求无效'}}
if len(body.encode())>6*1024*1024:return {'status':413,'body':{'error':'画面过大'}}
# This bridge lives inside the allocated GPU worker. The Node rule engine calls
# it synchronously while it checks the trial or advances a monitoring contract.
bridge=ThreadingHTTPServer(('127.0.0.1',0),ModelBridge)
thread=threading.Thread(target=bridge.serve_forever,daemon=True);thread.start()
try:
with httpx.Client(trust_env=False,timeout=115) as client:
response=client.post(f'http://127.0.0.1:{NODE_PORT}'+route,content=body,headers={
'Content-Type':'application/json','X-Home-Pulse-Internal':INTERNAL_KEY,
'X-Home-Pulse-Workspace':workspace,'X-Home-Pulse-Vision-Port':str(bridge.server_port)})
return {'status':response.status_code,'body':response.json()}
finally:
bridge.shutdown();bridge.server_close()
@app.get('/_model/v1/models')
def models():
return {'data':[{'id':backend.model}],'runtime':{'model':backend.model,'gpu':'HF ZeroGPU · 按需分配','memoryGiB':None,'quantization':'BF16','maxImageSide':640}}
@app.api_route('/api/{path:path}',methods=['GET','POST'])
async def api_proxy(path:str,request:Request):
workspace=request.headers.get('x-home-pulse-workspace') or request.cookies.get('hp_workspace','')
if not WORKSPACE.fullmatch(workspace):return JSONResponse({'error':'请刷新页面,重新连接你的空间'},status_code=401)
if request.method=='POST' and VISUAL.fullmatch('/api/'+path):
return JSONResponse({'error':'请通过页面发起 GPU 观察'},status_code=400)
headers={k:v for k,v in request.headers.items() if k.lower() in ('content-type','content-length','range','x-file-name','origin','host')}
headers.update({'X-Home-Pulse-Internal':INTERNAL_KEY,'X-Home-Pulse-Workspace':workspace})
client=httpx.AsyncClient(trust_env=False,timeout=220)
try:
target=f'http://127.0.0.1:{NODE_PORT}/api/'+path+('?' + request.url.query if request.url.query else '')
outbound=client.build_request(request.method,target,headers=headers,content=request.stream())
response=await client.send(outbound,stream=True)
except Exception:
await client.aclose();return JSONResponse({'error':'空间连接暂时中断,请重试'},status_code=502)
async def close(): await response.aclose();await client.aclose()
kept={k:v for k,v in response.headers.items() if k.lower() in ('content-type','content-length','content-range','accept-ranges','cache-control','content-disposition')}
return StreamingResponse(response.aiter_raw(),status_code=response.status_code,headers=kept,background=BackgroundTask(close))
app.mount('/assets',StaticFiles(directory=ROOT/'web/dist/assets'),name='assets')
app.mount('/media',StaticFiles(directory=ROOT/'web/dist/media'),name='media')
html=(ROOT/'web/dist/index.html').read_text(encoding='utf-8').replace('<head>','<head><script>window.__HOME_PULSE_CLOUD__=true</script>')
async def page():return HTMLResponse(html,headers={'Cache-Control':'no-cache'})
for route in ('/','/home','/watches','/create','/memories','/events','/review','/insights','/privacy','/watch/{item_id}','/observe/{item_id}'):
app.add_api_route(route,page,methods=['GET'],include_in_schema=False)
@app.get('/favicon.svg')
def favicon():
from fastapi.responses import FileResponse
return FileResponse(ROOT/'web/dist/favicon.svg')
if __name__=='__main__':
app.launch(server_name='0.0.0.0',server_port=PORT,show_error=False)123version https://git-lfs.github.com/spec/v1oid sha256:0139566e1e3ed9f452472cd444236f745e3dcce99b0648fb01d9a8835af25ef9size 1072646123version https://git-lfs.github.com/spec/v1oid sha256:c011225e9859ee9301997f658b6ef254186c4617aeda8f27510491992a138cb4size 4431305
123version https://git-lfs.github.com/spec/v1oid sha256:154e74795d12bf904091cdc7479f997865dd6339c85040012e7cab28cd863e30size 1523613123version https://git-lfs.github.com/spec/v1oid sha256:e1a4cc7124c1c10b3d7cda67163b50799cb6910552beba511702d88e072d416dsize 2468175
123version https://git-lfs.github.com/spec/v1oid sha256:3622a90a5996034e3bfdde33cd39f429f8a97ed0a3c1226c9f94eda154d0a968size 3157631123version https://git-lfs.github.com/spec/v1oid sha256:642764d1a6178c54d5b0e270b8e17a6ce5f66864b8a2267683f75012532c3ef0size 3445934
123version https://git-lfs.github.com/spec/v1oid sha256:9f6abc40a22cc4cdd3b5a926566c901981e357be58324284b656872abf5964c3size 1671611123version https://git-lfs.github.com/spec/v1oid sha256:caef889954f5c202287bc6241c54e6d0579c98b0ae33cd0e841ed592ffe57484size 3033512
123version https://git-lfs.github.com/spec/v1oid sha256:a0e3b0927e29b937f362d318edc039140c32c97b5f2197ae74222027809a6e7asize 7782483123version https://git-lfs.github.com/spec/v1oid sha256:5df7644187513e706f6231d3a893a87db1931946c016eaa36c328d3e863af385size 25902123version https://git-lfs.github.com/spec/v1oid sha256:33051945cea04a96f12a66c1a919cd664fd941bc33b53246254e0007391ee935size 320723
123version https://git-lfs.github.com/spec/v1oid sha256:15e4666860a6dfc433cf230e21ae692197a811940c6d1a1f00f728db3833d3e5size 2867089123version https://git-lfs.github.com/spec/v1oid sha256:6583f1e22909aa4ac9570a65e9f6923f81d5e6d6b35869109f310c9983d7f37fsize 4094116123version https://git-lfs.github.com/spec/v1oid sha256:51cbfe2e637f7418fabdd7a2ed825f027f5f34de54efc943af5faed173d135ecsize 4257452123version https://git-lfs.github.com/spec/v1oid sha256:0f9e6e8ca19b976a4b84262647314c17b61312a4fcf542eb921684b4eb74839bsize 16885712123version https://git-lfs.github.com/spec/v1oid sha256:2ee21c33e798333bcd43436f38da39f8a0a773131487ad9585e77311854716ffsize 2509003123version https://git-lfs.github.com/spec/v1oid sha256:7f926247ac9815f541673a37233915d079193d1ab306b3a9d4ea21d6d553e6a4size 283907123version https://git-lfs.github.com/spec/v1oid sha256:003431be7a70d4f66324e4bff9b18e81fc9c8ccfa29c937d4080f8d824233068size 666171
123version https://git-lfs.github.com/spec/v1oid sha256:781f3430896c16fd03cb2c2735056f2eee65fc611c22c3f82935497554075876size 3593305123version https://git-lfs.github.com/spec/v1oid sha256:908a45b1ab0b1156c5bd9d8f827b26d57a6a335296bb6c8d8b8eb8eaaf291d64size 1666677123version https://git-lfs.github.com/spec/v1oid sha256:09f86ecd97a2a16a79a8ccbc3acc8d8fa435e53e34da6d9fe144083446d2c644size 144442123version https://git-lfs.github.com/spec/v1oid sha256:9c0b85ed18e928fa5fe84abc083f8c3eb97a7f7ce1842697fe489bc1f5248ec1size 939520
123version https://git-lfs.github.com/spec/v1oid sha256:e98bf467108fa1502b8a6fb916f0fe1a47c68b51f035f11753b5423cfa9b781asize 1181814123version https://git-lfs.github.com/spec/v1oid sha256:65f74beb2d80ea2c246d2407d6186f8c3f19ba06c125ebdffbd372a058e11422size 602318123version https://git-lfs.github.com/spec/v1oid sha256:891f90f23e85afc00d79637bd52f8847407a4ae29cb1808c5c5aa16aa16e327csize 3365441123version https://git-lfs.github.com/spec/v1oid sha256:6c3e8e84a9128391f12aeca8d5df3fdde7902ff95c6c65117ed8014bb9085296size 1292660123version https://git-lfs.github.com/spec/v1oid sha256:db22363ad8304458d586979e866763a5a218ca3ded62ea95087697fa4d561ac0size 1399556123version https://git-lfs.github.com/spec/v1oid sha256:564bca14aae364c1675d336a2bbc774e2710d257a5c814aff7d1c5fd6ab5a026size 8640133123version https://git-lfs.github.com/spec/v1oid sha256:33873bb3eda06024d63db739c07a0828291767ac619f08fc086e2de957cd855asize 16668998123version https://git-lfs.github.com/spec/v1oid sha256:5569f6fc913791de712ab586343a38c14e35d2b1143e5f59693281a0bcbf1b7esize 1642478123version https://git-lfs.github.com/spec/v1oid sha256:488febab0e48543d1f392f6ef190f45363651efc2e49c4e06896f63321374d52size 1249496123version https://git-lfs.github.com/spec/v1oid sha256:77957d3920bd0ce617946acfcbb1b2f1fac0bbae129e8354510b087c917055d5size 1360843123version https://git-lfs.github.com/spec/v1oid sha256:4477b4649ff4ada0ba39b27c81f296cf2f12b64b99715ffc379c3eebc24b8820size 1214593123version https://git-lfs.github.com/spec/v1oid sha256:a44680763f837410191ef618b7a3310ee7e178deb5d7372f4f621a43608dca33size 1394804123version https://git-lfs.github.com/spec/v1oid sha256:3ef2fff976523439d25b1bf2592f42f9628fde955568bd5f876f6b734fd1324dsize 1942713123version https://git-lfs.github.com/spec/v1oid sha256:42d548742da2a82971fc74e95bb56faf3d00490885b7d2c60120c2fc151de7c5size 7069638123version https://git-lfs.github.com/spec/v1oid sha256:f550a4980d685ab5af07dca3bcd15cc9afb376551e9f42d5797f5e700bd2bfb1size 1898144123version https://git-lfs.github.com/spec/v1oid sha256:9f962b09ed65516dcc62b2e205680ee3771d6c38fae37d73e976d91ee01f80a2size 2524105123version https://git-lfs.github.com/spec/v1oid sha256:9487304f1cb3e3807b1c47dabbad80660779a91d17cb4e2caf750fe550014eb7size 1940356123version https://git-lfs.github.com/spec/v1oid sha256:d9111bed3120b857c5fcdf83a27c9c88a5eae6640ff237cc8570da0cc2f0b0besize 2837778123version https://git-lfs.github.com/spec/v1oid sha256:54287efc54404ee33e984c91ed327d0bdad7cd3315d2d0c00c84e5132e5f3f20size 215127123version https://git-lfs.github.com/spec/v1oid sha256:685150db6e5cfd396f82e116e9fcaa83a6bdde634dd271d95a3e818280200903size 226630123version https://git-lfs.github.com/spec/v1oid sha256:67a70ed4e1c7b343eca6af014cc4cbd1df4b32358def273e1db45c20e7908ee4size 548387123version https://git-lfs.github.com/spec/v1oid sha256:f4c8f26b01b29f925346a4fb9e6a8850515488836dfb004b2233c7b8e2aedba5size 581968123version https://git-lfs.github.com/spec/v1oid sha256:a674d025922cf7ee6714d1181d5a34105427261c9630c8601e8e33cc88adad6asize 3861778123version https://git-lfs.github.com/spec/v1oid sha256:557055b2fdc060a59396eb02fabf676beac72ac5e9f19785683a5190c89d3dc8size 1009363123version https://git-lfs.github.com/spec/v1oid sha256:514dafc4deb7e95f72dca3906238e362c3c4ff50278ec17877c00979d1563495size 2553060123version https://git-lfs.github.com/spec/v1oid sha256:0d987545482e4807ad9d7a9e1a663d62e2acac8eb6625e9aefaf4012f163e0a0size 870997123version https://git-lfs.github.com/spec/v1oid sha256:ffe719eef43291401f810c6d9fd0c6fc3956b7148ae85ace8d9ab87ba8b115cdsize 715787123version https://git-lfs.github.com/spec/v1oid sha256:b80c6f6c21bd55830fbce317f49cb383de4b755710826400c8128ec1125ad9f6size 1827868.gitattributes+6-35
MEDIA-SOURCES.mdAdded+61
README.md+42-9
app.py+136-95
app_zerogpu.pyAdded+115
fig/10102107193.mp4 → media-library/clips/S01.mp4Renamed+2-2
fig/10244479353.mp4 → media-library/clips/S02.mp4Renamed+2-2
fig/eiffel_a.jpg → media-library/clips/S03.mp4Renamed+2-2
fig/longgang_nightblur.png → media-library/clips/S04.mp4Renamed+2-2
media-library/clips/S05.mp4Added+3
fig/none.png → media-library/clips/S06.mp4Renamed+2-2
media-library/clips/S07.mp4Added+3
media-library/clips/S08.mp4Added+3
media-library/clips/S09.mp4Added+3
media-library/clips/S10.mp4Added+3
media-library/clips/S11.mp4Added+3
fig/onescorer.png → media-library/clips/S12.mp4Renamed+2-2
media-library/clips/S13.mp4Added+3
media-library/clips/S14.mp4Added+3
fig/singapore_flyer_2.jpg → media-library/clips/S15.mp4Renamed+2-2
media-library/clips/S16.mp4Added+3
media-library/clips/S17.mp4Added+3
media-library/clips/S18.mp4Added+3
media-library/clips/S19.mp4Added+3
media-library/clips/S20.mp4Added+3
media-library/clips/S21.mp4Added+3
media-library/clips/S22.mp4Added+3
media-library/clips/S23.mp4Added+3
media-library/clips/S24.mp4Added+3
media-library/clips/S25.mp4Added+3
media-library/clips/S26.mp4Added+3
media-library/clips/S27.mp4Added+3
media-library/clips/S28.mp4Added+3
media-library/clips/S29.mp4Added+3
media-library/clips/S30.mp4Added+3
media-library/clips/S31.mp4Added+3
media-library/clips/S32.mp4Added+3
media-library/clips/S33.mp4Added+3
media-library/clips/negative_01.mp4Added
media-library/clips/negative_02.mp4Added
media-library/clips/negative_03.mp4Added+3
media-library/clips/negative_04.mp4Added+3
media-library/clips/negative_05.mp4Added+3
media-library/clips/negative_06.mp4Added+3
media-library/clips/smartbench_0007.mp4Added+3
media-library/clips/smartbench_0036.mp4Added+3
media-library/clips/smartbench_0058.mp4Added+3
media-library/clips/smartbench_0083.mp4Added+3
media-library/clips/smartbench_0094.mp4Added+3
media-library/clips/smartbench_0133.mp4Added+3