WHU1psh commited on
Commit
9c1a06c
·
verified ·
1 Parent(s): 1f58ee5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +613 -0
app.py CHANGED
@@ -130,6 +130,619 @@ def init_space_storage() -> None:
130
  print(f"[INIT] CommitScheduler init failed: {e}")
131
 
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  init_space_storage()
134
 
135
  # Movie-Level 指标定义
 
130
  print(f"[INIT] CommitScheduler init failed: {e}")
131
 
132
 
133
+ init_space_storage()
134
+
135
+ # Movie-Level 指标定义
136
+ MOVIE_CRITERIA: List[Tuple[str, str, str]] = [
137
+ ("SF", "Script Faithfulness (剧本忠实度)", "生成的视觉内容与原始剧本描述的吻合程度。"),
138
+ ("NC", "Narrative Coherence (叙事连贯性)", "镜头间情节发展的逻辑性,确保故事表达清晰、不破碎。"),
139
+ ("VQ", "Visual Quality (视觉质量)", "画面的清晰度、噪点控制、光影效果等基础图像质量。"),
140
+ ("CC", "Character Consistency (角色一致性)", "同一角色在不同镜头、不同角度下的外貌、服装及特征的稳定性。"),
141
+ ("PLC", "Physical Law Compliance (物理规律符合度)", "运动、重力、碰撞等是否符合现实物理逻辑,是否存在严重 AI 幻觉。"),
142
+ ("V_AQ", "Voice/Audio Quality (语音/音频质量)", "配音、背景音乐和音效的清晰度、自然度及技术品质。"),
143
+ ("CT", "Cinematic Techniques (电影技巧)", "镜头运动、景深控制及构图的专业性。"),
144
+ ("AVR", "Audio-Visual Richness (视听丰富度)", "画面细节精细度以及音频层次(音效、氛围音)的丰富程度。"),
145
+ ("NP", "Narrative Pacing (叙事节奏)", "镜头剪辑长短切换是否契合故事情节张力需求。"),
146
+ ("VAC", "Video-Audio Coordination (视听协调性)", "画面动作与音效、音乐卡点的同步率。"),
147
+ ("CD", "Compelling Degree (引人入胜程度)", "吸引注意力并引发情感共鸣或沉浸感的能力。"),
148
+ ("OQ", "Overall Quality (整体质量)", "对生成视频作为“电影作品”的综合观感评分。"),
149
+ ]
150
+
151
+ BASE_METRIC_KEYS = [k for k, _, _ in MOVIE_CRITERIA]
152
+ SAVE_LOCK = threading.Lock()
153
+
154
+ CUSTOM_CSS = """
155
+ .gradio-container {
156
+ max-width: 1400px !important;
157
+ margin-left: auto !important;
158
+ margin-right: auto !important;
159
+ background:
160
+ radial-gradient(circle at 8% 12%, rgba(102, 124, 255, 0.16) 0%, rgba(102, 124, 255, 0) 28%),
161
+ radial-gradient(circle at 92% 18%, rgba(255, 107, 157, 0.11) 0%, rgba(255, 107, 157, 0) 30%),
162
+ linear-gradient(180deg, #0b1220 0%, #0d1526 52%, #0c1323 100%);
163
+ }
164
+ .title-text h1 {
165
+ text-align: center;
166
+ background: linear-gradient(135deg, #7c5cff 0%, #ff6b9d 100%);
167
+ -webkit-background-clip: text;
168
+ -webkit-text-fill-color: transparent;
169
+ font-size: 2rem;
170
+ font-weight: 760;
171
+ letter-spacing: 0.2px;
172
+ margin: 0 0 8px 0;
173
+ }
174
+ .title-sub {
175
+ text-align: center;
176
+ color: #c4d0f1;
177
+ margin-bottom: 14px;
178
+ }
179
+ #hero {
180
+ border: 1px solid #33456f;
181
+ border-radius: 16px;
182
+ padding: 20px 22px;
183
+ background: linear-gradient(130deg, #121f3f 0%, #1d2f5e 58%, #2b2a63 100%);
184
+ box-shadow: 0 14px 34px rgba(8, 10, 30, 0.42);
185
+ margin-bottom: 14px;
186
+ }
187
+ .hero-badge {
188
+ display: inline-block;
189
+ margin-top: 10px;
190
+ padding: 5px 12px;
191
+ border-radius: 999px;
192
+ border: 1px solid rgba(205, 220, 255, 0.42);
193
+ background: rgba(11, 22, 46, 0.52);
194
+ color: #d9e7ff;
195
+ font-size: 12px;
196
+ font-weight: 600;
197
+ }
198
+ .metric-grid {
199
+ display: grid;
200
+ grid-template-columns: repeat(3, minmax(110px, 1fr));
201
+ gap: 12px;
202
+ margin: 10px 0 16px 0;
203
+ }
204
+ .metric-card {
205
+ border: 1px solid #2f4166;
206
+ border-radius: 12px;
207
+ padding: 12px 14px;
208
+ background: linear-gradient(180deg, #111d33 0%, #111a2d 100%);
209
+ }
210
+ .metric-label {
211
+ color: #9fb0da;
212
+ font-size: 12px;
213
+ margin-bottom: 4px;
214
+ }
215
+ .metric-value {
216
+ color: #e8efff;
217
+ font-size: 16px;
218
+ font-weight: 700;
219
+ }
220
+ .panel {
221
+ border: 1px solid #2b3e64 !important;
222
+ border-radius: 14px !important;
223
+ padding: 14px !important;
224
+ background: linear-gradient(180deg, #111b31 0%, #10192d 100%) !important;
225
+ box-shadow: 0 8px 22px rgba(5, 10, 24, 0.28);
226
+ }
227
+ .section-title {
228
+ margin: 0 0 10px 0;
229
+ font-size: 1.04rem;
230
+ font-weight: 650;
231
+ color: #e2eaff;
232
+ }
233
+ .hint {
234
+ color: #9badd6;
235
+ font-size: 0.9rem;
236
+ }
237
+ .toolbar-btn {
238
+ min-height: 42px !important;
239
+ border-radius: 10px !important;
240
+ }
241
+ .gr-button-primary {
242
+ background: linear-gradient(180deg, #5f85ff 0%, #4a70f0 100%) !important;
243
+ border: 1px solid #90a8ff !important;
244
+ box-shadow: 0 8px 22px rgba(61, 103, 234, 0.35) !important;
245
+ }
246
+ .status-box {
247
+ border: 1px dashed #4a6398;
248
+ border-radius: 10px;
249
+ padding: 9px 11px;
250
+ background: #0c1529;
251
+ }
252
+ .soft-input textarea,
253
+ .soft-input input,
254
+ .soft-input .wrap {
255
+ border-radius: 10px !important;
256
+ }
257
+ .gr-accordion {
258
+ border-radius: 12px !important;
259
+ border-color: #2e426a !important;
260
+ }
261
+ """
262
+
263
+
264
+ def _safe_read_text(path: Path) -> str:
265
+ if not path.exists():
266
+ return ""
267
+ return path.read_text(encoding="utf-8-sig").strip()
268
+
269
+
270
+ def load_dataset_index() -> List[Dict[str, Any]]:
271
+ """扫描输入目录,构建可评测样本列表(每个方法-故事仅保留1个视频)。"""
272
+ stories = {p.stem: _safe_read_text(p) for p in sorted(STORY_DIR.glob("*.txt"))}
273
+ samples: List[Dict[str, Any]] = []
274
+
275
+ if not VIDEO_DIR.exists():
276
+ return samples
277
+
278
+ for method_dir in sorted([d for d in VIDEO_DIR.iterdir() if d.is_dir()]):
279
+ method = method_dir.name
280
+ for story_dir in sorted([d for d in method_dir.iterdir() if d.is_dir()]):
281
+ story_name = story_dir.name
282
+ # 每个方法-故事只评一次:如果有多个视频,默认取排序后第一个
283
+ video_candidates = sorted(story_dir.glob("*.mp4"))
284
+ if not video_candidates:
285
+ continue
286
+ video_path = video_candidates[0]
287
+ sample_id = f"{method}__{story_name}__{video_path.stem}"
288
+ samples.append(
289
+ {
290
+ "sample_id": sample_id,
291
+ "method": method,
292
+ "story_name": story_name,
293
+ "video_name": video_path.name,
294
+ "video_path": str(video_path.resolve()),
295
+ "story_text": stories.get(story_name, ""),
296
+ }
297
+ )
298
+ return samples
299
+
300
+
301
+ def load_evaluated_method_story_pairs() -> set:
302
+ """从结果目录读取已评估的 (method, story_name) 组合。"""
303
+ evaluated = set()
304
+ raw_root = OUTPUT_DIR / "raw_results"
305
+ if not raw_root.exists():
306
+ return evaluated
307
+
308
+ for fp in raw_root.rglob("*.json"):
309
+ try:
310
+ with open(fp, "r", encoding="utf-8-sig") as f:
311
+ data = json.load(f)
312
+ except Exception:
313
+ continue
314
+ sample = data.get("sample", {})
315
+ method = sample.get("method")
316
+ story_name = sample.get("story_name")
317
+ if method and story_name:
318
+ evaluated.add((method, story_name))
319
+ return evaluated
320
+
321
+
322
+ def build_pending_samples() -> List[Dict[str, Any]]:
323
+ """构建待评估样本池,并分配匿名ID。"""
324
+ all_samples = load_dataset_index()
325
+ evaluated_pairs = load_evaluated_method_story_pairs()
326
+ pending = [
327
+ s for s in all_samples
328
+ if (s["method"], s["story_name"]) not in evaluated_pairs
329
+ ]
330
+ for i, sample in enumerate(pending, start=1):
331
+ sample["anon_id"] = f"id_{i:03d}"
332
+ return pending
333
+
334
+
335
+ def build_data_diagnostics(samples: List[Dict[str, Any]]) -> str:
336
+ return (
337
+ f"**SPACE_MODE**: `{SPACE_MODE}` \n"
338
+ f"**DATA_REPO_ID**: `{DATA_REPO_ID}` \n"
339
+ f"**RESULTS_REPO_ID**: `{RESULTS_REPO_ID}` \n"
340
+ f"**ROOT_DIR**: `{ROOT_DIR}` \n"
341
+ f"**INPUT_DIR exists**: `{INPUT_DIR.exists()}` \n"
342
+ f"**STORY_DIR exists**: `{STORY_DIR.exists()}` \n"
343
+ f"**VIDEO_DIR exists**: `{VIDEO_DIR.exists()}` \n"
344
+ f"**Pending samples**: `{len(samples)}`"
345
+ )
346
+
347
+
348
+ def compute_derived(scores: Dict[str, float]) -> Dict[str, float]:
349
+ """计算 CL / CRh / AVG。"""
350
+ cl = (
351
+ (scores["SF"] + scores["NC"] + scores["VQ"] + scores["CC"] + scores["PLC"]) / 5.0
352
+ + 0.5 * ((scores["CT"] + scores["AVR"]) / 2.0)
353
+ )
354
+ crh = (
355
+ (scores["V_AQ"] + scores["NP"] + scores["VAC"] + scores["CD"] + scores["OQ"]) / 5.0
356
+ + 0.5 * ((scores["CT"] + scores["AVR"]) / 2.0)
357
+ )
358
+ avg = sum(scores[k] for k in BASE_METRIC_KEYS) / len(BASE_METRIC_KEYS)
359
+ return {"CL": cl, "CRh": crh, "AVG": avg}
360
+
361
+
362
+ def save_single_result(sample: Dict[str, Any], evaluator_id: str, scores: Dict[str, int], reasons: Dict[str, str], summary: str) -> Path:
363
+ """保存单个问卷结果。"""
364
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
365
+ result_dir = OUTPUT_DIR / "raw_results" / sample["method"] / sample["story_name"]
366
+ result_dir.mkdir(parents=True, exist_ok=True)
367
+ out_path = result_dir / f"{sample['video_name'].replace('.mp4', '')}_{evaluator_id}_{ts}.json"
368
+
369
+ score_float = {k: float(v) for k, v in scores.items()}
370
+ derived = compute_derived(score_float)
371
+
372
+ payload = {
373
+ "timestamp": datetime.now().isoformat(),
374
+ "evaluator_id": evaluator_id,
375
+ "sample": sample,
376
+ "scores": scores,
377
+ "reasons": reasons,
378
+ "summary": summary,
379
+ "derived": derived,
380
+ }
381
+ with open(out_path, "w", encoding="utf-8") as f:
382
+ json.dump(payload, f, ensure_ascii=False, indent=2)
383
+ return out_path
384
+
385
+
386
+ def recompute_method_aggregates() -> Path:
387
+ """
388
+ 统计每个方法各维度均分,并输出 method_aggregates.json。
389
+ 同时给出 CL/CRh/AVG 的方法均值。
390
+ """
391
+ raw_root = OUTPUT_DIR / "raw_results"
392
+ method_scores: Dict[str, Dict[str, List[float]]] = defaultdict(lambda: defaultdict(list))
393
+ method_count: Dict[str, int] = defaultdict(int)
394
+
395
+ if raw_root.exists():
396
+ for fp in raw_root.rglob("*.json"):
397
+ with open(fp, "r", encoding="utf-8-sig") as f:
398
+ data = json.load(f)
399
+ method = data.get("sample", {}).get("method", "UNKNOWN")
400
+ scores = data.get("scores", {})
401
+ if not all(k in scores for k in BASE_METRIC_KEYS):
402
+ continue
403
+ method_count[method] += 1
404
+ for k in BASE_METRIC_KEYS:
405
+ method_scores[method][k].append(float(scores[k]))
406
+
407
+ # 衍生指标也参与方法均值统计
408
+ derived = compute_derived({k: float(scores[k]) for k in BASE_METRIC_KEYS})
409
+ for d_key, d_val in derived.items():
410
+ method_scores[method][d_key].append(float(d_val))
411
+
412
+ agg = {
413
+ "updated_at": datetime.now().isoformat(),
414
+ "metric_keys": BASE_METRIC_KEYS,
415
+ "derived_keys": ["CL", "CRh", "AVG"],
416
+ "methods": {},
417
+ }
418
+ for method in sorted(method_scores.keys()):
419
+ metric_avg = {}
420
+ for key, vals in method_scores[method].items():
421
+ metric_avg[key] = round(sum(vals) / len(vals), 4) if vals else None
422
+ agg["methods"][method] = {
423
+ "num_submissions": method_count[method],
424
+ "avg_scores": metric_avg,
425
+ }
426
+
427
+ out_path = OUTPUT_DIR / "method_aggregates.json"
428
+ with open(out_path, "w", encoding="utf-8") as f:
429
+ json.dump(agg, f, ensure_ascii=False, indent=2)
430
+ return out_path
431
+
432
+
433
+ def build_sample_brief(sample: Dict[str, Any], index: int, total: int) -> str:
434
+ story = sample.get("story_text") or "(未找到对应 story 文本,请检查 clip_movie_story 下是否有同名 txt)"
435
+ return (
436
+ f"### 当前匿名样本 {index + 1}/{total}\n"
437
+ f"- **Sample ID**: `{sample['anon_id']}`\n\n"
438
+ f"### Story Description\n{story}"
439
+ )
440
+
441
+
442
+ def create_app():
443
+ samples = build_pending_samples()
444
+ sample_map = {s["anon_id"]: s for s in samples}
445
+
446
+ with gr.Blocks(
447
+ title="VideoEval Movie-Level Evaluation",
448
+ css=CUSTOM_CSS,
449
+ theme=gr.themes.Soft(primary_hue="purple", secondary_hue="pink", neutral_hue="slate"),
450
+ ) as app:
451
+ gr.Markdown("# VideoEval · Movie-Level Evaluation", elem_classes=["title-text"])
452
+ gr.Markdown("统一电影级评测问卷,支持方法级均分统计(含 CL / CRh / AVG)", elem_classes=["title-sub"])
453
+
454
+ gr.HTML(
455
+ f"""
456
+ <div id="hero">
457
+ <div class="hero-badge">HF Space Ready · Gradio Blocks · Clean Review Flow</div>
458
+ <div class="metric-grid">
459
+ <div class="metric-card">
460
+ <div class="metric-label">Pending Samples</div>
461
+ <div class="metric-value">{len(samples)}</div>
462
+ </div>
463
+ <div class="metric-card">
464
+ <div class="metric-label">Evaluation Scope</div>
465
+ <div class="metric-value">Movie-Level</div>
466
+ </div>
467
+ <div class="metric-card">
468
+ <div class="metric-label">Scoring Standard</div>
469
+ <div class="metric-value">12 Metrics · 1~5</div>
470
+ </div>
471
+ </div>
472
+ </div>
473
+ """
474
+ )
475
+ gr.Markdown(
476
+ f"<span class='hint'>输入目录:`{INPUT_DIR}` | 输出目录:`{OUTPUT_DIR}`</span>",
477
+ )
478
+ with gr.Accordion("系统诊断信息(展开查看)", open=False):
479
+ gr.Markdown(build_data_diagnostics(samples))
480
+
481
+ current_idx = gr.State(0)
482
+ evaluator_state = gr.State("anonymous")
483
+
484
+ with gr.Row():
485
+ with gr.Column(scale=4, elem_classes=["panel"]):
486
+ gr.Markdown("<div class='section-title'>1) 评测员与样本</div>")
487
+ with gr.Row():
488
+ evaluator_input = gr.Textbox(label="Evaluator ID", value="anonymous", elem_classes=["soft-input"])
489
+ sample_dropdown = gr.Dropdown(
490
+ label="选择评测样本(匿名)",
491
+ choices=[s["anon_id"] for s in samples],
492
+ value=samples[0]["anon_id"] if samples else None,
493
+ interactive=True,
494
+ elem_classes=["soft-input"],
495
+ )
496
+ with gr.Row():
497
+ prev_btn = gr.Button("← Previous", elem_classes=["toolbar-btn"])
498
+ next_btn = gr.Button("Next →", elem_classes=["toolbar-btn"])
499
+ submit_btn = gr.Button("提交当前评分并统计", variant="primary", elem_classes=["toolbar-btn"])
500
+ status = gr.Markdown("<div class='status-box'>等待提交</div>")
501
+ with gr.Column(scale=8, elem_classes=["panel"]):
502
+ gr.Markdown("<div class='section-title'>2) 视频与剧情</div>")
503
+ movie_video = gr.Video(label="Movie Video", value=samples[0]["video_path"] if samples else None, height=460)
504
+ sample_info = gr.Markdown("无可用样本" if not samples else build_sample_brief(samples[0], 0, len(samples)))
505
+
506
+ gr.Markdown("## 3) Movie-Level 指标评分(1-5)")
507
+ gr.Markdown("<span class='hint'>先给分,再填写可选理由。未打分无法提交。</span>")
508
+
509
+ score_widgets: Dict[str, gr.Radio] = {}
510
+ reason_widgets: Dict[str, gr.Textbox] = {}
511
+ metric_groups = {
512
+ "I. 叙事与剧本 (NS)": ["SF", "NC"],
513
+ "II. 视听与技术 (AT)": ["VQ", "CC", "PLC", "V_AQ"],
514
+ "III. 美学与表现力 (AE)": ["CT", "AVR"],
515
+ "IV. 节奏与流动性 (RF)": ["NP", "VAC"],
516
+ "V. 情感与参与度 (EE)": ["CD"],
517
+ "VI. 整体体验 (OE)": ["OQ"],
518
+ }
519
+ criteria_map = {k: (name, desc) for k, name, desc in MOVIE_CRITERIA}
520
+
521
+ for section_title, keys in metric_groups.items():
522
+ with gr.Accordion(section_title, open=True):
523
+ for key in keys:
524
+ name, desc = criteria_map[key]
525
+ with gr.Group(elem_classes=["panel"]):
526
+ gr.Markdown(f"**{key} · {name}**")
527
+ gr.Markdown(f"<span class='hint'>{desc}</span>")
528
+ with gr.Row():
529
+ score_widgets[key] = gr.Radio(choices=[1, 2, 3, 4, 5], label=f"{key} Score", scale=1, elem_classes=["soft-input"])
530
+ reason_widgets[key] = gr.Textbox(label=f"{key} Reason(可选)", lines=2, placeholder="补充评分依据", scale=2, elem_classes=["soft-input"])
531
+
532
+ final_summary = gr.Textbox(label="Final Summary(可选)", lines=4, placeholder="总结该视频的主要优缺点", elem_classes=["soft-input"])
533
+
534
+ def _sync_sample_from_dropdown(anon_id: str) -> Tuple[str, str, int]:
535
+ if not anon_id or anon_id not in sample_map:
536
+ return None, "未找到样本", 0
537
+ idx = next(i for i, s in enumerate(samples) if s["anon_id"] == anon_id)
538
+ sample = samples[idx]
539
+ return sample["video_path"], build_sample_brief(sample, idx, len(samples)), idx
540
+
541
+ def _go_prev(idx: int) -> Tuple[str, str, str, int]:
542
+ if not samples:
543
+ return None, "无可用样本", None, 0
544
+ idx = max(0, idx - 1)
545
+ sample = samples[idx]
546
+ return sample["video_path"], build_sample_brief(sample, idx, len(samples)), sample["anon_id"], idx
547
+
548
+ def _go_next(idx: int) -> Tuple[str, str, str, int]:
549
+ if not samples:
550
+ return None, "无可用样本", None, 0
551
+ idx = min(len(samples) - 1, idx + 1)
552
+ sample = samples[idx]
553
+ return sample["video_path"], build_sample_brief(sample, idx, len(samples)), sample["anon_id"], idx
554
+
555
+ def _submit(evaluator_id: str, anon_id: str, summary: str, *score_reason_vals):
556
+ if not samples:
557
+ return "❌ 没有可提交样本。"
558
+ if not anon_id or anon_id not in sample_map:
559
+ return "❌ 请先选择样本。"
560
+ sample = sample_map[anon_id]
561
+ evaluator_id = (evaluator_id or "anonymous").strip() or "anonymous"
562
+
563
+ # 防重复:方法-故事只允许评估一次
564
+ evaluated_pairs = load_evaluated_method_story_pairs()
565
+ if (sample["method"], sample["story_name"]) in evaluated_pairs:
566
+ return "⚠️ 该方法-故事已经被评估过一次,请选择其他匿名样本。"
567
+
568
+ scores: Dict[str, int] = {}
569
+ reasons: Dict[str, str] = {}
570
+ for i, key in enumerate(BASE_METRIC_KEYS):
571
+ score = score_reason_vals[i * 2]
572
+ reason = score_reason_vals[i * 2 + 1]
573
+ if score is None:
574
+ return f"❌ 请为 `{key}` 打分。"
575
+ scores[key] = int(score)
576
+ reasons[key] = (reason or "").strip()
577
+
578
+ with SAVE_LOCK:
579
+ single_path = save_single_result(sample, evaluator_id, scores, reasons, summary or "")
580
+ agg_path = recompute_method_aggregates()
581
+
582
+ return f"✅ 已保存: `{single_path}`\n\n✅ 已更新方法统计: `{agg_path}`"
583
+
584
+ sample_dropdown.change(
585
+ _sync_sample_from_dropdown,
586
+ inputs=[sample_dropdown],
587
+ outputs=[movie_video, sample_info, current_idx],
588
+ )
589
+ prev_btn.click(_go_prev, inputs=[current_idx], outputs=[movie_video, sample_info, sample_dropdown, current_idx])
590
+ next_btn.click(_go_next, inputs=[current_idx], outputs=[movie_video, sample_info, sample_dropdown, current_idx])
591
+
592
+ submit_inputs = [evaluator_input, sample_dropdown, final_summary]
593
+ for key in BASE_METRIC_KEYS:
594
+ submit_inputs.append(score_widgets[key])
595
+ submit_inputs.append(reason_widgets[key])
596
+ submit_btn.click(_submit, inputs=submit_inputs, outputs=[status])
597
+
598
+ app.load(lambda x: x, inputs=[evaluator_input], outputs=[evaluator_state])
599
+
600
+ return app
601
+
602
+
603
+ demo = create_app()
604
+
605
+ if __name__ == "__main__":
606
+ allowed_paths = [str(INPUT_DIR.resolve())] if INPUT_DIR.exists() else None
607
+ demo.launch(
608
+ server_name="0.0.0.0",
609
+ server_port=7860,
610
+ share=False,
611
+ show_error=True,
612
+ allowed_paths=allowed_paths,
613
+ )
614
+ """
615
+ VideoEval Movie-Level 问卷应用(Hugging Face Spaces)
616
+ 仅保留 Movie-Level 评测,并支持方法级别统计输出。
617
+ """
618
+
619
+ import json
620
+ import os
621
+ import threading
622
+ from collections import defaultdict
623
+ from datetime import datetime
624
+ from pathlib import Path
625
+ from typing import Any, Dict, List, Optional, Tuple
626
+
627
+ import gradio as gr
628
+ from huggingface_hub import CommitScheduler, snapshot_download
629
+
630
+ # 路径配置(按用户要求)
631
+ # Spaces 推荐优先读取当前 Space 仓库内文件(app.py 同级)
632
+ APP_DIR = Path(__file__).resolve().parent
633
+ LOCAL_INPUT_DIR = APP_DIR / "user_study_input"
634
+ LOCAL_OUTPUT_DIR = APP_DIR / "user_study_results"
635
+ DATA_INPUT_DIR = Path("/data/user_study_input")
636
+ DATA_OUTPUT_DIR = Path("/data/user_study_results")
637
+ DATA_REPO_ID = os.environ.get("DATA_REPO_ID", "MemDirector/user_study_input")
638
+ RESULTS_REPO_ID = os.environ.get("RESULTS_REPO_ID", "MemDirector/user_study_results")
639
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
640
+ SPACE_MODE = os.environ.get("SPACE_MODE", "repo_first") # repo_first / data_first / hub_only
641
+
642
+ ROOT_DIR = APP_DIR
643
+ INPUT_DIR = LOCAL_INPUT_DIR
644
+ OUTPUT_DIR = LOCAL_OUTPUT_DIR
645
+ STORY_DIR = INPUT_DIR / "clip_movie_story"
646
+ VIDEO_DIR = INPUT_DIR / "video"
647
+
648
+ Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
649
+ scheduler: Optional[CommitScheduler] = None
650
+
651
+
652
+ def _set_paths(input_dir: Path, output_dir: Path) -> None:
653
+ global INPUT_DIR, OUTPUT_DIR, STORY_DIR, VIDEO_DIR, ROOT_DIR
654
+ INPUT_DIR = input_dir
655
+ OUTPUT_DIR = output_dir
656
+ STORY_DIR = INPUT_DIR / "clip_movie_story"
657
+ VIDEO_DIR = INPUT_DIR / "video"
658
+ ROOT_DIR = INPUT_DIR.parent
659
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
660
+
661
+
662
+ def _try_use_local_repo_layout() -> bool:
663
+ # Space 仓库内自带 user_study_input 时,直接读取(最符合“已放上去直接跑”)
664
+ if LOCAL_INPUT_DIR.exists():
665
+ _set_paths(LOCAL_INPUT_DIR, LOCAL_OUTPUT_DIR)
666
+ return True
667
+ return False
668
+
669
+
670
+ def _try_use_data_volume_layout() -> bool:
671
+ # 如果使用 /data 持久卷,则可放在 /data/user_study_input
672
+ if DATA_INPUT_DIR.exists():
673
+ _set_paths(DATA_INPUT_DIR, DATA_OUTPUT_DIR)
674
+ return True
675
+ return False
676
+
677
+
678
+ def _try_download_from_hub() -> bool:
679
+ # 最后兜底:从 dataset repo 下载
680
+ if not DATA_REPO_ID:
681
+ return False
682
+ hub_root = APP_DIR / ".hf_space_cache"
683
+ try:
684
+ snapshot_download(
685
+ repo_id=DATA_REPO_ID,
686
+ repo_type="dataset",
687
+ local_dir=str(hub_root),
688
+ token=HF_TOKEN,
689
+ allow_patterns=[
690
+ "clip_movie_story/**",
691
+ "video/**",
692
+ "user_study_input/**",
693
+ "user_study_results/**",
694
+ ],
695
+ )
696
+ except Exception as e:
697
+ print(f"[INIT] snapshot_download failed: {e}")
698
+ return False
699
+
700
+ # 兼容两种 dataset 结构:
701
+ # A) 仓库根目录直接是 clip_movie_story/ 与 video/
702
+ # B) 仓库里有 user_study_input/ 子目录
703
+ if (hub_root / "clip_movie_story").exists() and (hub_root / "video").exists():
704
+ hub_input = hub_root
705
+ elif (hub_root / "user_study_input").exists():
706
+ hub_input = hub_root / "user_study_input"
707
+ else:
708
+ return False
709
+
710
+ hub_output = hub_root / "user_study_results"
711
+ _set_paths(hub_input, hub_output)
712
+ return True
713
+
714
+
715
+ def init_space_storage() -> None:
716
+ """
717
+ Hugging Face Spaces 规范:
718
+ - 从 dataset repo 拉取 user_study_input 与 user_study_results 到本地 ROOT_DIR
719
+ - 使用 CommitScheduler 持续回写 user_study_results
720
+ """
721
+ global scheduler
722
+
723
+ if SPACE_MODE == "hub_only":
724
+ ok = _try_download_from_hub()
725
+ elif SPACE_MODE == "data_first":
726
+ ok = _try_use_data_volume_layout() or _try_use_local_repo_layout() or _try_download_from_hub()
727
+ else:
728
+ ok = _try_use_local_repo_layout() or _try_use_data_volume_layout() or _try_download_from_hub()
729
+ print(f"[INIT] storage init mode={SPACE_MODE}, success={ok}, input={INPUT_DIR}, output={OUTPUT_DIR}")
730
+
731
+ if RESULTS_REPO_ID:
732
+ try:
733
+ scheduler = CommitScheduler(
734
+ repo_id=RESULTS_REPO_ID,
735
+ repo_type="dataset",
736
+ folder_path=str(OUTPUT_DIR),
737
+ path_in_repo="user_study_results",
738
+ every=3,
739
+ token=HF_TOKEN,
740
+ )
741
+ print(f"[INIT] CommitScheduler enabled: {RESULTS_REPO_ID}")
742
+ except Exception as e:
743
+ print(f"[INIT] CommitScheduler init failed: {e}")
744
+
745
+
746
  init_space_storage()
747
 
748
  # Movie-Level 指标定义