ZevonLew commited on
Commit
435ecd3
·
verified ·
1 Parent(s): 01b49f7

Upload 63 files

Browse files
Files changed (15) hide show
  1. AGENTS.md +1 -1
  2. README.md +65 -122
  3. app.js +3 -3
  4. app.py +33 -0
  5. docs/dev/DESIGN.md +2 -0
  6. docs/dev/LATEST.md +6 -0
  7. docs/wish/DESIGN.md +2 -0
  8. docs/wish/LATEST.md +4 -0
  9. how-to-start.html +2 -2
  10. how-to-start.pdf +2 -2
  11. index.html +3 -3
  12. packages.txt +2 -0
  13. recognizers.js +101 -101
  14. requirements.txt +4 -1
  15. server.py +129 -129
AGENTS.md CHANGED
@@ -31,7 +31,7 @@ Boundary: Code/files plus live Hugging Face runtime own current behavior; govern
31
  <!-- wr92-course-project-rules-20261012:start -->
32
  ## Local authority and routing
33
 
34
- Current implementation update,2026-10-13: the user authorized a convenient solution requiring no backend design by them. The supplied app is now a Docker CPU Space. Face/OCR remain in-browser; gestures use the same MediaPipe0.10.18 task on the Space CPU if WebGL2 or the graphics context fails. The UI discloses gesture image transfer, with no image/result persistence. Deployment files,9-file patch and runtime evidence are prepared locally; no remote push or HF container-runtime claim is implied. Earlier Static references below are history. Read the local Wish/Dev for the current CPU compatibility path.
35
 
36
  Profile: product-space; role: AI-Power Image Recognition browser-based pretrained teaching Space (face verification, static hand gestures, and English OCR).
37
 
 
31
  <!-- wr92-course-project-rules-20261012:start -->
32
  ## Local authority and routing
33
 
34
+ Current user requirement,2026-10-13: do not use Docker, request a PRO subscription or hardware downgrade. The app now uses the native Gradio SDK and app.py, keeping the same course UI/models. requirements.txt/packages.txt install automatically. Existing ZeroGPU hardware is compatible with the Gradio SDK; this application makes no GPU execution request. Face/OCR remain in-browser, while the same gesture model uses Space CPU when browser graphics fail. The UI discloses image transfer with no persistence. Local Gradio runtime verification and a single complete upload package are required. Earlier Docker/Static descriptions below are history, not current deployment instructions.
35
 
36
  Profile: product-space; role: AI-Power Image Recognition browser-based pretrained teaching Space (face verification, static hand gestures, and English OCR).
37
 
