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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
demo = create_app()
|
| 508 |
|
| 509 |
if __name__ == "__main__":
|
|
|
|
| 504 |
return app
|
| 505 |
|
| 506 |
|
| 507 |
+
demo = create_app()
|
| 508 |
+
|
| 509 |
+
if __name__ == "__main__":
|
| 510 |
+
allowed_paths = [str(INPUT_DIR.resolve())] if INPUT_DIR.exists() else None
|
| 511 |
+
demo.launch(
|
| 512 |
+
server_name="0.0.0.0",
|
| 513 |
+
server_port=7860,
|
| 514 |
+
share=False,
|
| 515 |
+
show_error=True,
|
| 516 |
+
allowed_paths=allowed_paths,
|
| 517 |
+
)
|
| 518 |
+
"""
|
| 519 |
+
VideoEval Movie-Level 问卷应用(Hugging Face Spaces)
|
| 520 |
+
仅保留 Movie-Level 评测,并支持方法级别统计输出。
|
| 521 |
+
"""
|
| 522 |
+
|
| 523 |
+
import json
|
| 524 |
+
import os
|
| 525 |
+
import threading
|
| 526 |
+
from collections import defaultdict
|
| 527 |
+
from datetime import datetime
|
| 528 |
+
from pathlib import Path
|
| 529 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 530 |
+
|
| 531 |
+
import gradio as gr
|
| 532 |
+
from huggingface_hub import CommitScheduler, snapshot_download
|
| 533 |
+
|
| 534 |
+
# 路径配置(按用户要求)
|
| 535 |
+
# Spaces 推荐优先读取当前 Space 仓库内文件(app.py 同级)
|
| 536 |
+
APP_DIR = Path(__file__).resolve().parent
|
| 537 |
+
LOCAL_INPUT_DIR = APP_DIR / "user_study_input"
|
| 538 |
+
LOCAL_OUTPUT_DIR = APP_DIR / "user_study_results"
|
| 539 |
+
DATA_INPUT_DIR = Path("/data/user_study_input")
|
| 540 |
+
DATA_OUTPUT_DIR = Path("/data/user_study_results")
|
| 541 |
+
DATA_REPO_ID = os.environ.get("DATA_REPO_ID", "MemDirector/user_study_input")
|
| 542 |
+
RESULTS_REPO_ID = os.environ.get("RESULTS_REPO_ID", "MemDirector/user_study_results")
|
| 543 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
| 544 |
+
SPACE_MODE = os.environ.get("SPACE_MODE", "repo_first") # repo_first / data_first / hub_only
|
| 545 |
+
|
| 546 |
+
ROOT_DIR = APP_DIR
|
| 547 |
+
INPUT_DIR = LOCAL_INPUT_DIR
|
| 548 |
+
OUTPUT_DIR = LOCAL_OUTPUT_DIR
|
| 549 |
+
STORY_DIR = INPUT_DIR / "clip_movie_story"
|
| 550 |
+
VIDEO_DIR = INPUT_DIR / "video"
|
| 551 |
+
|
| 552 |
+
Path(OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
|
| 553 |
+
scheduler: Optional[CommitScheduler] = None
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def _set_paths(input_dir: Path, output_dir: Path) -> None:
|
| 557 |
+
global INPUT_DIR, OUTPUT_DIR, STORY_DIR, VIDEO_DIR, ROOT_DIR
|
| 558 |
+
INPUT_DIR = input_dir
|
| 559 |
+
OUTPUT_DIR = output_dir
|
| 560 |
+
STORY_DIR = INPUT_DIR / "clip_movie_story"
|
| 561 |
+
VIDEO_DIR = INPUT_DIR / "video"
|
| 562 |
+
ROOT_DIR = INPUT_DIR.parent
|
| 563 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def _try_use_local_repo_layout() -> bool:
|
| 567 |
+
# Space 仓库内自带 user_study_input 时,直接读取(最符合“已放上去直接跑”)
|
| 568 |
+
if LOCAL_INPUT_DIR.exists():
|
| 569 |
+
_set_paths(LOCAL_INPUT_DIR, LOCAL_OUTPUT_DIR)
|
| 570 |
+
return True
|
| 571 |
+
return False
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def _try_use_data_volume_layout() -> bool:
|
| 575 |
+
# 如果使用 /data 持久卷,则可放在 /data/user_study_input
|
| 576 |
+
if DATA_INPUT_DIR.exists():
|
| 577 |
+
_set_paths(DATA_INPUT_DIR, DATA_OUTPUT_DIR)
|
| 578 |
+
return True
|
| 579 |
+
return False
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _try_download_from_hub() -> bool:
|
| 583 |
+
# 最后兜底:从 dataset repo 下载
|
| 584 |
+
if not DATA_REPO_ID:
|
| 585 |
+
return False
|
| 586 |
+
hub_root = APP_DIR / ".hf_space_cache"
|
| 587 |
+
try:
|
| 588 |
+
snapshot_download(
|
| 589 |
+
repo_id=DATA_REPO_ID,
|
| 590 |
+
repo_type="dataset",
|
| 591 |
+
local_dir=str(hub_root),
|
| 592 |
+
token=HF_TOKEN,
|
| 593 |
+
allow_patterns=[
|
| 594 |
+
"clip_movie_story/**",
|
| 595 |
+
"video/**",
|
| 596 |
+
"user_study_input/**",
|
| 597 |
+
"user_study_results/**",
|
| 598 |
+
],
|
| 599 |
+
)
|
| 600 |
+
except Exception as e:
|
| 601 |
+
print(f"[INIT] snapshot_download failed: {e}")
|
| 602 |
+
return False
|
| 603 |
+
|
| 604 |
+
# 兼容两种 dataset 结构:
|
| 605 |
+
# A) 仓库根目录直接是 clip_movie_story/ 与 video/
|
| 606 |
+
# B) 仓库里有 user_study_input/ 子目录
|
| 607 |
+
if (hub_root / "clip_movie_story").exists() and (hub_root / "video").exists():
|
| 608 |
+
hub_input = hub_root
|
| 609 |
+
elif (hub_root / "user_study_input").exists():
|
| 610 |
+
hub_input = hub_root / "user_study_input"
|
| 611 |
+
else:
|
| 612 |
+
return False
|
| 613 |
+
|
| 614 |
+
hub_output = hub_root / "user_study_results"
|
| 615 |
+
_set_paths(hub_input, hub_output)
|
| 616 |
+
return True
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def init_space_storage() -> None:
|
| 620 |
+
"""
|
| 621 |
+
Hugging Face Spaces 规范:
|
| 622 |
+
- 从 dataset repo 拉取 user_study_input 与 user_study_results 到本地 ROOT_DIR
|
| 623 |
+
- 使用 CommitScheduler 持续回写 user_study_results
|
| 624 |
+
"""
|
| 625 |
+
global scheduler
|
| 626 |
+
|
| 627 |
+
if SPACE_MODE == "hub_only":
|
| 628 |
+
ok = _try_download_from_hub()
|
| 629 |
+
elif SPACE_MODE == "data_first":
|
| 630 |
+
ok = _try_use_data_volume_layout() or _try_use_local_repo_layout() or _try_download_from_hub()
|
| 631 |
+
else:
|
| 632 |
+
ok = _try_use_local_repo_layout() or _try_use_data_volume_layout() or _try_download_from_hub()
|
| 633 |
+
print(f"[INIT] storage init mode={SPACE_MODE}, success={ok}, input={INPUT_DIR}, output={OUTPUT_DIR}")
|
| 634 |
+
|
| 635 |
+
if RESULTS_REPO_ID:
|
| 636 |
+
try:
|
| 637 |
+
scheduler = CommitScheduler(
|
| 638 |
+
repo_id=RESULTS_REPO_ID,
|
| 639 |
+
repo_type="dataset",
|
| 640 |
+
folder_path=str(OUTPUT_DIR),
|
| 641 |
+
path_in_repo="user_study_results",
|
| 642 |
+
every=3,
|
| 643 |
+
token=HF_TOKEN,
|
| 644 |
+
)
|
| 645 |
+
print(f"[INIT] CommitScheduler enabled: {RESULTS_REPO_ID}")
|
| 646 |
+
except Exception as e:
|
| 647 |
+
print(f"[INIT] CommitScheduler init failed: {e}")
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
init_space_storage()
|
| 651 |
+
|
| 652 |
+
# Movie-Level 指标定义
|
| 653 |
+
MOVIE_CRITERIA: List[Tuple[str, str, str]] = [
|
| 654 |
+
("SF", "Script Faithfulness (剧本忠实度)", "生成的视觉内容与原始剧本描述的吻合程度。"),
|
| 655 |
+
("NC", "Narrative Coherence (叙事连贯性)", "镜头间情节发展的逻辑性,确保故事表达清晰、不破碎。"),
|
| 656 |
+
("VQ", "Visual Quality (视觉质量)", "画面的清晰度、噪点控制、光影效果等基础图像质量。"),
|
| 657 |
+
("CC", "Character Consistency (角色一致性)", "同一角色在不同镜头、不同角度下的外貌、服装及特征的稳定性。"),
|
| 658 |
+
("PLC", "Physical Law Compliance (物理规律符合度)", "运动、重力、碰撞等是否符合现实物理逻辑,是否存在严重 AI 幻觉。"),
|
| 659 |
+
("V_AQ", "Voice/Audio Quality (语音/音频质量)", "配音、背景音乐和音效的清晰度、自然度及技术品质。"),
|
| 660 |
+
("CT", "Cinematic Techniques (电影技巧)", "镜头运动、景深控制及构图的专业性。"),
|
| 661 |
+
("AVR", "Audio-Visual Richness (视听丰富度)", "画面细节精细度以及音频层次(音效、氛围音)的丰富程度。"),
|
| 662 |
+
("NP", "Narrative Pacing (叙事节奏)", "镜头剪辑长短切换是否契合故事情节张力需求。"),
|
| 663 |
+
("VAC", "Video-Audio Coordination (视听协调性)", "画面动作与音效、音乐卡点的同步率。"),
|
| 664 |
+
("CD", "Compelling Degree (引人入胜程度)", "吸引注意力并引发情感共鸣或沉浸感的能力。"),
|
| 665 |
+
("OQ", "Overall Quality (整体质量)", "对生成视频作为“电影作品”的综合观感评分。"),
|
| 666 |
+
]
|
| 667 |
+
|
| 668 |
+
BASE_METRIC_KEYS = [k for k, _, _ in MOVIE_CRITERIA]
|
| 669 |
+
SAVE_LOCK = threading.Lock()
|
| 670 |
+
|
| 671 |
+
CUSTOM_CSS = """
|
| 672 |
+
.gradio-container {
|
| 673 |
+
max-width: 1360px !important;
|
| 674 |
+
background:
|
| 675 |
+
radial-gradient(circle at 8% 12%, rgba(80, 130, 255, 0.16) 0%, rgba(80, 130, 255, 0) 28%),
|
| 676 |
+
radial-gradient(circle at 92% 18%, rgba(103, 223, 255, 0.12) 0%, rgba(103, 223, 255, 0) 30%),
|
| 677 |
+
linear-gradient(180deg, #0a1221 0%, #0b1426 50%, #0b1324 100%);
|
| 678 |
+
padding-bottom: 18px;
|
| 679 |
+
}
|
| 680 |
+
#hero {
|
| 681 |
+
border: 1px solid #365087;
|
| 682 |
+
border-radius: 16px;
|
| 683 |
+
padding: 22px 24px;
|
| 684 |
+
background: linear-gradient(130deg, #101f3f 0%, #1a2f5d 55%, #153a70 100%);
|
| 685 |
+
box-shadow: 0 18px 45px rgba(5, 9, 22, 0.45);
|
| 686 |
+
margin-bottom: 12px;
|
| 687 |
+
}
|
| 688 |
+
#hero h1 {
|
| 689 |
+
margin: 0;
|
| 690 |
+
font-size: 1.75rem;
|
| 691 |
+
letter-spacing: 0.3px;
|
| 692 |
+
}
|
| 693 |
+
#hero p {
|
| 694 |
+
margin: 8px 0 0 0;
|
| 695 |
+
color: #d8e4ff;
|
| 696 |
+
}
|
| 697 |
+
#hero .hero-badge {
|
| 698 |
+
display: inline-flex;
|
| 699 |
+
gap: 8px;
|
| 700 |
+
align-items: center;
|
| 701 |
+
margin-top: 14px;
|
| 702 |
+
padding: 6px 12px;
|
| 703 |
+
border-radius: 999px;
|
| 704 |
+
border: 1px solid rgba(189, 217, 255, 0.4);
|
| 705 |
+
background: rgba(12, 24, 51, 0.52);
|
| 706 |
+
color: #d8e8ff;
|
| 707 |
+
font-size: 12px;
|
| 708 |
+
}
|
| 709 |
+
.topbar {
|
| 710 |
+
margin: 12px 0 16px 0;
|
| 711 |
+
display: grid;
|
| 712 |
+
grid-template-columns: repeat(3, minmax(120px, 1fr));
|
| 713 |
+
gap: 12px;
|
| 714 |
+
}
|
| 715 |
+
.metric-card {
|
| 716 |
+
border: 1px solid #2f456f;
|
| 717 |
+
border-radius: 12px;
|
| 718 |
+
padding: 12px 14px;
|
| 719 |
+
background: linear-gradient(180deg, #12203b 0%, #101b33 100%);
|
| 720 |
+
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
| 721 |
+
}
|
| 722 |
+
.metric-label {
|
| 723 |
+
font-size: 12px;
|
| 724 |
+
color: #a8bae4;
|
| 725 |
+
margin-bottom: 4px;
|
| 726 |
+
}
|
| 727 |
+
.metric-value {
|
| 728 |
+
color: #ecf2ff;
|
| 729 |
+
font-size: 16px;
|
| 730 |
+
font-weight: 650;
|
| 731 |
+
}
|
| 732 |
+
.panel {
|
| 733 |
+
border: 1px solid #2a3e65 !important;
|
| 734 |
+
border-radius: 14px !important;
|
| 735 |
+
padding: 14px !important;
|
| 736 |
+
background: linear-gradient(180deg, #101b31 0%, #0f1a2d 100%) !important;
|
| 737 |
+
box-shadow: 0 10px 25px rgba(5, 10, 24, 0.28);
|
| 738 |
+
}
|
| 739 |
+
.section-title {
|
| 740 |
+
margin: 0 0 10px 0;
|
| 741 |
+
font-size: 1.03rem;
|
| 742 |
+
font-weight: 620;
|
| 743 |
+
color: #dfe7ff;
|
| 744 |
+
}
|
| 745 |
+
.hint {
|
| 746 |
+
color: #9dafd6;
|
| 747 |
+
font-size: 0.9rem;
|
| 748 |
+
}
|
| 749 |
+
.toolbar-btn {
|
| 750 |
+
min-height: 42px !important;
|
| 751 |
+
border-radius: 10px !important;
|
| 752 |
+
}
|
| 753 |
+
.gr-button-primary {
|
| 754 |
+
background: linear-gradient(180deg, #5a84ff 0%, #446ff0 100%) !important;
|
| 755 |
+
border: 1px solid #8fa9ff !important;
|
| 756 |
+
box-shadow: 0 8px 22px rgba(61, 103, 234, 0.35) !important;
|
| 757 |
+
}
|
| 758 |
+
.status-box {
|
| 759 |
+
border: 1px dashed #4b6394;
|
| 760 |
+
border-radius: 10px;
|
| 761 |
+
padding: 9px 11px;
|
| 762 |
+
background: #0c1529;
|
| 763 |
+
}
|
| 764 |
+
.soft-input textarea,
|
| 765 |
+
.soft-input input,
|
| 766 |
+
.soft-input .wrap {
|
| 767 |
+
border-radius: 10px !important;
|
| 768 |
+
}
|
| 769 |
+
.gr-accordion {
|
| 770 |
+
border-radius: 12px !important;
|
| 771 |
+
border-color: #2d4169 !important;
|
| 772 |
+
}
|
| 773 |
+
"""
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def _safe_read_text(path: Path) -> str:
|
| 777 |
+
if not path.exists():
|
| 778 |
+
return ""
|
| 779 |
+
return path.read_text(encoding="utf-8-sig").strip()
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def load_dataset_index() -> List[Dict[str, Any]]:
|
| 783 |
+
"""扫描输入目录,构建可评测样本列表(每个方法-故事仅保留1个视频)。"""
|
| 784 |
+
stories = {p.stem: _safe_read_text(p) for p in sorted(STORY_DIR.glob("*.txt"))}
|
| 785 |
+
samples: List[Dict[str, Any]] = []
|
| 786 |
+
|
| 787 |
+
if not VIDEO_DIR.exists():
|
| 788 |
+
return samples
|
| 789 |
+
|
| 790 |
+
for method_dir in sorted([d for d in VIDEO_DIR.iterdir() if d.is_dir()]):
|
| 791 |
+
method = method_dir.name
|
| 792 |
+
for story_dir in sorted([d for d in method_dir.iterdir() if d.is_dir()]):
|
| 793 |
+
story_name = story_dir.name
|
| 794 |
+
# 每个方法-故事只评一次:如果有多个视频,默认取排序后第一个
|
| 795 |
+
video_candidates = sorted(story_dir.glob("*.mp4"))
|
| 796 |
+
if not video_candidates:
|
| 797 |
+
continue
|
| 798 |
+
video_path = video_candidates[0]
|
| 799 |
+
sample_id = f"{method}__{story_name}__{video_path.stem}"
|
| 800 |
+
samples.append(
|
| 801 |
+
{
|
| 802 |
+
"sample_id": sample_id,
|
| 803 |
+
"method": method,
|
| 804 |
+
"story_name": story_name,
|
| 805 |
+
"video_name": video_path.name,
|
| 806 |
+
"video_path": str(video_path.resolve()),
|
| 807 |
+
"story_text": stories.get(story_name, ""),
|
| 808 |
+
}
|
| 809 |
+
)
|
| 810 |
+
return samples
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def load_evaluated_method_story_pairs() -> set:
|
| 814 |
+
"""从结果目录读取已评估的 (method, story_name) 组合。"""
|
| 815 |
+
evaluated = set()
|
| 816 |
+
raw_root = OUTPUT_DIR / "raw_results"
|
| 817 |
+
if not raw_root.exists():
|
| 818 |
+
return evaluated
|
| 819 |
+
|
| 820 |
+
for fp in raw_root.rglob("*.json"):
|
| 821 |
+
try:
|
| 822 |
+
with open(fp, "r", encoding="utf-8-sig") as f:
|
| 823 |
+
data = json.load(f)
|
| 824 |
+
except Exception:
|
| 825 |
+
continue
|
| 826 |
+
sample = data.get("sample", {})
|
| 827 |
+
method = sample.get("method")
|
| 828 |
+
story_name = sample.get("story_name")
|
| 829 |
+
if method and story_name:
|
| 830 |
+
evaluated.add((method, story_name))
|
| 831 |
+
return evaluated
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def build_pending_samples() -> List[Dict[str, Any]]:
|
| 835 |
+
"""构建待评估样本池,并分配匿名ID。"""
|
| 836 |
+
all_samples = load_dataset_index()
|
| 837 |
+
evaluated_pairs = load_evaluated_method_story_pairs()
|
| 838 |
+
pending = [
|
| 839 |
+
s for s in all_samples
|
| 840 |
+
if (s["method"], s["story_name"]) not in evaluated_pairs
|
| 841 |
+
]
|
| 842 |
+
for i, sample in enumerate(pending, start=1):
|
| 843 |
+
sample["anon_id"] = f"id_{i:03d}"
|
| 844 |
+
return pending
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def build_data_diagnostics(samples: List[Dict[str, Any]]) -> str:
|
| 848 |
+
return (
|
| 849 |
+
f"**SPACE_MODE**: `{SPACE_MODE}` \n"
|
| 850 |
+
f"**DATA_REPO_ID**: `{DATA_REPO_ID}` \n"
|
| 851 |
+
f"**RESULTS_REPO_ID**: `{RESULTS_REPO_ID}` \n"
|
| 852 |
+
f"**ROOT_DIR**: `{ROOT_DIR}` \n"
|
| 853 |
+
f"**INPUT_DIR exists**: `{INPUT_DIR.exists()}` \n"
|
| 854 |
+
f"**STORY_DIR exists**: `{STORY_DIR.exists()}` \n"
|
| 855 |
+
f"**VIDEO_DIR exists**: `{VIDEO_DIR.exists()}` \n"
|
| 856 |
+
f"**Pending samples**: `{len(samples)}`"
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
def compute_derived(scores: Dict[str, float]) -> Dict[str, float]:
|
| 861 |
+
"""计算 CL / CRh / AVG。"""
|
| 862 |
+
cl = (
|
| 863 |
+
(scores["SF"] + scores["NC"] + scores["VQ"] + scores["CC"] + scores["PLC"]) / 5.0
|
| 864 |
+
+ 0.5 * ((scores["CT"] + scores["AVR"]) / 2.0)
|
| 865 |
+
)
|
| 866 |
+
crh = (
|
| 867 |
+
(scores["V_AQ"] + scores["NP"] + scores["VAC"] + scores["CD"] + scores["OQ"]) / 5.0
|
| 868 |
+
+ 0.5 * ((scores["CT"] + scores["AVR"]) / 2.0)
|
| 869 |
+
)
|
| 870 |
+
avg = sum(scores[k] for k in BASE_METRIC_KEYS) / len(BASE_METRIC_KEYS)
|
| 871 |
+
return {"CL": cl, "CRh": crh, "AVG": avg}
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def save_single_result(sample: Dict[str, Any], evaluator_id: str, scores: Dict[str, int], reasons: Dict[str, str], summary: str) -> Path:
|
| 875 |
+
"""保存单个问卷结果。"""
|
| 876 |
+
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 877 |
+
result_dir = OUTPUT_DIR / "raw_results" / sample["method"] / sample["story_name"]
|
| 878 |
+
result_dir.mkdir(parents=True, exist_ok=True)
|
| 879 |
+
out_path = result_dir / f"{sample['video_name'].replace('.mp4', '')}_{evaluator_id}_{ts}.json"
|
| 880 |
+
|
| 881 |
+
score_float = {k: float(v) for k, v in scores.items()}
|
| 882 |
+
derived = compute_derived(score_float)
|
| 883 |
+
|
| 884 |
+
payload = {
|
| 885 |
+
"timestamp": datetime.now().isoformat(),
|
| 886 |
+
"evaluator_id": evaluator_id,
|
| 887 |
+
"sample": sample,
|
| 888 |
+
"scores": scores,
|
| 889 |
+
"reasons": reasons,
|
| 890 |
+
"summary": summary,
|
| 891 |
+
"derived": derived,
|
| 892 |
+
}
|
| 893 |
+
with open(out_path, "w", encoding="utf-8") as f:
|
| 894 |
+
json.dump(payload, f, ensure_ascii=False, indent=2)
|
| 895 |
+
return out_path
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def recompute_method_aggregates() -> Path:
|
| 899 |
+
"""
|
| 900 |
+
统计每个方法各维度均分,并输出 method_aggregates.json。
|
| 901 |
+
同时给出 CL/CRh/AVG 的方法均值。
|
| 902 |
+
"""
|
| 903 |
+
raw_root = OUTPUT_DIR / "raw_results"
|
| 904 |
+
method_scores: Dict[str, Dict[str, List[float]]] = defaultdict(lambda: defaultdict(list))
|
| 905 |
+
method_count: Dict[str, int] = defaultdict(int)
|
| 906 |
+
|
| 907 |
+
if raw_root.exists():
|
| 908 |
+
for fp in raw_root.rglob("*.json"):
|
| 909 |
+
with open(fp, "r", encoding="utf-8-sig") as f:
|
| 910 |
+
data = json.load(f)
|
| 911 |
+
method = data.get("sample", {}).get("method", "UNKNOWN")
|
| 912 |
+
scores = data.get("scores", {})
|
| 913 |
+
if not all(k in scores for k in BASE_METRIC_KEYS):
|
| 914 |
+
continue
|
| 915 |
+
method_count[method] += 1
|
| 916 |
+
for k in BASE_METRIC_KEYS:
|
| 917 |
+
method_scores[method][k].append(float(scores[k]))
|
| 918 |
+
|
| 919 |
+
# 衍生指标也参与方法均值统计
|
| 920 |
+
derived = compute_derived({k: float(scores[k]) for k in BASE_METRIC_KEYS})
|
| 921 |
+
for d_key, d_val in derived.items():
|
| 922 |
+
method_scores[method][d_key].append(float(d_val))
|
| 923 |
+
|
| 924 |
+
agg = {
|
| 925 |
+
"updated_at": datetime.now().isoformat(),
|
| 926 |
+
"metric_keys": BASE_METRIC_KEYS,
|
| 927 |
+
"derived_keys": ["CL", "CRh", "AVG"],
|
| 928 |
+
"methods": {},
|
| 929 |
+
}
|
| 930 |
+
for method in sorted(method_scores.keys()):
|
| 931 |
+
metric_avg = {}
|
| 932 |
+
for key, vals in method_scores[method].items():
|
| 933 |
+
metric_avg[key] = round(sum(vals) / len(vals), 4) if vals else None
|
| 934 |
+
agg["methods"][method] = {
|
| 935 |
+
"num_submissions": method_count[method],
|
| 936 |
+
"avg_scores": metric_avg,
|
| 937 |
+
}
|
| 938 |
+
|
| 939 |
+
out_path = OUTPUT_DIR / "method_aggregates.json"
|
| 940 |
+
with open(out_path, "w", encoding="utf-8") as f:
|
| 941 |
+
json.dump(agg, f, ensure_ascii=False, indent=2)
|
| 942 |
+
return out_path
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
def build_sample_brief(sample: Dict[str, Any], index: int, total: int) -> str:
|
| 946 |
+
story = sample.get("story_text") or "(未找到对应 story 文本,请检查 clip_movie_story 下是否有同名 txt)"
|
| 947 |
+
return (
|
| 948 |
+
f"### 当前匿名样本 {index + 1}/{total}\n"
|
| 949 |
+
f"- **Sample ID**: `{sample['anon_id']}`\n\n"
|
| 950 |
+
f"### Story Description\n{story}"
|
| 951 |
+
)
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def create_app():
|
| 955 |
+
samples = build_pending_samples()
|
| 956 |
+
sample_map = {s["anon_id"]: s for s in samples}
|
| 957 |
+
|
| 958 |
+
with gr.Blocks(
|
| 959 |
+
title="VideoEval Movie-Level Evaluation",
|
| 960 |
+
css=CUSTOM_CSS,
|
| 961 |
+
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="indigo", neutral_hue="slate"),
|
| 962 |
+
) as app:
|
| 963 |
+
gr.HTML(
|
| 964 |
+
f"""
|
| 965 |
+
<div id="hero">
|
| 966 |
+
<h1>VideoEval · Movie-Level Evaluation</h1>
|
| 967 |
+
<p>统一电影级评测问卷,支持方法级均分统计(含 CL / CRh / AVG)</p>
|
| 968 |
+
<div class="hero-badge">HF Space Ready · Gradio Blocks · Clean Review Flow</div>
|
| 969 |
+
</div>
|
| 970 |
+
<div class="topbar">
|
| 971 |
+
<div class="metric-card">
|
| 972 |
+
<div class="metric-label">Pending Samples</div>
|
| 973 |
+
<div class="metric-value">{len(samples)}</div>
|
| 974 |
+
</div>
|
| 975 |
+
<div class="metric-card">
|
| 976 |
+
<div class="metric-label">Evaluation Scope</div>
|
| 977 |
+
<div class="metric-value">Movie-Level</div>
|
| 978 |
+
</div>
|
| 979 |
+
<div class="metric-card">
|
| 980 |
+
<div class="metric-label">Scoring Standard</div>
|
| 981 |
+
<div class="metric-value">12 Metrics · 1~5</div>
|
| 982 |
+
</div>
|
| 983 |
+
</div>
|
| 984 |
+
"""
|
| 985 |
+
)
|
| 986 |
+
gr.Markdown(
|
| 987 |
+
f"<span class='hint'>输入目录:`{INPUT_DIR}` | 输出目录:`{OUTPUT_DIR}`</span>",
|
| 988 |
+
)
|
| 989 |
+
with gr.Accordion("系统诊断信息(展开查看)", open=False):
|
| 990 |
+
gr.Markdown(build_data_diagnostics(samples))
|
| 991 |
+
|
| 992 |
+
current_idx = gr.State(0)
|
| 993 |
+
evaluator_state = gr.State("anonymous")
|
| 994 |
+
|
| 995 |
+
with gr.Row():
|
| 996 |
+
with gr.Column(scale=4, elem_classes=["panel"]):
|
| 997 |
+
gr.Markdown("<div class='section-title'>1) 评测员与样本</div>")
|
| 998 |
+
with gr.Row():
|
| 999 |
+
evaluator_input = gr.Textbox(label="Evaluator ID", value="anonymous", elem_classes=["soft-input"])
|
| 1000 |
+
sample_dropdown = gr.Dropdown(
|
| 1001 |
+
label="选择评测样本(匿名)",
|
| 1002 |
+
choices=[s["anon_id"] for s in samples],
|
| 1003 |
+
value=samples[0]["anon_id"] if samples else None,
|
| 1004 |
+
interactive=True,
|
| 1005 |
+
elem_classes=["soft-input"],
|
| 1006 |
+
)
|
| 1007 |
+
with gr.Row():
|
| 1008 |
+
prev_btn = gr.Button("← Previous", elem_classes=["toolbar-btn"])
|
| 1009 |
+
next_btn = gr.Button("Next →", elem_classes=["toolbar-btn"])
|
| 1010 |
+
submit_btn = gr.Button("提交当前评分并统计", variant="primary", elem_classes=["toolbar-btn"])
|
| 1011 |
+
status = gr.Markdown("<div class='status-box'>等待提交</div>")
|
| 1012 |
+
with gr.Column(scale=8, elem_classes=["panel"]):
|
| 1013 |
+
gr.Markdown("<div class='section-title'>2) 视频与剧情</div>")
|
| 1014 |
+
movie_video = gr.Video(label="Movie Video", value=samples[0]["video_path"] if samples else None, height=460)
|
| 1015 |
+
sample_info = gr.Markdown("无可用样本" if not samples else build_sample_brief(samples[0], 0, len(samples)))
|
| 1016 |
+
|
| 1017 |
+
gr.Markdown("## 3) Movie-Level 指标评分(1-5)")
|
| 1018 |
+
gr.Markdown("<span class='hint'>先给分,再填写可选理由。未打分无法提交。</span>")
|
| 1019 |
+
|
| 1020 |
+
score_widgets: Dict[str, gr.Radio] = {}
|
| 1021 |
+
reason_widgets: Dict[str, gr.Textbox] = {}
|
| 1022 |
+
metric_groups = {
|
| 1023 |
+
"I. 叙事与剧本 (NS)": ["SF", "NC"],
|
| 1024 |
+
"II. 视听与技术 (AT)": ["VQ", "CC", "PLC", "V_AQ"],
|
| 1025 |
+
"III. 美学与表现力 (AE)": ["CT", "AVR"],
|
| 1026 |
+
"IV. 节奏与流动性 (RF)": ["NP", "VAC"],
|
| 1027 |
+
"V. 情感与参与度 (EE)": ["CD"],
|
| 1028 |
+
"VI. 整体体验 (OE)": ["OQ"],
|
| 1029 |
+
}
|
| 1030 |
+
criteria_map = {k: (name, desc) for k, name, desc in MOVIE_CRITERIA}
|
| 1031 |
+
|
| 1032 |
+
for section_title, keys in metric_groups.items():
|
| 1033 |
+
with gr.Accordion(section_title, open=True):
|
| 1034 |
+
for key in keys:
|
| 1035 |
+
name, desc = criteria_map[key]
|
| 1036 |
+
with gr.Group(elem_classes=["panel"]):
|
| 1037 |
+
gr.Markdown(f"**{key} · {name}**")
|
| 1038 |
+
gr.Markdown(f"<span class='hint'>{desc}</span>")
|
| 1039 |
+
with gr.Row():
|
| 1040 |
+
score_widgets[key] = gr.Radio(choices=[1, 2, 3, 4, 5], label=f"{key} Score", scale=1, elem_classes=["soft-input"])
|
| 1041 |
+
reason_widgets[key] = gr.Textbox(label=f"{key} Reason(可选)", lines=2, placeholder="补充评分依据", scale=2, elem_classes=["soft-input"])
|
| 1042 |
+
|
| 1043 |
+
final_summary = gr.Textbox(label="Final Summary(可选)", lines=4, placeholder="总结该视频的主要优缺点", elem_classes=["soft-input"])
|
| 1044 |
+
|
| 1045 |
+
def _sync_sample_from_dropdown(anon_id: str) -> Tuple[str, str, int]:
|
| 1046 |
+
if not anon_id or anon_id not in sample_map:
|
| 1047 |
+
return None, "未找到样本", 0
|
| 1048 |
+
idx = next(i for i, s in enumerate(samples) if s["anon_id"] == anon_id)
|
| 1049 |
+
sample = samples[idx]
|
| 1050 |
+
return sample["video_path"], build_sample_brief(sample, idx, len(samples)), idx
|
| 1051 |
+
|
| 1052 |
+
def _go_prev(idx: int) -> Tuple[str, str, str, int]:
|
| 1053 |
+
if not samples:
|
| 1054 |
+
return None, "无可用样本", None, 0
|
| 1055 |
+
idx = max(0, idx - 1)
|
| 1056 |
+
sample = samples[idx]
|
| 1057 |
+
return sample["video_path"], build_sample_brief(sample, idx, len(samples)), sample["anon_id"], idx
|
| 1058 |
+
|
| 1059 |
+
def _go_next(idx: int) -> Tuple[str, str, str, int]:
|
| 1060 |
+
if not samples:
|
| 1061 |
+
return None, "无可用样本", None, 0
|
| 1062 |
+
idx = min(len(samples) - 1, idx + 1)
|
| 1063 |
+
sample = samples[idx]
|
| 1064 |
+
return sample["video_path"], build_sample_brief(sample, idx, len(samples)), sample["anon_id"], idx
|
| 1065 |
+
|
| 1066 |
+
def _submit(evaluator_id: str, anon_id: str, summary: str, *score_reason_vals):
|
| 1067 |
+
if not samples:
|
| 1068 |
+
return "❌ 没有可提交样本。"
|
| 1069 |
+
if not anon_id or anon_id not in sample_map:
|
| 1070 |
+
return "❌ 请先选择样本。"
|
| 1071 |
+
sample = sample_map[anon_id]
|
| 1072 |
+
evaluator_id = (evaluator_id or "anonymous").strip() or "anonymous"
|
| 1073 |
+
|
| 1074 |
+
# 防重复:方法-故事只允许评估一次
|
| 1075 |
+
evaluated_pairs = load_evaluated_method_story_pairs()
|
| 1076 |
+
if (sample["method"], sample["story_name"]) in evaluated_pairs:
|
| 1077 |
+
return "⚠️ 该方法-故事已经被评估过一次,请选择其他匿名样本。"
|
| 1078 |
+
|
| 1079 |
+
scores: Dict[str, int] = {}
|
| 1080 |
+
reasons: Dict[str, str] = {}
|
| 1081 |
+
for i, key in enumerate(BASE_METRIC_KEYS):
|
| 1082 |
+
score = score_reason_vals[i * 2]
|
| 1083 |
+
reason = score_reason_vals[i * 2 + 1]
|
| 1084 |
+
if score is None:
|
| 1085 |
+
return f"❌ 请为 `{key}` 打分。"
|
| 1086 |
+
scores[key] = int(score)
|
| 1087 |
+
reasons[key] = (reason or "").strip()
|
| 1088 |
+
|
| 1089 |
+
with SAVE_LOCK:
|
| 1090 |
+
single_path = save_single_result(sample, evaluator_id, scores, reasons, summary or "")
|
| 1091 |
+
agg_path = recompute_method_aggregates()
|
| 1092 |
+
|
| 1093 |
+
return f"✅ 已保存: `{single_path}`\n\n✅ 已更新方法统计: `{agg_path}`"
|
| 1094 |
+
|
| 1095 |
+
sample_dropdown.change(
|
| 1096 |
+
_sync_sample_from_dropdown,
|
| 1097 |
+
inputs=[sample_dropdown],
|
| 1098 |
+
outputs=[movie_video, sample_info, current_idx],
|
| 1099 |
+
)
|
| 1100 |
+
prev_btn.click(_go_prev, inputs=[current_idx], outputs=[movie_video, sample_info, sample_dropdown, current_idx])
|
| 1101 |
+
next_btn.click(_go_next, inputs=[current_idx], outputs=[movie_video, sample_info, sample_dropdown, current_idx])
|
| 1102 |
+
|
| 1103 |
+
submit_inputs = [evaluator_input, sample_dropdown, final_summary]
|
| 1104 |
+
for key in BASE_METRIC_KEYS:
|
| 1105 |
+
submit_inputs.append(score_widgets[key])
|
| 1106 |
+
submit_inputs.append(reason_widgets[key])
|
| 1107 |
+
submit_btn.click(_submit, inputs=submit_inputs, outputs=[status])
|
| 1108 |
+
|
| 1109 |
+
app.load(lambda x: x, inputs=[evaluator_input], outputs=[evaluator_state])
|
| 1110 |
+
|
| 1111 |
+
return app
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
demo = create_app()
|
| 1115 |
|
| 1116 |
if __name__ == "__main__":
|