oscarzhang commited on
Commit
f427ff2
·
verified ·
1 Parent(s): 8713446

Upload API_USAGE.md with huggingface_hub

Browse files
Files changed (1) hide show
  1. API_USAGE.md +262 -0
API_USAGE.md ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wearable Anomaly Detector 接口文档
2
+
3
+ 本指南说明 `hf_release` 目录下各核心模块的调用方式,涵盖输入输出格式、常用方法与示例。
4
+
5
+ ---
6
+
7
+ ## 1. 初始化
8
+
9
+ ```python
10
+ from wearable_anomaly_detector import WearableAnomalyDetector
11
+
12
+ detector = WearableAnomalyDetector(
13
+ model_dir="checkpoints/phase2/exp_factor_balanced",
14
+ device="cpu", # 可选,默认自动检测
15
+ threshold=None # 可选,未设置时使用配置/默认阈值
16
+ )
17
+ ```
18
+
19
+ | 参数 | 说明 |
20
+ | --- | --- |
21
+ | `model_dir` | Phase2 最佳权重所在目录,必须包含 `best_model.pt` |
22
+ | `device` | `"cpu"` / `"cuda"` / `"cuda:0"` 等 |
23
+ | `threshold` | 手动指定异常阈值(浮点数),不指定则使用配置或默认值 0.53 |
24
+
25
+ ---
26
+
27
+ ## 2. 数据结构
28
+
29
+ ### 2.1 单个数据点 (`dict`)
30
+
31
+ ```python
32
+ {
33
+ "timestamp": "2025-01-01T08:00:00",
34
+ "deviceId": "demo_user",
35
+ "features": {
36
+ "hr": 72.0,
37
+ "hrv_rmssd": 35.0,
38
+ "time_period_primary": "day",
39
+ "data_quality": "high",
40
+ "...": "..."
41
+ },
42
+ "static_features": {
43
+ "age_group": 2,
44
+ "sex": 0,
45
+ "exercise": 1
46
+ }
47
+ }
48
+ ```
49
+
50
+ - 单个窗口需 12 条 5 分钟数据,顺序按时间递增。
51
+ - 缺失字段会自动回退到 `configs/features_config.json` 的默认值或分类映射。
52
+
53
+ ### 2.2 `data_points` / `windows`
54
+
55
+ - **实时检测**需要 1 个窗口(`List[Dict]`)。
56
+ - **模式聚合**可传 `List[List[Dict]]`(每个内部列表代表一天)。
57
+
58
+ ### 2.3 缺失字段与低质量数据
59
+
60
+ - 若某些特征缺失,直接删除键即可,推理时会回退到默认值。
61
+ - 静态特征缺失可将 `static_features` 设为空字典。
62
+ - 对于传感器丢包,可将 `hr` 等数值设为 `float("nan")`,模型会忽略该值。
63
+ - 仓库内提供 `test_data/example_window.json`,可直接作为 12 条完整窗口输入,用于验证 API 行为。
64
+
65
+ ```python
66
+ window = build_window()
67
+ for point in window:
68
+ point["features"].pop("hr_resting", None) # 删除可选特征
69
+ point["features"]["data_quality"] = "low" # 标记质量
70
+ window[0]["static_features"] = {} # 缺少静态信息
71
+ window[3]["features"]["hr"] = float("nan") # 某个时间点无心率
72
+
73
+ result = detector.detect_realtime(window, update_baseline=False)
74
+ ```
75
+
76
+ ```python
77
+ import json, Path
78
+ with open("test_data/example_window.json", "r") as f:
79
+ sample_window = json.load(f)
80
+ result = detector.detect_realtime(sample_window, update_baseline=False)
81
+ ```
82
+
83
+ ### 2.4 官方测试脚本
84
+
85
+ 若只想“读取一个 JSON → 获取模型输出”,可以直接运行:
86
+
87
+ ```bash
88
+ python run_official_inference.py \
89
+ --window-file test_data/example_window.json \
90
+ --model-dir checkpoints/phase2/exp_factor_balanced
91
+ ```
92
+
93
+ 脚本会输出:
94
+
95
+ 1. 模型原始 JSON 结果
96
+ 2. 由 `AnomalyFormatter` 生成的 Markdown 文本
97
+
98
+ 替换 `--window-file` 为自己的窗口数据即可模拟正式 API 调用。
99
+
100
+ ---
101
+
102
+ ## 3. `WearableAnomalyDetector` 方法
103
+
104
+ ### 3.1 `predict(data_points, return_score=True, return_details=False)`
105
+
106
+ 用于直接推理(无附加逻辑)。
107
+
108
+ ```python
109
+ result = detector.predict(window, return_score=True, return_details=True)
110
+ ```
111
+
112
+ **返回示例**
113
+
114
+ ```python
115
+ {
116
+ "is_anomaly": False,
117
+ "threshold": 0.53,
118
+ "anomaly_score": 0.47,
119
+ "details": {
120
+ "window_size": 12,
121
+ "model_output": 0.47,
122
+ "prediction_confidence": 0.06
123
+ }
124
+ }
125
+ ```
126
+
127
+ ### 3.2 `detect_realtime(data_points, update_baseline=True, ...)`
128
+
129
+ 在 `predict` 基础上,附加基线更新等逻辑,适合直接接入实时服务。
130
+
131
+ ```python
132
+ result = detector.detect_realtime(window, update_baseline=False)
133
+ ```
134
+
135
+ | 参数 | 默认值 | 说明 |
136
+ | --- | --- | --- |
137
+ | `data_points` | 必填 | 最新窗口数据 |
138
+ | `update_baseline` | `True` | 是否在推理后更新基线 |
139
+ | `return_score` | `True` | 是否返回异常分数 |
140
+ | `return_details` | `False` | 是否返回详细字段 |
141
+
142
+ ### 3.3 `detect_pattern(data_points, days=None, min_duration_days=3, format_for_llm=False)`
143
+
144
+ 对多天数据做异常模式聚合,输出模式摘要及可选的 LLM 文本。
145
+
146
+ ```python
147
+ pattern_result = detector.detect_pattern(daily_data, days=7, format_for_llm=True)
148
+ ```
149
+
150
+ **返回示例**
151
+
152
+ ```python
153
+ {
154
+ "anomaly_pattern": {
155
+ "has_pattern": True,
156
+ "duration_days": 3,
157
+ "trend": "stable",
158
+ "anomaly_type": "continuous_anomaly"
159
+ },
160
+ "formatted_for_llm": "...结构化 Markdown 文本..."
161
+ }
162
+ ```
163
+
164
+ ---
165
+
166
+ ## 4. `AnomalyFormatter`
167
+
168
+ 将检测结果、基线信息、历史趋势等转换为适合 LLM 的文本。
169
+
170
+ ```python
171
+ from utils.formatter import AnomalyFormatter
172
+
173
+ formatter = AnomalyFormatter() # 可传 config_path 指向自定义格式
174
+ text = formatter.format_for_llm(
175
+ anomaly_result=result,
176
+ baseline_info={
177
+ "baseline_mean": 75.0,
178
+ "baseline_std": 5.0,
179
+ "current_value": 68.0,
180
+ "deviation_pct": -9.3
181
+ },
182
+ daily_results=None
183
+ )
184
+ print(text)
185
+ ```
186
+
187
+ **常用参数**
188
+
189
+ | 参数 | 类型 | 说明 |
190
+ | --- | --- | --- |
191
+ | `anomaly_result` | `dict` | 来自 `predict/detect_realtime` 的结果 |
192
+ | `baseline_info` | `dict` | 基线均值/标准差、当前值、偏离百分比等 |
193
+ | `related_indicators` | `dict` | 睡眠、活动、压力等指标,可选 |
194
+ | `daily_results` | `List[dict]` | 多天趋势(日期 + HRV/分数),可选 |
195
+
196
+ ---
197
+
198
+ ## 5. `BaselineStorage`(可选)
199
+
200
+ 路径:`utils/baseline_storage.py`
201
+
202
+ ```python
203
+ from utils.baseline_storage import BaselineStorage
204
+
205
+ storage = BaselineStorage(
206
+ storage_type="file",
207
+ file_path="data_storage/baselines.json",
208
+ import_from_csv=False
209
+ )
210
+
211
+ storage.save_baseline({
212
+ "device_id": "demo_user",
213
+ "feature_name": "hrv_rmssd",
214
+ "baseline_type": "personal",
215
+ "baseline_mean": 75.0,
216
+ "baseline_std": 5.0,
217
+ "data_count": 30
218
+ })
219
+
220
+ baseline = storage.get_baseline("demo_user", "hrv_rmssd")
221
+ storage.update_baseline_incremental("demo_user", "hrv_rmssd", new_value=70.0, data_count=baseline["data_count"] + 1)
222
+ ```
223
+
224
+ ---
225
+
226
+ ## 6. 快速脚本
227
+
228
+ | 场景 | 文件 | 说明 |
229
+ | --- | --- | --- |
230
+ | 官方推理(与线上一致) | `run_official_inference.py` | `python run_official_inference.py --window-file test_data/example_window.json` |
231
+ | 多场景演示(随机噪声/缺失/连续异常) | `test_quickstart.py` | `python test_quickstart.py`(演示中会暂时调低阈值) |
232
+ | PatchTrAD → build_case 双模式演示 | `simulate_patchad_case_pipeline.py` | `python simulate_patchad_case_pipeline.py --mode all`(输出预筛结果、case、校验信息) |
233
+ | 交互体验(选择样例并查看输出) | `gradio_app.py` | `python gradio_app.py` 或部署到 Hugging Face Space |
234
+
235
+ ### 6.1 PatchTrAD + build_case 演示
236
+
237
+ ```bash
238
+ python simulate_patchad_case_pipeline.py --mode all
239
+ ```
240
+
241
+ 输出包含:
242
+ - 模式A:平台自带 PatchTrAD,直接 `POST /api/build_case`
243
+ - 模式B:官方 `precheck` → `build_case` 两次交互
244
+ - 校验失败示例(缺少 history_windows)
245
+
246
+ 可通过 `--mode platform` 或 `--mode official` 单独运行某个流程,也可替换 `--data-file` 为自有 JSONL。
247
+
248
+ ---
249
+
250
+ ## 7. 常见问题
251
+
252
+ | 问题 | 处理方式 |
253
+ | --- | --- |
254
+ | 没有配置文件 | `_load_config` 会自动回退默认值,无需额外设置 |
255
+ | 没有静态特征 | `FeatureCalculator` 将使用配置中的默认值 |
256
+ | 想换窗口尺寸 | 修改 `configs/detector_config.json` 中的 `detection.window_size` |
257
+ | 想换特征列表 | 修改 `configs/features_config.json`,无需改代码 |
258
+
259
+ ---
260
+
261
+ 如需更多示例或扩展,欢迎查看 `README.md` 的“真实数据测试”章节或提交 Issue。祝使用顺利!
262
+