README.md CHANGED
@@ -1,122 +1,65 @@
1
- ---
2
- title: AI-Power Image Recognition
3
- emoji: 👁️
4
- colorFrom: blue
5
- colorTo: indigo
6
- sdk: docker
7
- app_port: 7860
8
- pinned: false
9
- ---
10
-
11
- # AI-Power Image Recognition
12
-
13
- **恢复版本:20261013-recovery-1。** 本轮请只使用 `AI-Power_Image_Recognition_HF_Recovery_20261013.zip` 的完整52文件上传。页面底部必须显示该版本与“Space CPU service ready”。HTML、界面和模型模块版本不同会阻止运行并说明文件混用,防止旧整包覆盖人脸修复。`/api/health`返回相同version表示CPU服务已经启动。
14
-
15
- ## 中文说明
16
-
17
- 本课程项目由 `wr92-course/test` 目标检测教学仓库克隆改造,来源提交为 `9d11aee0c2c539b5a5781e12215136c599b01fb0`。当前应用包含三个浏览器实验:
18
-
19
- | 任务 | 实现 | 输入与输出 | 设置 |
20
- |---|---|---|---|
21
- | 人脸验证 | face-api.js 0.22.2:Tiny Face Detector、68点关键点、128维描述子 | 两张各有一张脸的图片;距离与匹配判定 | 距离阈值,越低越严格 |
22
- | 手势识别 | MediaPipe Tasks Vision 0.10.18 | 静态图片,最多两只手;关键点、候选、分数、接受标签 | 分数阈值,越高越严格 |
23
- | 文字OCR | Tesseract.js 5.1.1,英文LSTM数据 | 英文印刷体图片;文字、词框、置信度 | 文本块、稀疏文字、单行 |
24
-
25
- 英文为默认学生界面,可独立切换中文。中文界面不会改变OCR语言;基础版仅包含英文识别数据。
26
-
27
- ### 学习顺序
28
-
29
- 选择任务和自生成样例 → 运行真实预训练模型 → 观察输入、叠加图和输出 → 只改变一个设置 → 导出JSON并解释一个成功与一个局限。
30
-
31
- ### 本地运行与托管
32
-
33
- 推荐直接上传完整CPU部署包到Hugging Face Space根目录。本卡片配置 `sdk: docker`、端口7860,平台按照附带Dockerfile自动构建;使用CPU Basic,无需GPU。已有Static Space也可通过覆盖本README和上传Dockerfile切换SDK,具体机制见[官方Docker Spaces说明](https://huggingface.co/docs/hub/spaces-sdks-docker)。
34
-
35
- 人脸和OCR继续在浏览器运行。手势优先在浏览器运行,WebGL2不可用或图形上下文失败时自动调用本Space的CPU接口,使用相同MediaPipe 0.10.18与同一份 `gesture_recognizer.task`。用户已部署[课程Space](https://huggingface.co/spaces/ZevonLew/Image_Recognition),需上传本轮全部补丁文件并等待Docker启动后,线上才能获得CPU兼容能力。本流程未推送远程仓库。教师课件最后一页仍为配置中的占位链接。
36
-
37
- ### 2026-10-13 CPU兼容修复
38
-
39
- - 在设置图片src前设置 `crossOrigin='anonymous'`,处理Static Space图片重定向到CDN的情况。
40
- - 推理前验证画布像素可读;人脸检测、关键点、描述子任务使用普通Promise传递异常,失败能够返回页面。
41
- - 手势优先使用独立HTML WebGL2画布;无WebGL2、activeTexture或上下文失败时,自动由Space CPU完成本次识别。后端是真实模型推理,不是规则猜测或固定答案。
42
- - 小补丁含9个文件:`index.html`、`app.js`、`recognizers.js`、`README.md`、`Dockerfile`、`server.py`、`requirements.txt`、`how-to-start.html`、`how-to-start.pdf`。必须全部上传,不能只覆盖三个JS/HTML文件。权重不变,已有模型目录无需重传。
43
- - JSON记录 `backend`;比较分数或耗时时固定后端。CPU路径保持图像比例,最长边超过1920像素时缩小;记录输入和处理尺寸。模型和类别未改变,两端预处理可能带来分数差异。
44
- - 本地CPU验证:在隔离环境安装 `requirements.txt`,在本仓库运行 `python -m uvicorn server:app --host 127.0.0.1 --port 8765 --no-access-log`。普通静态HTTP服务仍可运行浏览器路径,但不提供CPU接口。
45
-
46
- ### 文件职责
47
-
48
- - `index.html`、`style.css`:页面结构和样式。
49
- - `app.js`:状态、输入、结果绘制、中文切换和JSON导出。
50
- - `recognizers.js`:三类模型加载与推理,失败时允许重试。
51
- - `server.py`、`Dockerfile`、`requirements.txt`:CPU兼容接口与自动容器部署;接口不保存图片,仅暴露必要页面与资源。
52
- - `models/`、`vendor/`:本地固定版本的权重、运行库与许可证。
53
- - `samples/`:本次新生成的虚构人像、手势和程序排版OCR样例;`ground_truth.json`保存OCR正确文本。
54
- - `how-to-start.html`、`how-to-start.pdf`:配套学生指南。
55
-
56
- 根据用户确认,已将旧 `detector.js`、`wr92-language.js`、`wr92-language.css`、`examples/` 和 `guide-assets/` 共108个无引用文件移出本目录,原件保存于外层 `backup/20261013-191024/`。当前识别代码、模型、依赖、许可证、原创样例、Git记录和项目说明保留;部署包只包含识别应用必需文件。
57
-
58
- ### 使用边界与数据
59
-
60
- 人脸和OCR图片留在当前浏览器。手势CPU兼容模式将图片发送到本Space,在请求内存中解码和推理,不保存图片或结果;页面在运行按钮上方明确提示。应用不持久保存图片、结果或人脸描��子。模型可被缓存;主动JSON导出会生成不含人脸描述子的本地文件。人脸实验不提供身份认证或活体检测;手势不是手语翻译;OCR需要核对;生成样例不能证明真实人群或领域准确率。
61
-
62
- ### 学生提交
63
-
64
- 任选一个任务,提供可运行链接、输入输出解释、一个控制变量实验、一个失败案例和清楚的修改说明。基础作业不要求训练;训练选做需要有许可的标注数据及独立测试。使用本项目之前阅读 [How to Start](./how-to-start.html)。
65
-
66
- ### 验证记录
67
-
68
- 2026-10-13使用本地Edge/Chromium执行真实浏览器推理,覆盖同/不同人物、四种手势、严格阈值、四类OCR、空人脸输入、双语切换和390px布局。记录与截图在教师课程包的 `validation/`。这是本地浏览器验证,不是HF线上部署验证,也不是科学准确率评测。
69
-
70
- ## English
71
-
72
- **Recovery build:20261013-recovery-1.** Upload all52 files from `AI-Power_Image_Recognition_HF_Recovery_20261013.zip`. The footer must show this build and “Space CPU service ready”. Mixed HTML/interface/model versions are blocked before inference. The health endpoint identifies the same CPU build. Do not replace the app with an older49-file Static archive.
73
-
74
- This teaching project was adapted from `wr92-course/test` at commit `9d11aee0c2c539b5a5781e12215136c599b01fb0`. It now contains three browser experiments:
75
-
76
- | Task | Implementation | Input and output | Setting |
77
- |---|---|---|---|
78
- | Face verification | face-api.js 0.22.2: Tiny Face Detector, 68 landmarks, 128-value descriptor | Two images with one face each; distance and decision | Lower distance thresholds are stricter |
79
- | Gesture recognition | MediaPipe Tasks Vision 0.10.18 | Still image, up to two hands; landmarks, candidate, score and accepted label | Higher score thresholds are stricter |
80
- | Text OCR | Tesseract.js 5.1.1 with English LSTM data | Printed English; transcript, word boxes and confidence | Text block, sparse text or one line |
81
-
82
- The student interface defaults to English with a separate Chinese switch. Interface language does not change the OCR language: the baseline ships English recognition only.
83
-
84
- ### Learning path
85
-
86
- Choose a task and generated sample, run a real pretrained model, inspect the input and result, change one setting, export JSON, and explain one success and one limitation.
87
-
88
- ### Running and hosting
89
-
90
- Upload the supplied CPU package to the Space root. The README sets `sdk: docker` and port7860; Hugging Face builds the supplied Dockerfile automatically. Use CPU Basic. An existing Static Space can switch SDK by replacing this README and adding the Dockerfile, as described in the [official Docker Spaces guide](https://huggingface.co/docs/hub/spaces-sdks-docker).
91
-
92
- Face and OCR run in the browser. Gestures use browser inference when graphics work and automatically use this Space CPU when WebGL2 or the graphics context fails. Both paths use MediaPipe 0.10.18 and the same gesture task weights. Upload the complete patch and wait for the Docker startup to update the user's [course Space](https://huggingface.co/spaces/ZevonLew/Image_Recognition). This workflow has not pushed remotely. The slide link remains a placeholder.
93
-
94
- ### CPU compatibility fix · 2026-10-13
95
-
96
- Images retain the anonymous CORS fix and readable-pixel check. Face stages retain ordinary Promise error propagation. Gestures receive an independent HTML WebGL2 canvas; unavailable WebGL2, activeTexture or context errors automatically use the Space CPU endpoint. This runs the real pretrained model, not simulated outputs.
97
-
98
- Upload all nine patch files: `index.html`, `app.js`, `recognizers.js`, `README.md`, `Dockerfile`, `server.py`, `requirements.txt`, `how-to-start.html`, and `how-to-start.pdf`. JavaScript alone cannot add a CPU server to a Static Space. Existing weights do not need to be uploaded again. JSON identifies the backend; keep it fixed when comparing scores or times. CPU inputs above1920 pixels on the longest side are proportionally resized, with dimensions recorded. The models and categories stay the same; preprocessing can cause score differences.
99
-
100
- For local CPU testing, install the requirements in an isolated environment and run `python -m uvicorn server:app --host 127.0.0.1 --port 8765 --no-access-log` in this directory. A plain static HTTP server supports browser inference but has no CPU endpoint.
101
-
102
- ### Files
103
-
104
- - `index.html` and `style.css`: structure and presentation.
105
- - `app.js`: inputs, state, overlays, translation and export.
106
- - `recognizers.js`: model loading and inference with retry after loading failure.
107
- - `server.py`, `Dockerfile`, `requirements.txt`: CPU compatibility and automated container deployment, with no image persistence and a restricted static-file surface.
108
- - `models/` and `vendor/`: pinned weights, runtimes and licenses.
109
- - `samples/`: newly generated fictional portraits, gestures and typeset OCR images; `ground_truth.json` contains independent OCR text.
110
- - `how-to-start.html` and `how-to-start.pdf`: matching student guides.
111
-
112
- With the user's approval,108 unused legacy files were moved out of this directory: `detector.js`, `wr92-language.js`, `wr92-language.css`, `examples/` and `guide-assets/`. Originals are kept in the teacher project's `backup/20261013-191024/`. Active code, models, runtimes, licenses, generated samples, Git history and project guidance remain. Deployment includes only required recognition files.
113
-
114
- ### Data and limitations
115
-
116
- Face and OCR images stay in the browser. CPU compatibility sends the gesture image to this Space, processes it in request memory and does not save the image or result; the input panel states this before Run recognition. The app does not persist images, results or face descriptors. Browsers may cache models. JSON export creates a local file and excludes face descriptors. Face verification is not identity authentication or liveness detection; gestures are not sign-language translation; OCR needs checking. Generated samples do not establish real-world accuracy.
117
-
118
- ### Assignment and validation
119
-
120
- Choose one task and submit a working link, correct output interpretation, a controlled experiment, a failure case and a description of your changes. Training is optional and requires permitted labels and a held-out test.
121
-
122
- Local Edge/Chromium checks on 2026-10-13 covered real face, gesture and OCR inference, errors, translation and a 390px layout. The teacher package contains records under `validation/`. These are local checks, not HF deployment verification or a scientific accuracy benchmark.
 
1
+ ---
2
+ title: AI-Power Image Recognition
3
+ emoji: 👁️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: "5.49.1"
8
+ python_version: "3.10"
9
+ app_file: app.py
10
+ pinned: false
11
+ ---
12
+
13
+ # AI-Power Image Recognition
14
+
15
+ ## 中文说明
16
+
17
+ 当前版本:`20261013-gradio-1`。这是原生Gradio SDK部署包,不使用Docker。将完整包解压后的文件上传到Space根目录,平台自动读取本README、安装requirements.txt与packages.txt,并运行app.py。你当前的ZeroGPU设置可以保留,不需要PRO订阅、改硬件或启用Chrome图形加速。
18
+
19
+ 保留现有英文课程页面、独立中文切换、原创样例和三任务模型:
20
+
21
+ | 任务 | 模型与运行位置 | 输出与设置 |
22
+ |---|---|---|
23
+ | 人脸验证 | face-api.js 0.22.2:Tiny Face Detector、68点、128维描述子;浏览器CPU可运行 | 两张各含一张脸的图;距离与判定,距离阈值越低越严格 |
24
+ | 手势识别 | MediaPipe Tasks Vision 0.10.18;图形不可用时自动由Space CPU运行同一task权重 | 最多两手、21关键点、有限静态类别、分数与接受标签;分数阈值越高越严格 |
25
+ | 英文OCR | Tesseract.js 5.1.1与英文LSTM数据;浏览器运行 | 转写、词框、置信度;布局模式6/11/7 |
26
+
27
+ 本项目不请求GPU执行。Gradio SDK兼容ZeroGPU的配置要求,不需要把硬件降级到CPU Basic。模型文件随包提供,首次浏览器运行仍需要读取它们。界面语言切换不增加中文OCR能力。
28
+
29
+ ### 上传与使用
30
+
31
+ 1. 解压 `AI-Power_Image_Recognition_HF_Gradio.zip`,把内容上传到Space根目录并覆盖,不要再嵌套一层目录。
32
+ 2. 保留README头部的 `sdk: gradio` 和 `app_file: app.py`;不要改回Docker或复制报错页面上的占位模板。
33
+ 3. 等待显示Running,从App标签进入。页面底部应显示 `20261013-gradio-1` 与 `Space CPU service ready`。
34
+ 4. 选择样例 → Run recognition → 观察叠加图和结果 → 改一个设置 → 导出JSON。
35
+
36
+ Space中之前残留的Dockerfile不参与Gradio启动,无需额外删除才能运行。本地test目录已将Dockerfile与旧目标检测资源移入教师备份。app.py是唯一部署入口;index.html仍负责课程页面。
37
+
38
+ ### 文件职责
39
+
40
+ - app.py:Gradio入口,启动相同课程页面与CPU兼容服务。
41
+ - requirements.txt / packages.txt:平台自动安装Python及系统依赖。
42
+ - index.html / style.css / app.js:原有界面、输入、叠加图、双语与导出。
43
+ - recognizers.js / server.py:浏览器模型、同模型手势CPU路径与失败恢复。
44
+ - models/ / vendor/ / samples/:固定版本模型、运行库、许可证与本课程自生成样例。
45
+ - how-to-start.html / how-to-start.pdf:学生指南。
46
+
47
+ 本地运行:在隔离Python环境安装requirements.txt后执行 `python app.py`,访问http://127.0.0.1:7860。基础作业不要求训练。
48
+
49
+ ### 数据与教学边界
50
+
51
+ 人脸与OCR图片留在浏览器;只有手势CPU兼容模式将手势图发送到本Space,在内存中处理、不保存。运行前的页面提示说明数据去向。JSON不含人脸描述子,记录参数、后端与版本。使用合成或获许可图片。人脸结果不是身份证明,有限静态手势不是手语翻译,OCR需要与原图核对。生成样例不能证明真实人群/领域准确率。
52
+
53
+ 来源:从wr92-course/test提交9d11aee0c2c539b5a5781e12215136c599b01fb0改造。原件与本轮修改前备份保存在教师目录,Git历史保留。
54
+
55
+ ## English
56
+
57
+ Build: `20261013-gradio-1`. This package uses the native Gradio SDK with app.py as its entry. Upload all extracted files to the Space root; the platform installs requirements.txt/packages.txt and starts the app. Keep the existing ZeroGPU setting. No Docker, PRO subscription, hardware downgrade or Chrome graphics change is required by this application.
58
+
59
+ The existing course UI and model behavior are retained: face-api.js0.22.2 for face verification; MediaPipe0.10.18 for static gestures; Tesseract.js5.1.1 for printed-English OCR. Face/OCR run in the browser. If graphics are unavailable, the same gesture task runs on the Space CPU, with no GPU request. The interface defaults to English with a separate Chinese switch.
60
+
61
+ Upload the contents of AI-Power_Image_Recognition_HF_Gradio.zip, keep `sdk: gradio` and `app_file: app.py`, wait for Running, then open the App tab. The footer identifies the build and CPU readiness. A leftover Dockerfile is ignored by the Gradio SDK. For local use, install the requirements in an isolated environment and run `python app.py`.
62
+
63
+ Choose a sample, run the model, inspect outputs, change one setting and export evidence. Lower face distance thresholds are stricter; higher gesture score thresholds are stricter. OCR layout modes6/11/7 correspond to a text block, sparse text and one line. Interface language does not change OCR language.
64
+
65
+ Face/OCR images stay local. CPU compatibility sends only the gesture image to this Space, processes request memory and does not save it. JSON excludes face descriptors and records backend/version. Use synthetic or permitted inputs. Face verification is not identity proof; gestures are not sign-language translation; OCR needs manual checking. Generated examples do not establish scientific accuracy.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.js CHANGED
@@ -1,7 +1,7 @@
1
  /** 默认英文界面与中文切换;所有预测来自真实模型调用,文字输出用textContent避免HTML注入。 */
2
- import * as recognition from './recognizers.js?v=20261013-recovery-1';
3
  const {recognizeFace,recognizeGesture,recognizeOCR,handConnections,versions}=recognition;
4
- const APP_RELEASE='20261013-recovery-1';
5
  const $=id=>document.getElementById(id);
6
  let deploymentMessage=['Checking the Space CPU service…','正在检查Space CPU服务…'];
7
  async function checkDeployment(){
@@ -12,7 +12,7 @@ async function checkDeployment(){
12
  const health=response.ok?await response.json():null;
13
  deploymentMessage=health?.ready&&health?.gesture_cpu&&health?.version===APP_RELEASE?
14
  ['Space CPU service ready','Space CPU服务已就绪']:
15
- ['CPU compatibility is not deployed. Upload all files from the recovery package, including README.md and Dockerfile.','CPU兼容服务尚未部署。请上传恢复包的全部文件,包括README.md和Dockerfile。'];
16
  }catch{
17
  deploymentMessage=['Space CPU service unavailable. Check the Space build and retry.','Space CPU服务不可用,请检查Space构建状态后重试。'];
18
  }finally{
 
1
  /** 默认英文界面与中文切换;所有预测来自真实模型调用,文字输出用textContent避免HTML注入。 */
2
+ import * as recognition from './recognizers.js?v=20261013-gradio-1';
3
  const {recognizeFace,recognizeGesture,recognizeOCR,handConnections,versions}=recognition;
4
+ const APP_RELEASE='20261013-gradio-1';
5
  const $=id=>document.getElementById(id);
6
  let deploymentMessage=['Checking the Space CPU service…','正在检查Space CPU服务…'];
7
  async function checkDeployment(){
 
12
  const health=response.ok?await response.json():null;
13
  deploymentMessage=health?.ready&&health?.gesture_cpu&&health?.version===APP_RELEASE?
14
  ['Space CPU service ready','Space CPU服务已就绪']:
15
+ ['CPU compatibility is not deployed. Upload all files from the recovery package, including README.md and app.py.','CPU兼容服务尚未部署。请上传恢复包的全部文件,包括README.md和app.py。'];
16
  }catch{
17
  deploymentMessage=['Space CPU service unavailable. Check the Space build and retry.','Space CPU服务不可用,请检查Space构建状态后重试。'];
18
  }finally{
app.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """原生Gradio SDK入口:启动现有教学页面和CPU手势服务,无Docker或GPU调用。"""
2
+ import os
3
+
4
+ # 必须在导入Gradio/MediaPipe之前关闭遥测并指定可写缓存,适配HF运行账号。
5
+ os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
6
+ os.environ.setdefault('MPLCONFIGDIR', '/tmp/matplotlib' if os.name != 'nt' else os.path.join(os.environ.get('TEMP', '.'), 'vision-lab-matplotlib'))
7
+
8
+ import gradio as gr
9
+ import uvicorn
10
+ from fastapi import FastAPI
11
+ from server import app as lab_app, health
12
+
13
+
14
+ # 采用官方Gradio挂载接口;父服务负责一次性加载CPU模型,页面与模型保持同源。
15
+ app = FastAPI(lifespan=lab_app.router.lifespan_context,
16
+ docs_url=None, redoc_url=None, openapi_url=None)
17
+ app.mount('/lab', lab_app)
18
+ app.add_api_route('/api/health', health, methods=['GET'])
19
+
20
+ with gr.Blocks(title='AI-Power Image Recognition',
21
+ css='.gradio-container{max-width:100%!important;padding:0!important} footer{display:none!important}',
22
+ analytics_enabled=False) as demo:
23
+ # 同源页面完整复用已验证的课程界面;保留EN/中文、上传、叠加图和JSON导出。
24
+ gr.HTML('<iframe id="vision-lab" title="AI-Power Image Recognition" '
25
+ 'src="/lab/" style="display:block;width:100%;height:calc(100vh - 24px);'
26
+ 'min-height:640px;border:0" allow="clipboard-write"></iframe>')
27
+
28
+ app = gr.mount_gradio_app(app, demo, path='/', show_api=False, ssr_mode=False)
29
+
30
+ if __name__ == '__main__':
31
+ # Hugging Face Gradio SDK直接执行app.py;本地测试可通过PORT选择空闲端口。
32
+ uvicorn.run(app, host='0.0.0.0', port=int(os.environ.get('PORT', '7860')),
33
+ access_log=False)
docs/dev/DESIGN.md CHANGED
@@ -1,5 +1,7 @@
1
  # 开发分工与恢复 / Development design
2
 
 
 
3
  恢复版新增发布一致性:HTML的vision-lab-build元信息、app.js的APP_RELEASE、recognizers.js的release和/api/health的version同为20261013-recovery-1。网页文件版本混用在任务初始化前阻止推理;CPU健康状态明确显示后端是否启动,不用页面文案推断已部署。JSON记录appBuild/modelBuild,CPU结果另含serverBuild。日期恢复ZIP是本轮唯一推荐入口,旧Static包退出根目录。
4
 
5
  当前兼容实现:README使用sdk: docker、app_port:7860,Dockerfile自动部署相同学生页面和CPU接口。recognizers.js优先运行浏览器任务;WebGL2不可用或activeTexture/上下文错误时回退POST /api/gesture,120秒超时后释放按钮。CPU调用没有WebGL要求,使用Python MediaPipe 0.10.18的CPU委托与同一份task权重;模型锁串行保护,繁忙返回503且可重试。后端限制上传大小与像素数,静态目录/页面用白名单,不暴露源码或Git。
 
1
  # 开发分工与恢复 / Development design
2
 
3
+ 当前Gradio实现:app.py以官方mount_gradio_app将课程页面和CPU兼容接口同源启动;主页由Gradio承载,/lab/保留现有交互。父服务lifespan负责一次加载CPU模型,避免子应用生命周期没有执行。显式关闭SSR,不要求Node启动;无Dockerfile或GPU执行调用。app.py/requirements.txt/packages.txt随包提供,README使用sdk:gradio/app_file:app.py。页面、模型与健康接口版本同为20261013-gradio-1。之前Docker实现已退出当前test和交付包。
4
+
5
  恢复版新增发布一致性:HTML的vision-lab-build元信息、app.js的APP_RELEASE、recognizers.js的release和/api/health的version同为20261013-recovery-1。网页文件版本混用在任务初始化前阻止推理;CPU健康状态明确显示后端是否启动,不用页面文案推断已部署。JSON记录appBuild/modelBuild,CPU结果另含serverBuild。日期恢复ZIP是本轮唯一推荐入口,旧Static包退出根目录。
6
 
7
  当前兼容实现:README使用sdk: docker、app_port:7860,Dockerfile自动部署相同学生页面和CPU接口。recognizers.js优先运行浏览器任务;WebGL2不可用或activeTexture/上下文错误时回退POST /api/gesture,120秒超时后释放按钮。CPU调用没有WebGL要求,使用Python MediaPipe 0.10.18的CPU委托与同一份task权重;模型锁串行保护,繁忙返回503且可重试。后端限制上传大小与像素数,静态目录/页面用白名单,不暴露源码或Git。
docs/dev/LATEST.md CHANGED
@@ -1,5 +1,11 @@
1
  # 当前开发状态 / Current development
2
 
 
 
 
 
 
 
3
  2026-10-13用户明确同意清理test:已备份并移出旧detector.js、wr92-language.js/.css、101个COCO样例/索引与4张旧指南截图,共108文件、16,488,545字节。当前应用没有引用这些文件;识别代码、模型、运行库、许可证、Git记录与治理文件保留。备份在外层backup/20261013-191024,明细与验证在validation/test_cleanup.json。清理仅影响本地目录,没有修改远程Space。
4
 
5
  The user authorized cleanup:108 unreferenced legacy files were backed up and moved out of test. Active recognition code/models/runtimes/licenses and Git/project guidance remain. Receipts are in the teacher validation/test_cleanup.json; no remote mutation or new inference result is implied.
 
1
  # 当前开发状态 / Current development
2
 
3
+ 当前版本20261013-gradio-1:根据用户“不用Docker、上传即可运行”的明确要求,改为原生Gradio5.49.1 SDK/Python3.10入口app.py,packages.txt安装系统依赖,requirements.txt固定兼容版本。现有课程界面和模型不变,通过官方mount_gradio_app接口启动同源页面/CPU服务,不调用GPU。可以保留现有ZeroGPU硬件,不要求PRO或降级。
4
+
5
+ 本轮本地实际Gradio首页13次模型运行与4组检查通过,含完全禁用HTML/Offscreen WebGL的人脸/四手势/OCR、上传、阈值、空结果、错误恢复、JSON、中文切换、390px布局及图形可用路径,页面脚本错误0。证据位于外层validation/gradio_validation.json与gradio_linux_dependencies.json。课件启动页/资料页及双语文档同步;没有推送远程。
6
+
7
+ Native Gradio5.49.1/Python3.10 is now the deployment target. app.py mounts the same UI and CPU compatibility service; models/settings are unchanged. Dependencies install automatically. The app requests no GPU execution and needs no Docker/PRO/hardware change. Local checks passed13 actual model runs/4 check groups with no page errors; a later HF deployment requires verification after upload. The older Docker records below are history.
8
+
9
  2026-10-13用户明确同意清理test:已备份并移出旧detector.js、wr92-language.js/.css、101个COCO样例/索引与4张旧指南截图,共108文件、16,488,545字节。当前应用没有引用这些文件;识别代码、模型、运行库、许可证、Git记录与治理文件保留。备份在外层backup/20261013-191024,明细与验证在validation/test_cleanup.json。清理仅影响本地目录,没有修改远程Space。
10
 
11
  The user authorized cleanup:108 unreferenced legacy files were backed up and moved out of test. Active recognition code/models/runtimes/licenses and Git/project guidance remain. Receipts are in the teacher validation/test_cleanup.json; no remote mutation or new inference result is implied.
docs/wish/DESIGN.md CHANGED
@@ -1,5 +1,7 @@
1
  # 设计说明 / Design
2
 
 
 
3
  兼容版不改变学生操作顺序:选择图片、点击Run recognition、读取真实结果。手势图形不可用时自动切到Space CPU;运行按钮上方说明数据去向,结果与JSON标明后端。模型类别和阈值含义保持不变,但比较实验需固定后端与处理尺寸。上传补丁即可获得后端,无需自行设计。
4
 
5
  The compatibility version preserves the learner flow. CPU fallback is automatic for gesture graphics failures, with input-time disclosure and backend labels in the result/JSON. Keep the backend and processed dimensions fixed in comparisons. Upload the supplied Docker files to activate the backend.
 
1
  # 设计说明 / Design
2
 
3
+ 当前启动设计:Gradio入口承载同源课程页面,学生仍按输入—运行—观察—控制变量—导出的顺序操作。改启动方式不替换三任务模型和阈值语义。无WebGL时使用同模型Space CPU手势路径;数据去向继续明确提示。上传一个完整Gradio包即由平台安装依赖并启动,不给教师增加Docker/硬件/订阅设置。
4
+
5
  兼容版不改变学生操作顺序:选择图片、点击Run recognition、读取真实结果。手势图形不可用时自动切到Space CPU;运行按钮上方说明数据去向,结果与JSON标明后端。模型类别和阈值含义保持不变,但比较实验需固定后端与处理尺寸。上传补丁即可获得后端,无需自行设计。
6
 
7
  The compatibility version preserves the learner flow. CPU fallback is automatic for gesture graphics failures, with input-time disclosure and backend labels in the result/JSON. Keep the backend and processed dimensions fixed in comparisons. Upload the supplied Docker files to activate the backend.
docs/wish/LATEST.md CHANGED
@@ -1,5 +1,9 @@
1
  # 当前课程项目意图 / Current Wish
2
 
 
 
 
 
3
  最新兼容方向:用户反馈浏览器缺少WebGL2,并要求方便、无需自行设计的方案。课程任务和模型保持一致,交付Docker CPU兼容版:人脸/OCR仍在浏览器;手势图形故障时自动在本Space的CPU上用同一模型识别。界面在运行前说明手势图片可能发送到Space,后端内存处理、不保存;无需学生修改Chrome设置或购买GPU。附完整部署文件与9文件补丁,上传后自动构建。
4
 
5
  Current compatibility intent: provide a ready-to-upload Docker CPU Space with the same course models and tasks. Face/OCR stay in the browser; gestures automatically use the Space CPU when browser graphics fail. Disclose image transfer before running and do not persist inputs/results. The user should not need to design a backend or change browser settings. All deployment files are supplied locally; updating the public Space requires upload and build.
 
1
  # 当前课程项目意图 / Current Wish
2
 
3
+ 最新用户约束:不再使用Docker,不要求PRO订阅或改硬件,给出可直接上传的简单版本。采用原生Gradio SDK以app.py启动现有课程页面和CPU手势服务;模型、参数、样例、双语与导出保留。完整包带requirements.txt和packages.txt,由平台自动安装。可以保留现有ZeroGPU配置,应用没有GPU执行函数。唯一当前部署包为AI-Power_Image_Recognition_HF_Gradio.zip。
4
+
5
+ Current direction: a simple native Gradio SDK upload, without Docker, a PRO requirement or hardware downgrade. app.py starts the same course UI and CPU gesture service; tasks/models/settings remain aligned with the slides. Dependencies are supplied for automatic installation. Keep existing ZeroGPU configuration; the app requests no GPU execution. Only the complete Gradio package is current.
6
+
7
  最新兼容方向:用户反馈浏览器缺少WebGL2,并要求方便、无需自行设计的方案。课程任务和模型保持一致,交付Docker CPU兼容版:人脸/OCR仍在浏览器;手势图形故障时自动在本Space的CPU上用同一模型识别。界面在运行前说明手势图片可能发送到Space,后端内存处理、不保存;无需学生修改Chrome设置或购买GPU。附完整部署文件与9文件补丁,上传后自动构建。
8
 
9
  Current compatibility intent: provide a ready-to-upload Docker CPU Space with the same course models and tasks. Face/OCR stay in the browser; gestures automatically use the Space CPU when browser graphics fail. Disclose image transfer before running and do not persist inputs/results. The user should not need to design a backend or change browser settings. All deployment files are supplied locally; updating the public Space requires upload and build.
how-to-start.html CHANGED
@@ -1,8 +1,8 @@
1
  <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>How to Start · AI-Power Image Recognition</title><link rel="stylesheet" href="./style.css"></head><body><main class="shell guide"><nav class="topbar"><a href="./index.html">← Vision Lab</a><a href="./how-to-start.pdf">PDF guide</a></nav><p class="eyebrow">CREATIVE TECHNOLOGY · STUDENT GUIDE</p><h1>Build. Test. Explain.</h1><p>Use a pretrained recognition model as a starting point for your own small AI application.</p>
2
  <section><h2>1. Try the supplied app</h2><p>Open the Face verification, Gesture recognition or Text OCR tab. Choose a sample and select <strong>Run recognition</strong>. Wait for model loading. Inspect the input, overlay and result together.</p><p>Face verification compares two images and reports a distance. Gesture recognition classifies a static hand pose. OCR transcribes printed English. These tasks have different outputs and different limits.</p></section>
3
- <section><h2>2. Make your own working copy</h2><p>Sign in to Hugging Face. Duplicate the instructor’s deployed recognition Space, or create a <strong>Docker</strong> Space using <strong>CPU Basic</strong>. Upload the supplied CPU deployment package while preserving its directory structure. The README specifies <strong>sdk: docker</strong> and <strong>app_port: 7860</strong>; the supplied Dockerfile builds the app automatically.</p><p>Keep <strong>Dockerfile, server.py, requirements.txt, README.md, index.html, style.css, app.js, recognizers.js, models/, vendor/, samples/</strong> and the guide files. Wait for the build and startup to finish, then open the App page and test a sample. No backend design or GPU setup is required.</p><p>A local static HTTP server supports browser inference on devices with working graphics. To test CPU compatibility locally, install the supplied requirements in an isolated environment and run the server. Do not open the HTML directly as a file.</p></section>
4
  <section><h2>3. Understand one model call</h2><p><strong>app.js</strong> reads the input, sets the task and draws the result. <strong>recognizers.js</strong> chooses the appropriate model path. The <strong>models/</strong> directory contains weights; downloading them is not training.</p><p>Face and OCR run in your browser. Gestures also run in the browser when its graphics work. Otherwise <strong>server.py</strong> runs the same MediaPipe 0.10.18 model on the Space CPU and returns the same kind of labels, scores and 21 landmarks. JSON identifies the backend. Keep the backend fixed when comparing scores or timings.</p></section>
5
  <section><h2>4. Run one controlled experiment</h2><p><strong>Face:</strong> keep the pair fixed and try distance thresholds 0.40, 0.60 and 0.80. Lower is stricter.</p><p><strong>Gesture:</strong> keep the hand image fixed and try score thresholds 0.30, 0.60 and 0.90. Higher is stricter.</p><p><strong>OCR:</strong> keep a text image fixed and compare text-block and sparse-text layouts. Check the transcript against the original, not only the confidence.</p><p>Select <strong>Export result JSON</strong>. Save a permitted input or a clear input identifier separately. Record an unchanged result honestly; a setting need not change every prediction.</p></section>
6
  <section><h2>5. Make one useful improvement</h2><p>Choose a problem you observed. Improve the input guidance, output presentation, review workflow or a task-specific setting. State the hypothesis and compare before and after under consistent conditions.</p><p>Replacing or training a model is optional. Training needs permitted labeled data, compute and a separate held-out test. Do not treat generated examples as a real-world accuracy benchmark.</p></section>
7
  <section><h2>6. Submit something easy to review</h2><p>Provide a working Space link, the task and intended user, input and output examples, model and version, your changes, a controlled comparison, one failure and a short explanation.</p><p>Test the public URL in a fresh browser before submitting. Do not submit the temporary example.com link from the course slides as your working app.</p></section>
8
- <section><h2>Use the demo responsibly</h2><p>Use synthetic examples or images you have permission to process. Face and OCR images stay in the browser. In CPU compatibility mode the gesture image is sent to this Space, processed in memory and not saved by the application. Large gesture images are proportionally reduced to at most 1920 pixels on the longest side before transfer. Results and face descriptors are not persisted by the app.</p><p>Face comparison is not identity proof; static gesture recognition is not sign-language translation; English OCR does not support every language or document type. A no-hand result and an unsupported gesture are different outcomes. If CPU compatibility is not deployed yet, upload the complete fix package and wait for the Docker build; uploading only JavaScript cannot add a server to a Static Space.</p></section><footer>AI-Power Image Recognition · Course guide · CPU compatibility · 2026-10-13</footer></main></body></html>
 
1
  <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>How to Start · AI-Power Image Recognition</title><link rel="stylesheet" href="./style.css"></head><body><main class="shell guide"><nav class="topbar"><a href="./index.html">← Vision Lab</a><a href="./how-to-start.pdf">PDF guide</a></nav><p class="eyebrow">CREATIVE TECHNOLOGY · STUDENT GUIDE</p><h1>Build. Test. Explain.</h1><p>Use a pretrained recognition model as a starting point for your own small AI application.</p>
2
  <section><h2>1. Try the supplied app</h2><p>Open the Face verification, Gesture recognition or Text OCR tab. Choose a sample and select <strong>Run recognition</strong>. Wait for model loading. Inspect the input, overlay and result together.</p><p>Face verification compares two images and reports a distance. Gesture recognition classifies a static hand pose. OCR transcribes printed English. These tasks have different outputs and different limits.</p></section>
3
+ <section><h2>2. Make your own working copy</h2><p>Sign in to Hugging Face. Duplicate the instructor’s recognition Space, or create a <strong>Gradio</strong> Space. Upload the complete supplied Gradio package, preserving its directory structure. The README sets <strong>sdk: gradio</strong> and <strong>app_file: app.py</strong>; Hugging Face installs the listed dependencies and starts the app automatically.</p><p>Keep <strong>app.py, packages.txt, server.py, requirements.txt, README.md, index.html, style.css, app.js, recognizers.js, models/, vendor/, samples/</strong> and the guide files. Existing ZeroGPU settings can remain: this lab does not request GPU execution. No Docker setup, PRO subscription or hardware downgrade is required by the application.</p><p>Wait for Running, open the App tab and check build <strong>20261013-gradio-1</strong> with <strong>Space CPU service ready</strong>. For local use, install the requirements in an isolated environment and run <strong>python app.py</strong>, then open localhost port7860.</p></section>
4
  <section><h2>3. Understand one model call</h2><p><strong>app.js</strong> reads the input, sets the task and draws the result. <strong>recognizers.js</strong> chooses the appropriate model path. The <strong>models/</strong> directory contains weights; downloading them is not training.</p><p>Face and OCR run in your browser. Gestures also run in the browser when its graphics work. Otherwise <strong>server.py</strong> runs the same MediaPipe 0.10.18 model on the Space CPU and returns the same kind of labels, scores and 21 landmarks. JSON identifies the backend. Keep the backend fixed when comparing scores or timings.</p></section>
5
  <section><h2>4. Run one controlled experiment</h2><p><strong>Face:</strong> keep the pair fixed and try distance thresholds 0.40, 0.60 and 0.80. Lower is stricter.</p><p><strong>Gesture:</strong> keep the hand image fixed and try score thresholds 0.30, 0.60 and 0.90. Higher is stricter.</p><p><strong>OCR:</strong> keep a text image fixed and compare text-block and sparse-text layouts. Check the transcript against the original, not only the confidence.</p><p>Select <strong>Export result JSON</strong>. Save a permitted input or a clear input identifier separately. Record an unchanged result honestly; a setting need not change every prediction.</p></section>
6
  <section><h2>5. Make one useful improvement</h2><p>Choose a problem you observed. Improve the input guidance, output presentation, review workflow or a task-specific setting. State the hypothesis and compare before and after under consistent conditions.</p><p>Replacing or training a model is optional. Training needs permitted labeled data, compute and a separate held-out test. Do not treat generated examples as a real-world accuracy benchmark.</p></section>
7
  <section><h2>6. Submit something easy to review</h2><p>Provide a working Space link, the task and intended user, input and output examples, model and version, your changes, a controlled comparison, one failure and a short explanation.</p><p>Test the public URL in a fresh browser before submitting. Do not submit the temporary example.com link from the course slides as your working app.</p></section>
8
+ <section><h2>Use the demo responsibly</h2><p>Use synthetic examples or images you have permission to process. Face and OCR images stay in the browser. In CPU compatibility mode the gesture image is sent to this Space, processed in memory and not saved by the application. Large gesture images are proportionally reduced to at most 1920 pixels on the longest side before transfer. Results and face descriptors are not persisted by the app.</p><p>Face comparison is not identity proof; static gesture recognition is not sign-language translation; English OCR does not support every language or document type. A no-hand result and an unsupported gesture are different outcomes. Upload the complete Gradio package if CPU readiness is missing, and wait for the Space startup.</p></section><footer>AI-Power Image Recognition · Gradio course guide · 2026-10-13</footer></main></body></html>
how-to-start.pdf CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:03e72affcda55434e6a6f2cb805e816f4c3cfe15d0dd214f9eb451d7fceec185
3
- size 71274
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a9b77c935bcae7e95d5106a2b36e18516d70b7fa1d3c961a0114107388750c5
3
+ size 71286
index.html CHANGED
@@ -1,8 +1,8 @@
1
  <!doctype html>
2
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3
- <meta name="vision-lab-build" content="20261013-recovery-1">
4
  <title>AI-Power Image Recognition · Vision Lab</title><meta name="description" content="Browser teaching lab: face verification, gesture recognition and printed English OCR.">
5
- <link rel="stylesheet" href="./style.css"><script defer src="./vendor/face-api.min.js"></script><script defer src="./vendor/tesseract.min.js"></script><script type="module" src="./app.js?v=20261013-recovery-1"></script></head>
6
  <body><main class="shell"><nav class="topbar"><a class="brand" href="./index.html">VISION LAB <span>Creative Technology</span></a><div><a href="./how-to-start.html" data-i18n="guide">How to Start</a><button id="language" aria-label="Switch language">中文</button></div></nav>
7
  <header class="hero"><div><p class="eyebrow" data-i18n="eyebrow">PRETRAINED MODELS · REAL INFERENCE</p><h1>AI-Power<br>Image Recognition</h1><p class="lede" data-i18n="lede">Compare faces. Read a gesture. Turn printed text into editable words.</p></div><aside><strong data-i18n="path">One image. A useful result.</strong><p data-i18n="promise">Choose a task, inspect its output, change one setting and explain the difference.</p><div class="badges"><span data-i18n="browser">Browser + CPU compatibility</span><span data-i18n="training">No training required</span></div></aside></header>
8
  <div class="tabs" role="tablist" aria-label="Recognition task"><button role="tab" id="tab-face" aria-selected="true" data-task="face" data-i18n="face">01 Face verification</button><button role="tab" id="tab-gesture" aria-selected="false" data-task="gesture" data-i18n="gesture">02 Gesture recognition</button><button role="tab" id="tab-ocr" aria-selected="false" data-task="ocr" data-i18n="ocr">03 Text OCR</button></div>
@@ -15,4 +15,4 @@
15
  <button id="run" class="primary" data-i18n="run">Run recognition</button><p id="status" role="status" aria-live="polite"></p><p id="model-name" class="model"></p></div>
16
  <div class="output"><div class="output-head"><p class="step" data-i18n="step2">STEP 2 · INSPECT THE RESULT</p><button id="export" disabled data-i18n="export">Export result JSON</button></div><div id="canvases" class="canvases"><figure id="reference-figure"><figcaption data-i18n="reference">Reference</figcaption><canvas id="reference-canvas"></canvas></figure><figure><figcaption id="probe-caption">Probe</figcaption><canvas id="probe-canvas"></canvas></figure></div><div id="result" class="result" aria-live="polite"></div><details id="details" hidden><summary data-i18n="details">Result details</summary><pre id="json"></pre></details></div></section>
17
  <section class="experiment"><div><p class="step" data-i18n="step3">STEP 3 · ASK A BETTER QUESTION</p><h2 id="question"></h2><p id="experiment"></p></div><div class="answer"><strong data-i18n="record">Record your evidence</strong><p data-i18n="recordhelp">Keep the input fixed. Save the setting, the output, one success and one limitation. Change only one factor.</p></div></section>
18
- <footer><p id="release-version" class="model">Build: 20261013-recovery-1</p><p id="deployment-status" class="model" role="status">Checking the Space CPU service?</p><p data-i18n="privacy">Face and OCR images stay in this browser. If browser graphics fail, the gesture image is sent to this Space CPU for recognition and is not saved. Use synthetic or permitted images. Results and face descriptors are not stored by the app.</p><p data-i18n="limits">Teaching demo: no identity proof, no sign-language translation, no guaranteed transcription accuracy. Model files may take time to load.</p><a href="./how-to-start.html" data-i18n="submission">Build, test and submit your own Space →</a></footer></main></body></html>
 
1
  <!doctype html>
2
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3
+ <meta name="vision-lab-build" content="20261013-gradio-1">
4
  <title>AI-Power Image Recognition · Vision Lab</title><meta name="description" content="Browser teaching lab: face verification, gesture recognition and printed English OCR.">
5
+ <link rel="stylesheet" href="./style.css"><script defer src="./vendor/face-api.min.js"></script><script defer src="./vendor/tesseract.min.js"></script><script type="module" src="./app.js?v=20261013-gradio-1"></script></head>
6
  <body><main class="shell"><nav class="topbar"><a class="brand" href="./index.html">VISION LAB <span>Creative Technology</span></a><div><a href="./how-to-start.html" data-i18n="guide">How to Start</a><button id="language" aria-label="Switch language">中文</button></div></nav>
7
  <header class="hero"><div><p class="eyebrow" data-i18n="eyebrow">PRETRAINED MODELS · REAL INFERENCE</p><h1>AI-Power<br>Image Recognition</h1><p class="lede" data-i18n="lede">Compare faces. Read a gesture. Turn printed text into editable words.</p></div><aside><strong data-i18n="path">One image. A useful result.</strong><p data-i18n="promise">Choose a task, inspect its output, change one setting and explain the difference.</p><div class="badges"><span data-i18n="browser">Browser + CPU compatibility</span><span data-i18n="training">No training required</span></div></aside></header>
8
  <div class="tabs" role="tablist" aria-label="Recognition task"><button role="tab" id="tab-face" aria-selected="true" data-task="face" data-i18n="face">01 Face verification</button><button role="tab" id="tab-gesture" aria-selected="false" data-task="gesture" data-i18n="gesture">02 Gesture recognition</button><button role="tab" id="tab-ocr" aria-selected="false" data-task="ocr" data-i18n="ocr">03 Text OCR</button></div>
 
15
  <button id="run" class="primary" data-i18n="run">Run recognition</button><p id="status" role="status" aria-live="polite"></p><p id="model-name" class="model"></p></div>
16
  <div class="output"><div class="output-head"><p class="step" data-i18n="step2">STEP 2 · INSPECT THE RESULT</p><button id="export" disabled data-i18n="export">Export result JSON</button></div><div id="canvases" class="canvases"><figure id="reference-figure"><figcaption data-i18n="reference">Reference</figcaption><canvas id="reference-canvas"></canvas></figure><figure><figcaption id="probe-caption">Probe</figcaption><canvas id="probe-canvas"></canvas></figure></div><div id="result" class="result" aria-live="polite"></div><details id="details" hidden><summary data-i18n="details">Result details</summary><pre id="json"></pre></details></div></section>
17
  <section class="experiment"><div><p class="step" data-i18n="step3">STEP 3 · ASK A BETTER QUESTION</p><h2 id="question"></h2><p id="experiment"></p></div><div class="answer"><strong data-i18n="record">Record your evidence</strong><p data-i18n="recordhelp">Keep the input fixed. Save the setting, the output, one success and one limitation. Change only one factor.</p></div></section>
18
+ <footer><p id="release-version" class="model">Build: 20261013-gradio-1</p><p id="deployment-status" class="model" role="status">Checking the Space CPU service?</p><p data-i18n="privacy">Face and OCR images stay in this browser. If browser graphics fail, the gesture image is sent to this Space CPU for recognition and is not saved. Use synthetic or permitted images. Results and face descriptors are not stored by the app.</p><p data-i18n="limits">Teaching demo: no identity proof, no sign-language translation, no guaranteed transcription accuracy. Model files may take time to load.</p><a href="./how-to-start.html" data-i18n="submission">Build, test and submit your own Space →</a></footer></main></body></html>
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ libgl1
2
+ libglib2.0-0
recognizers.js CHANGED
@@ -1,101 +1,101 @@
1
- /** 三个独立识别任务的模型层,仅处理当前页面内存中的图像。 */
2
- const caches=new Map();
3
- export const versions={face:'face-api.js 0.22.2',gesture:'MediaPipe Tasks Vision 0.10.18',ocr:'Tesseract.js 5.1.1 / English LSTM'};
4
- // 页面和模型层必须属于同一发布版,防止上传旧整包覆盖已修好的代码。
5
- export const release='20261013-recovery-1';
6
- async function cached(key,factory){
7
- // 加载失败清理缓存,允许修复文件或网络后再次尝试。
8
- if(!caches.has(key))caches.set(key,factory().catch(e=>{caches.delete(key);throw e;}));
9
- return caches.get(key);
10
- }
11
- function requireReadableImage(image){
12
- // 在进入模型之前检测同源/CORS状态,避免face-api的旧版任务链吞掉异步异常后一直等待。
13
- if(!(image.naturalWidth||image.width)||!(image.naturalHeight||image.height))throw new Error('The image is not ready. Choose a valid image and retry.');
14
- const canvas=document.createElement('canvas');canvas.width=canvas.height=1;
15
- try{const ctx=canvas.getContext('2d');if(!ctx)throw new Error('A 2D canvas is unavailable.');ctx.drawImage(image,0,0,1,1);ctx.getImageData(0,0,1,1);}
16
- catch(e){
17
- if(e.name==='SecurityError'||/taint|cross-origin/i.test(e.message))throw new Error('This image cannot be read because it was loaded without CORS permission. Update app.js and reload the page; an external image host must allow CORS.');
18
- throw e;
19
- }finally{canvas.width=canvas.height=0;}
20
- }
21
- async function describeFace(image,settings,label,progress){
22
- // 0.22.2的ComposableTask.then不转发拒绝,且链式检测用了不带reject的异步Promise。
23
- // 使用同一组导出的任务类,并将父阶段结果作为普通Promise传入:保留算法,可靠传递每阶段错误。
24
- progress(`Detecting the ${label} face…`);
25
- const detections=await faceapi.detectAllFaces(image,settings).run();
26
- if(detections.length!==1)throw new Error(`Use exactly one clear face per image. Found ${detections.length} in the ${label} image.`);
27
- const detected=detections.map(detection=>faceapi.extendWithFaceDetection({},detection));
28
- progress(`Locating landmarks in the ${label} face…`);
29
- const landmarks=await new faceapi.DetectAllFaceLandmarksTask(Promise.resolve(detected),image,false).run();
30
- progress(`Encoding the ${label} face descriptor…`);
31
- const described=await new faceapi.ComputeAllFaceDescriptorsTask(Promise.resolve(landmarks),image).run();
32
- return described[0];
33
- }
34
- export async function recognizeFace(reference,probe,threshold,progress){
35
- requireReadableImage(reference);requireReadableImage(probe);
36
- progress('Loading face detector, landmarks and descriptor model…');
37
- await cached('face',async()=>{await Promise.all([faceapi.nets.tinyFaceDetector.loadFromUri('./models/face'),faceapi.nets.faceLandmark68Net.loadFromUri('./models/face'),faceapi.nets.faceRecognitionNet.loadFromUri('./models/face')]);return true;});
38
- const settings=new faceapi.TinyFaceDetectorOptions({inputSize:416,scoreThreshold:0.35});
39
- const a=await describeFace(reference,settings,'reference',progress);
40
- const b=await describeFace(probe,settings,'probe',progress);
41
- progress('Comparing the two face descriptors…');
42
- const distance=faceapi.euclideanDistance(a.descriptor,b.descriptor);
43
- const pack=x=>({box:{x:x.detection.box.x,y:x.detection.box.y,width:x.detection.box.width,height:x.detection.box.height},points:x.landmarks.positions.map(p=>({x:p.x,y:p.y}))});
44
- return {task:'face',model:versions.face,distance,threshold,decision:distance<threshold?'Match at this threshold':'No match at this threshold',reference:pack(a),probe:pack(b),note:'Distance is not a probability. A match is not proof of identity. Descriptors are not exported.'};
45
- }
46
- async function recognizeGestureOnCPU(image,threshold,progress){
47
- // 网页Tasks无法绕过WebGL上传路径;后端使用相同版本和同一份task权重,不伪装成浏览器CPU。
48
- progress('Browser graphics unavailable. Recognizing on the Space CPU…');
49
- const canvas=document.createElement('canvas');
50
- // 限制兼容路径的传输尺寸并维持比例,归一化关键点仍可叠加在原图上。
51
- const scale=Math.min(1,1920/Math.max(image.naturalWidth,image.naturalHeight));
52
- canvas.width=Math.max(1,Math.round(image.naturalWidth*scale));canvas.height=Math.max(1,Math.round(image.naturalHeight*scale));
53
- const ctx=canvas.getContext('2d');if(!ctx)throw new Error('A 2D canvas is unavailable.');
54
- ctx.drawImage(image,0,0,canvas.width,canvas.height);
55
- const blob=await new Promise(resolve=>canvas.toBlob(resolve,'image/png'));canvas.width=canvas.height=0;
56
- if(!blob)throw new Error('Could not prepare the gesture image. Choose a valid image and retry.');
57
- const controller=new AbortController();const timer=setTimeout(()=>controller.abort(),120000);
58
- try{
59
- const response=await fetch(`./api/gesture?threshold=${encodeURIComponent(threshold)}`,{method:'POST',headers:{'Content-Type':'image/png'},body:blob,signal:controller.signal});
60
- if(response.status===404||response.status===405)throw new Error('CPU compatibility is not deployed yet. Upload the complete CPU fix package, including README.md and Dockerfile, to this Space and wait for its Docker build to finish.');
61
- let data;try{data=await response.json();}catch{throw new Error('The Space CPU did not return a recognition result. Wait for the Space to finish starting and retry.');}
62
- if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'The Space CPU could not complete this run. Retry shortly.');
63
- if(data.task!=='gesture'||!Array.isArray(data.hands))throw new Error('The Space CPU returned an invalid gesture result.');
64
- data.inputSize={width:image.naturalWidth,height:image.naturalHeight};return data;
65
- }catch(e){if(e.name==='AbortError')throw new Error('The Space CPU took too long to respond. Wait a moment and retry.');throw e;}
66
- finally{clearTimeout(timer);}
67
- }
68
- export async function recognizeGesture(image,threshold,progress){
69
- requireReadableImage(image);
70
- let model;
71
- try{
72
- model=await cached('gesture',async()=>{
73
- // 独立HTML画布保留可用设备的浏览器推理;无WebGL时由真正的Space CPU接口接手。
74
- const canvas=document.createElement('canvas');canvas.width=canvas.height=2;
75
- const gl=canvas.getContext('webgl2');
76
- if(!gl||gl.isContextLost())throw new Error('WebGL2 is unavailable.');
77
- progress('Loading hand landmarks and gesture classifier…');
78
- const {FilesetResolver,GestureRecognizer}=await import('./vendor/vision_bundle.mjs');
79
- const files=await FilesetResolver.forVisionTasks('./vendor/wasm');
80
- return GestureRecognizer.createFromOptions(files,{canvas,baseOptions:{modelAssetPath:'./models/gesture_recognizer.task',delegate:'CPU'},runningMode:'IMAGE',numHands:2});
81
- });
82
- progress('Recognizing the static hand pose…');
83
- const raw=model.recognize(image);
84
- const hands=raw.landmarks.map((points,i)=>{const g=raw.gestures[i]?.[0];const accepted=Boolean(g&&g.categoryName!=='None'&&g.score>=threshold);return {label:accepted?g.categoryName:'Unrecognized',candidate:g?.categoryName||'None',score:g?.score||0,accepted,handedness:raw.handedness[i]?.[0]?.categoryName||'Unknown',points:points.map(p=>({x:p.x,y:p.y,z:p.z}))};});
85
- return {task:'gesture',model:versions.gesture,backend:'Browser CPU (WebGL image input)',threshold,hands,note:hands.length?'Static gesture categories; not sign-language translation.':'No hand detected. Try a clear, complete hand on a simple background.'};
86
- }catch(e){
87
- // 清除坏图形任务;上下文错误自动回退,其他输入/权重错误保持真实失败。
88
- caches.delete('gesture');try{model?.close();}catch{}
89
- if(/activeTexture|WebGL|OpenGL|context/i.test(e.message))return recognizeGestureOnCPU(image,threshold,progress);
90
- throw e;
91
- }
92
- }
93
- export async function recognizeOCR(image,psm,progress){
94
- requireReadableImage(image);
95
- const worker=await cached('ocr',()=>Tesseract.createWorker('eng',1,{workerPath:'./vendor/worker.min.js',corePath:'./vendor/tesseract-core',langPath:'./models',logger:m=>progress(`${m.status}${Number.isFinite(m.progress)?' '+Math.round(m.progress*100)+'%':''}`)}));
96
- await worker.setParameters({tessedit_pageseg_mode:String(psm)});
97
- progress('Reading printed English text…');
98
- const {data}=await worker.recognize(image);
99
- return {task:'ocr',model:versions.ocr,psm,text:data.text.trim(),confidence:data.confidence,words:(data.words||[]).map(w=>({text:w.text,confidence:w.confidence,box:w.bbox})),note:'Confidence is a review cue, not measured accuracy. Check every important character against the image.'};
100
- }
101
- export const handConnections=[[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]];
 
1
+ /** 三个独立识别任务的模型层,仅处理当前页面内存中的图像。 */
2
+ const caches=new Map();
3
+ export const versions={face:'face-api.js 0.22.2',gesture:'MediaPipe Tasks Vision 0.10.18',ocr:'Tesseract.js 5.1.1 / English LSTM'};
4
+ // 页面和模型层必须属于同一发布版,防止上传旧整包覆盖已修好的代码。
5
+ export const release='20261013-gradio-1';
6
+ async function cached(key,factory){
7
+ // 加载失败清理缓存,允许修复文件或网络后再次尝试。
8
+ if(!caches.has(key))caches.set(key,factory().catch(e=>{caches.delete(key);throw e;}));
9
+ return caches.get(key);
10
+ }
11
+ function requireReadableImage(image){
12
+ // 在进入模型之前检测同源/CORS状态,避免face-api的旧版任务链吞掉异步异常后一直等待。
13
+ if(!(image.naturalWidth||image.width)||!(image.naturalHeight||image.height))throw new Error('The image is not ready. Choose a valid image and retry.');
14
+ const canvas=document.createElement('canvas');canvas.width=canvas.height=1;
15
+ try{const ctx=canvas.getContext('2d');if(!ctx)throw new Error('A 2D canvas is unavailable.');ctx.drawImage(image,0,0,1,1);ctx.getImageData(0,0,1,1);}
16
+ catch(e){
17
+ if(e.name==='SecurityError'||/taint|cross-origin/i.test(e.message))throw new Error('This image cannot be read because it was loaded without CORS permission. Update app.js and reload the page; an external image host must allow CORS.');
18
+ throw e;
19
+ }finally{canvas.width=canvas.height=0;}
20
+ }
21
+ async function describeFace(image,settings,label,progress){
22
+ // 0.22.2的ComposableTask.then不转发拒绝,且链式检测用了不带reject的异步Promise。
23
+ // 使用同一组导出的任务类,并将父阶段结果作为普通Promise传入:保留算法,可靠传递每阶段错误。
24
+ progress(`Detecting the ${label} face…`);
25
+ const detections=await faceapi.detectAllFaces(image,settings).run();
26
+ if(detections.length!==1)throw new Error(`Use exactly one clear face per image. Found ${detections.length} in the ${label} image.`);
27
+ const detected=detections.map(detection=>faceapi.extendWithFaceDetection({},detection));
28
+ progress(`Locating landmarks in the ${label} face…`);
29
+ const landmarks=await new faceapi.DetectAllFaceLandmarksTask(Promise.resolve(detected),image,false).run();
30
+ progress(`Encoding the ${label} face descriptor…`);
31
+ const described=await new faceapi.ComputeAllFaceDescriptorsTask(Promise.resolve(landmarks),image).run();
32
+ return described[0];
33
+ }
34
+ export async function recognizeFace(reference,probe,threshold,progress){
35
+ requireReadableImage(reference);requireReadableImage(probe);
36
+ progress('Loading face detector, landmarks and descriptor model…');
37
+ await cached('face',async()=>{await Promise.all([faceapi.nets.tinyFaceDetector.loadFromUri('./models/face'),faceapi.nets.faceLandmark68Net.loadFromUri('./models/face'),faceapi.nets.faceRecognitionNet.loadFromUri('./models/face')]);return true;});
38
+ const settings=new faceapi.TinyFaceDetectorOptions({inputSize:416,scoreThreshold:0.35});
39
+ const a=await describeFace(reference,settings,'reference',progress);
40
+ const b=await describeFace(probe,settings,'probe',progress);
41
+ progress('Comparing the two face descriptors…');
42
+ const distance=faceapi.euclideanDistance(a.descriptor,b.descriptor);
43
+ const pack=x=>({box:{x:x.detection.box.x,y:x.detection.box.y,width:x.detection.box.width,height:x.detection.box.height},points:x.landmarks.positions.map(p=>({x:p.x,y:p.y}))});
44
+ return {task:'face',model:versions.face,distance,threshold,decision:distance<threshold?'Match at this threshold':'No match at this threshold',reference:pack(a),probe:pack(b),note:'Distance is not a probability. A match is not proof of identity. Descriptors are not exported.'};
45
+ }
46
+ async function recognizeGestureOnCPU(image,threshold,progress){
47
+ // 网页Tasks无法绕过WebGL上传路径;后端使用相同版本和同一份task权重,不伪装成浏览器CPU。
48
+ progress('Browser graphics unavailable. Recognizing on the Space CPU…');
49
+ const canvas=document.createElement('canvas');
50
+ // 限制兼容路径的传输尺寸并维持比例,归一化关键点仍可叠加在原图上。
51
+ const scale=Math.min(1,1920/Math.max(image.naturalWidth,image.naturalHeight));
52
+ canvas.width=Math.max(1,Math.round(image.naturalWidth*scale));canvas.height=Math.max(1,Math.round(image.naturalHeight*scale));
53
+ const ctx=canvas.getContext('2d');if(!ctx)throw new Error('A 2D canvas is unavailable.');
54
+ ctx.drawImage(image,0,0,canvas.width,canvas.height);
55
+ const blob=await new Promise(resolve=>canvas.toBlob(resolve,'image/png'));canvas.width=canvas.height=0;
56
+ if(!blob)throw new Error('Could not prepare the gesture image. Choose a valid image and retry.');
57
+ const controller=new AbortController();const timer=setTimeout(()=>controller.abort(),120000);
58
+ try{
59
+ const response=await fetch(`./api/gesture?threshold=${encodeURIComponent(threshold)}`,{method:'POST',headers:{'Content-Type':'image/png'},body:blob,signal:controller.signal});
60
+ if(response.status===404||response.status===405)throw new Error('CPU compatibility is not deployed yet. Upload the complete CPU fix package, including README.md, app.py and packages.txt, to this Space and wait for the Gradio build to finish.');
61
+ let data;try{data=await response.json();}catch{throw new Error('The Space CPU did not return a recognition result. Wait for the Space to finish starting and retry.');}
62
+ if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'The Space CPU could not complete this run. Retry shortly.');
63
+ if(data.task!=='gesture'||!Array.isArray(data.hands))throw new Error('The Space CPU returned an invalid gesture result.');
64
+ data.inputSize={width:image.naturalWidth,height:image.naturalHeight};return data;
65
+ }catch(e){if(e.name==='AbortError')throw new Error('The Space CPU took too long to respond. Wait a moment and retry.');throw e;}
66
+ finally{clearTimeout(timer);}
67
+ }
68
+ export async function recognizeGesture(image,threshold,progress){
69
+ requireReadableImage(image);
70
+ let model;
71
+ try{
72
+ model=await cached('gesture',async()=>{
73
+ // 独立HTML画布保留可用设备的浏览器推理;无WebGL时由真正的Space CPU接口接手。
74
+ const canvas=document.createElement('canvas');canvas.width=canvas.height=2;
75
+ const gl=canvas.getContext('webgl2');
76
+ if(!gl||gl.isContextLost())throw new Error('WebGL2 is unavailable.');
77
+ progress('Loading hand landmarks and gesture classifier…');
78
+ const {FilesetResolver,GestureRecognizer}=await import('./vendor/vision_bundle.mjs');
79
+ const files=await FilesetResolver.forVisionTasks('./vendor/wasm');
80
+ return GestureRecognizer.createFromOptions(files,{canvas,baseOptions:{modelAssetPath:'./models/gesture_recognizer.task',delegate:'CPU'},runningMode:'IMAGE',numHands:2});
81
+ });
82
+ progress('Recognizing the static hand pose…');
83
+ const raw=model.recognize(image);
84
+ const hands=raw.landmarks.map((points,i)=>{const g=raw.gestures[i]?.[0];const accepted=Boolean(g&&g.categoryName!=='None'&&g.score>=threshold);return {label:accepted?g.categoryName:'Unrecognized',candidate:g?.categoryName||'None',score:g?.score||0,accepted,handedness:raw.handedness[i]?.[0]?.categoryName||'Unknown',points:points.map(p=>({x:p.x,y:p.y,z:p.z}))};});
85
+ return {task:'gesture',model:versions.gesture,backend:'Browser CPU (WebGL image input)',threshold,hands,note:hands.length?'Static gesture categories; not sign-language translation.':'No hand detected. Try a clear, complete hand on a simple background.'};
86
+ }catch(e){
87
+ // 清除坏图形任务;上下文错误自动回退,其他输入/权重错误保持真实失败。
88
+ caches.delete('gesture');try{model?.close();}catch{}
89
+ if(/activeTexture|WebGL|OpenGL|context/i.test(e.message))return recognizeGestureOnCPU(image,threshold,progress);
90
+ throw e;
91
+ }
92
+ }
93
+ export async function recognizeOCR(image,psm,progress){
94
+ requireReadableImage(image);
95
+ const worker=await cached('ocr',()=>Tesseract.createWorker('eng',1,{workerPath:'./vendor/worker.min.js',corePath:'./vendor/tesseract-core',langPath:'./models',logger:m=>progress(`${m.status}${Number.isFinite(m.progress)?' '+Math.round(m.progress*100)+'%':''}`)}));
96
+ await worker.setParameters({tessedit_pageseg_mode:String(psm)});
97
+ progress('Reading printed English text…');
98
+ const {data}=await worker.recognize(image);
99
+ return {task:'ocr',model:versions.ocr,psm,text:data.text.trim(),confidence:data.confidence,words:(data.words||[]).map(w=>({text:w.text,confidence:w.confidence,box:w.bbox})),note:'Confidence is a review cue, not measured accuracy. Check every important character against the image.'};
100
+ }
101
+ export const handConnections=[[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]];
requirements.txt CHANGED
@@ -1,5 +1,8 @@
1
  # -*- coding: utf-8 -*-
2
- # CPU兼容后端;固定NumPy/OpenCV/JAX版本,避免旧版MediaPipe依赖解析到不兼容的新版本。
 
 
 
3
  mediapipe==0.10.18
4
  numpy==1.26.4
5
  opencv-contrib-python==4.11.0.86
 
1
  # -*- coding: utf-8 -*-
2
+ # Gradio SDK自动安装;版本固定,使用CPU模型,不调用GPU或Docker。
3
+ gradio==5.49.1
4
+ pydantic==2.11.10
5
+ huggingface-hub==0.35.3
6
  mediapipe==0.10.18
7
  numpy==1.26.4
8
  opencv-contrib-python==4.11.0.86
server.py CHANGED
@@ -1,129 +1,129 @@
1
- """提供原页面和MediaPipe CPU兼容接口;图片仅在本次请求内存中处理。"""
2
- from contextlib import asynccontextmanager
3
- from io import BytesIO
4
- from pathlib import Path
5
- from threading import Lock
6
- import asyncio
7
- import math
8
-
9
- import mediapipe as mp
10
- import numpy as np
11
- from fastapi import FastAPI, HTTPException, Request
12
- from fastapi.responses import FileResponse, JSONResponse
13
- from fastapi.staticfiles import StaticFiles
14
- from PIL import Image, ImageOps, UnidentifiedImageError
15
-
16
- ROOT = Path(__file__).resolve().parent
17
- MAX_BYTES = 16 * 1024 * 1024
18
- MAX_PIXELS = 24_000_000
19
- Image.MAX_IMAGE_PIXELS = MAX_PIXELS
20
- recognizer = None
21
- recognizer_lock = Lock()
22
- MODEL_NAME = 'MediaPipe Tasks Vision 0.10.18'
23
- RELEASE = '20261013-recovery-1'
24
-
25
-
26
- @asynccontextmanager
27
- async def lifespan(application):
28
- """启动时加载同一task文件;显式指定CPU并在服务结束时释放。"""
29
- global recognizer
30
- options = mp.tasks.vision.GestureRecognizerOptions(
31
- base_options=mp.tasks.BaseOptions(
32
- model_asset_path=str(ROOT / 'models/gesture_recognizer.task'),
33
- delegate=mp.tasks.BaseOptions.Delegate.CPU),
34
- running_mode=mp.tasks.vision.RunningMode.IMAGE,
35
- num_hands=2)
36
- recognizer = mp.tasks.vision.GestureRecognizer.create_from_options(options)
37
- try:
38
- yield
39
- finally:
40
- recognizer.close()
41
- recognizer = None
42
-
43
-
44
- app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
45
-
46
-
47
- @app.get('/api/health')
48
- def health():
49
- """便于部署后确认CPU模型已就绪;此接口不接收图片。"""
50
- return {'ready': recognizer is not None, 'gesture_cpu': True,
51
- 'model': MODEL_NAME, 'version': RELEASE}
52
-
53
-
54
- def infer_gesture(payload, threshold):
55
- """串行调用非线程安全的Tasks对象;解码、推理及结果均不落盘。"""
56
- if not recognizer_lock.acquire(blocking=False):
57
- raise HTTPException(503, 'The Space CPU is busy. Wait a moment and retry.')
58
- try:
59
- try:
60
- with Image.open(BytesIO(payload)) as decoded:
61
- if decoded.format not in ('PNG', 'JPEG', 'WEBP'):
62
- raise HTTPException(415, 'Use a PNG, JPEG or WebP image.')
63
- if decoded.width * decoded.height > MAX_PIXELS:
64
- raise HTTPException(413, 'Use an image of at most 24 megapixels.')
65
- rgb = np.ascontiguousarray(np.asarray(ImageOps.exif_transpose(decoded).convert('RGB')))
66
- except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
67
- raise HTTPException(400, 'Could not decode this image. Choose a valid image and retry.')
68
- raw = recognizer.recognize(mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb))
69
- hands = []
70
- for i, points in enumerate(raw.hand_landmarks):
71
- gesture = raw.gestures[i][0] if raw.gestures[i] else None
72
- candidate = gesture.category_name if gesture else 'None'
73
- score = float(gesture.score) if gesture else 0.0
74
- accepted = bool(gesture and candidate != 'None' and score >= threshold)
75
- handedness = raw.handedness[i][0].category_name if raw.handedness[i] else 'Unknown'
76
- hands.append({'label': candidate if accepted else 'Unrecognized',
77
- 'candidate': candidate, 'score': score, 'accepted': accepted,
78
- 'handedness': handedness,
79
- 'points': [{'x': p.x, 'y': p.y, 'z': p.z} for p in points]})
80
- return {'task': 'gesture', 'model': MODEL_NAME, 'backend': 'Space CPU', 'serverBuild': RELEASE,
81
- 'threshold': threshold, 'hands': hands,
82
- 'processedSize': {'width': int(rgb.shape[1]), 'height': int(rgb.shape[0])},
83
- 'note': 'Static gesture categories; not sign-language translation.' if hands else
84
- 'No hand detected. Try a clear, complete hand on a simple background.'}
85
- finally:
86
- recognizer_lock.release()
87
-
88
-
89
- @app.post('/api/gesture')
90
- async def gesture(request: Request, threshold: float = 0.6):
91
- """限制上传大小和阈值;CPU推理移入线程,健康检查和页面读取仍可响应。"""
92
- if not math.isfinite(threshold) or not 0 <= threshold <= 1:
93
- raise HTTPException(400, 'The gesture score threshold must be between 0 and 1.')
94
- payload = bytearray()
95
- async for chunk in request.stream():
96
- payload.extend(chunk)
97
- if len(payload) > MAX_BYTES:
98
- raise HTTPException(413, 'Use an image under 16 MB.')
99
- if not payload:
100
- raise HTTPException(400, 'Choose an image before running recognition.')
101
- try:
102
- result = await asyncio.to_thread(infer_gesture, payload, threshold)
103
- except HTTPException:
104
- raise
105
- except Exception:
106
- # 不把图像内容、请求体或后端调用栈写入日志/返回给客户端。
107
- raise HTTPException(500, 'The CPU model could not complete this run. Retry with a clear hand image.')
108
- return JSONResponse(result, headers={'Cache-Control': 'no-store'})
109
-
110
-
111
- # 只暴露必需的静态目录和白名单文件,仓库其余内容不对外提供。
112
- for directory in ('vendor', 'models', 'samples'):
113
- app.mount('/' + directory, StaticFiles(directory=ROOT / directory), name=directory)
114
- PUBLIC_FILES = {'index.html', 'style.css', 'app.js', 'recognizers.js',
115
- 'how-to-start.html', 'how-to-start.pdf', 'THIRD_PARTY_NOTICES.md'}
116
-
117
-
118
- @app.get('/')
119
- def home():
120
- """显示与Static版相同的课程首页。"""
121
- return FileResponse(ROOT / 'index.html', headers={'Cache-Control': 'no-cache'})
122
-
123
-
124
- @app.get('/{file_name}')
125
- def public_file(file_name: str):
126
- """模块使用版本参数;HTML和脚本不强缓存,方便后续替换补丁。"""
127
- if file_name not in PUBLIC_FILES:
128
- raise HTTPException(404, 'Not found')
129
- return FileResponse(ROOT / file_name, headers={'Cache-Control': 'no-cache'})
 
1
+ """提供原页面和MediaPipe CPU兼容接口;图片仅在本次请求内存中处理。"""
2
+ from contextlib import asynccontextmanager
3
+ from io import BytesIO
4
+ from pathlib import Path
5
+ from threading import Lock
6
+ import asyncio
7
+ import math
8
+
9
+ import mediapipe as mp
10
+ import numpy as np
11
+ from fastapi import FastAPI, HTTPException, Request
12
+ from fastapi.responses import FileResponse, JSONResponse
13
+ from fastapi.staticfiles import StaticFiles
14
+ from PIL import Image, ImageOps, UnidentifiedImageError
15
+
16
+ ROOT = Path(__file__).resolve().parent
17
+ MAX_BYTES = 16 * 1024 * 1024
18
+ MAX_PIXELS = 24_000_000
19
+ Image.MAX_IMAGE_PIXELS = MAX_PIXELS
20
+ recognizer = None
21
+ recognizer_lock = Lock()
22
+ MODEL_NAME = 'MediaPipe Tasks Vision 0.10.18'
23
+ RELEASE = '20261013-gradio-1'
24
+
25
+
26
+ @asynccontextmanager
27
+ async def lifespan(application):
28
+ """启动时加载同一task文件;显式指定CPU并在服务结束时释放。"""
29
+ global recognizer
30
+ options = mp.tasks.vision.GestureRecognizerOptions(
31
+ base_options=mp.tasks.BaseOptions(
32
+ model_asset_path=str(ROOT / 'models/gesture_recognizer.task'),
33
+ delegate=mp.tasks.BaseOptions.Delegate.CPU),
34
+ running_mode=mp.tasks.vision.RunningMode.IMAGE,
35
+ num_hands=2)
36
+ recognizer = mp.tasks.vision.GestureRecognizer.create_from_options(options)
37
+ try:
38
+ yield
39
+ finally:
40
+ recognizer.close()
41
+ recognizer = None
42
+
43
+
44
+ app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
45
+
46
+
47
+ @app.get('/api/health')
48
+ def health():
49
+ """便于部署后确认CPU模型已就绪;此接口不接收图片。"""
50
+ return {'ready': recognizer is not None, 'gesture_cpu': True,
51
+ 'model': MODEL_NAME, 'version': RELEASE, 'sdk': 'gradio'}
52
+
53
+
54
+ def infer_gesture(payload, threshold):
55
+ """串行调用非线程安全的Tasks对象;解码、推理及结果均不落盘。"""
56
+ if not recognizer_lock.acquire(blocking=False):
57
+ raise HTTPException(503, 'The Space CPU is busy. Wait a moment and retry.')
58
+ try:
59
+ try:
60
+ with Image.open(BytesIO(payload)) as decoded:
61
+ if decoded.format not in ('PNG', 'JPEG', 'WEBP'):
62
+ raise HTTPException(415, 'Use a PNG, JPEG or WebP image.')
63
+ if decoded.width * decoded.height > MAX_PIXELS:
64
+ raise HTTPException(413, 'Use an image of at most 24 megapixels.')
65
+ rgb = np.ascontiguousarray(np.asarray(ImageOps.exif_transpose(decoded).convert('RGB')))
66
+ except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
67
+ raise HTTPException(400, 'Could not decode this image. Choose a valid image and retry.')
68
+ raw = recognizer.recognize(mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb))
69
+ hands = []
70
+ for i, points in enumerate(raw.hand_landmarks):
71
+ gesture = raw.gestures[i][0] if raw.gestures[i] else None
72
+ candidate = gesture.category_name if gesture else 'None'
73
+ score = float(gesture.score) if gesture else 0.0
74
+ accepted = bool(gesture and candidate != 'None' and score >= threshold)
75
+ handedness = raw.handedness[i][0].category_name if raw.handedness[i] else 'Unknown'
76
+ hands.append({'label': candidate if accepted else 'Unrecognized',
77
+ 'candidate': candidate, 'score': score, 'accepted': accepted,
78
+ 'handedness': handedness,
79
+ 'points': [{'x': p.x, 'y': p.y, 'z': p.z} for p in points]})
80
+ return {'task': 'gesture', 'model': MODEL_NAME, 'backend': 'Space CPU', 'serverBuild': RELEASE,
81
+ 'threshold': threshold, 'hands': hands,
82
+ 'processedSize': {'width': int(rgb.shape[1]), 'height': int(rgb.shape[0])},
83
+ 'note': 'Static gesture categories; not sign-language translation.' if hands else
84
+ 'No hand detected. Try a clear, complete hand on a simple background.'}
85
+ finally:
86
+ recognizer_lock.release()
87
+
88
+
89
+ @app.post('/api/gesture')
90
+ async def gesture(request: Request, threshold: float = 0.6):
91
+ """限制上传大小和阈值;CPU推理移入线程,健康检查和页面读取仍可响应。"""
92
+ if not math.isfinite(threshold) or not 0 <= threshold <= 1:
93
+ raise HTTPException(400, 'The gesture score threshold must be between 0 and 1.')
94
+ payload = bytearray()
95
+ async for chunk in request.stream():
96
+ payload.extend(chunk)
97
+ if len(payload) > MAX_BYTES:
98
+ raise HTTPException(413, 'Use an image under 16 MB.')
99
+ if not payload:
100
+ raise HTTPException(400, 'Choose an image before running recognition.')
101
+ try:
102
+ result = await asyncio.to_thread(infer_gesture, payload, threshold)
103
+ except HTTPException:
104
+ raise
105
+ except Exception:
106
+ # 不把图像内容、请求体或后端调用栈写入日志/返回给客户端。
107
+ raise HTTPException(500, 'The CPU model could not complete this run. Retry with a clear hand image.')
108
+ return JSONResponse(result, headers={'Cache-Control': 'no-store'})
109
+
110
+
111
+ # 只暴露必需的静态目录和白名单文件,仓库其余内容不对外提供。
112
+ for directory in ('vendor', 'models', 'samples'):
113
+ app.mount('/' + directory, StaticFiles(directory=ROOT / directory), name=directory)
114
+ PUBLIC_FILES = {'index.html', 'style.css', 'app.js', 'recognizers.js',
115
+ 'how-to-start.html', 'how-to-start.pdf', 'THIRD_PARTY_NOTICES.md'}
116
+
117
+
118
+ @app.get('/')
119
+ def home():
120
+ """显示与Static版相同的课程首页。"""
121
+ return FileResponse(ROOT / 'index.html', headers={'Cache-Control': 'no-cache'})
122
+
123
+
124
+ @app.get('/{file_name}')
125
+ def public_file(file_name: str):
126
+ """模块使用版本参数;HTML和脚本不强缓存,方便后续替换补丁。"""
127
+ if file_name not in PUBLIC_FILES:
128
+ raise HTTPException(404, 'Not found')
129
+ return FileResponse(ROOT / file_name, headers={'Cache-Control': 'no-cache'})