Datasets:
Download code/package_release.py from EgoF0102/SceneBench: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/datasets/EgoF0102/SceneBench/resolve/main/code/package_release.py
- Command line
-
hf download hf://datasets/EgoF0102/SceneBench/code/package_release.py
-
curl -L -o package_release.py https://huggingface.co/datasets/EgoF0102/SceneBench/resolve/main/code/package_release.py
20.3 kB
| import json,hashlib,collections,shutil,datetime,platform | |
| from pathlib import Path | |
| from datasets import Dataset,Features,Value,Sequence,Image as HFImage,load_dataset | |
| from common import read_jsonl,write_json | |
| root=Path('/home/ach18533cl/workspace/SceneBench');release=root/'release';hf=root/'huggingface';hf.mkdir(exist_ok=True);docs=root/'docs';docs.mkdir(exist_ok=True) | |
| cfg=json.loads((root/'config.json').read_text());rows=list(read_jsonl(release/'benchmark.jsonl'));valid=json.loads((release/'validation_report.json').read_text());assert valid['status']=='pass' and valid['items']==len(rows) | |
| cur=json.loads((release/'curation_report.json').read_text());sha=hashlib.sha256((release/'benchmark.jsonl').read_bytes()).hexdigest() | |
| families=['Perception','Relation','Composition','Procedure','CVS','Dynamic'];cn=['感知','关系','组合','流程','CVS','动态'];counts=collections.Counter(r['family'] for r in rows);tc=collections.Counter(r['task'] for r in rows) | |
| task_names=dict(zip(cfg['target_counts'],['器械定位识别','解剖结构定位识别','器械存在性','同类器械计数','器械绝对方位','动作识别','动作主体识别','动作目标识别','器械相对解剖结构方位','解剖结构相对器械方位','解剖结构之间方位','两个动作的有序目标组合','空间筛选器械后查询目标','动作目标的相对方位','两个空间条件的交集','动作与空间条件的交集','两个空间条件下的器械计数','空间筛选目标后查询器械','当前手术阶段','两结构标准评分','胆囊板标准评分','肝胆三角标准评分','整体 CVS 是否达到','器械存在状态变化','动作状态变化','作用目标变化','手术阶段变化','空间关系变化'])) | |
| frozen={'version':cfg['version'],'benchmark_sha256':sha,'items':len(rows),'created_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'curation_before_baseline':True} | |
| write_json(release/'FROZEN.json',frozen) | |
| stats={'items':len(rows),'unique_source_frames':valid['unique_source_frames'],'unique_exported_images':len({p for r in rows for p in r['images']}),'family_counts':dict(counts),'task_counts':dict(tc),'videos':dict(collections.Counter(r['video_id'] for r in rows)),'answer_classes':valid['answer_classes'],'answer_positions':valid['answer_positions'],'cvs':{}} | |
| for t in ['V01','V02','V03','V04']: | |
| rr=[r for r in rows if r['task']==t];stats['cvs'][t]={a:{'questions':sum(r['answer_class']==a for r in rr),'videos':sorted({r['video_id'] for r in rr if r['answer_class']==a}),'segments':len({r['episode_id'] for r in rr if r['answer_class']==a}),'label_sources':dict(collections.Counter(r['query']['label_source'] for r in rr if r['answer_class']==a))} for a in sorted({r['answer_class'] for r in rr})} | |
| write_json(release/'dataset_statistics.json',stats) | |
| lines=[f'# SceneBench v{cfg["version"]}:Benchmark 说明', '',f'本版本共 **{len(rows)} 题、6 层、28 个题型**,全部从原始数据重新生成。仅发布 test 集;没有复用旧版 2300 题,也没有另外划主榜或子榜。', '', '## 数据与输入', '', '固定视频:VID02、VID06、VID14、VID23、VID25、VID50、VID51、VID66、VID79。训练和验证数据应继续使用这些测试视频以外的手术,不能按帧把同一测试视频混入训练。', '',f'共有 {stats["unique_source_frames"]} 个不同的原始 1 fps 帧、{stats["unique_exported_images"]} 个导出图像文件。P/R/C/PR/V 均为单帧;只有 D 为按时间排序的两帧,间隔 3、5、8 或 10 秒。没有要求生成长时序 graph。', '', '问答使用英语。P03、V04 为二选一;V01–V03 保留原生 0/1/2 三级评分,为三选一;其余题型为四选一。每题只有一个可由完整查询确定的正确选项;R 类若同一查询存在多个动作、主体或目标,就不生成该候选。空间关系将横纵方向合成互斥四象限,避免“左”和“上”同时正确。', '', '## 各层数量', '', '| 层 | 目标 | 最终 |', '|---|---:|---:|'] | |
| for f,n in zip(families,cn):lines.append(f'| {n} | {sum(cfg["target_counts"][t] for t in tc if next(r["family"] for r in rows if r["task"]==t)==f)} | {counts[f]} |') | |
| lines+=['',f'候选抽样得到 {cur["initial"]} 题,图像复核剔除 {cur["dropped"]} 题,修正 {cur["point_corrections"]} 个箭头落点。C05、D02、V04 在初次抽样时已有候选容量缺口;进一步复核导致 P01/P02/P04/C04/C06 减少。没有用重复题或放宽 GT 唯一性来补齐目标。', '', '## 每个题型的真实问答示例', '', '下列示例均直接来自本次冻结的 benchmark.jsonl。选项顺序、答案与样本 ID 一致。完整证据见同 ID 的 source_evidence、query、marker 字段。', ''] | |
| for t in cfg['target_counts']: | |
| r=next(r for r in rows if r['task']==t);lines += [f'### {t} · {task_names[t]}({tc[t]} 题)','',f'样本 `{r["id"]}`;来源 `{r["video_id"]}`,1 fps 帧 `{r["frame_ids"]}`。', '',r['question'],'']+[f'- {chr(65+i)}. {a}' for i,a in enumerate(r['options'])]+['',f'正确答案:**{r["answer"]}. {r["answer_text"]}**。',''] | |
| lines += ['## Ground truth 与可追溯性', '', '原始目录为 `/home/ach18533cl/workspace/ori_data`。', '', '- 图像:`CholecT45/data/VIDxx/ffffff.png`。1 fps 帧索引从 0 开始,对应 Cholec80 原始 25 fps 帧号 `25 × f`;对九个视频逐帧验证了该映射。','- 动作与目标:`CholecT45/triplet/VIDxx.txt` 及 `dict/`。R01–R03、动作组合和动态动作使用真实 IVT;排除 null 动作/目标及完整查询多解。','- 阶段与器械存在:` Cholec80_labels/labels/{train,val,test}/...pickle`,目录名开头有一个空格。`Tool_gt=None` 视为缺失,不能当作不存在。','- 空间、类别、实例数:`scene_graph/VIDxx_f.json` 的 `scenes[0]`。保留原始对象、bbox、center 与关系。坐标画布为 430×240。`a in right[b]` 表示 a 在 b 右侧;用坐标和反向边同时验证,不能照 README 中相反方向的文字例子实现。','- CVS:`Cholec80_CVS/cholec80-CVS.xlsx` 的分段评分,并记录原 Excel 行号和标签来源。现有 VQA 文本没有用来改写旧题或替代证据。', '', '图结构中的 bbox 和部分解剖类别来自自动检测/图生成,不等同于逐帧专家金标准。本版本保证答案可由保存的源标注与确定规则重算,并做了图像质量筛选及分层视觉复核;不能声称每条源标注都经外科专家确认。P01/P02/P04/C06 对全部初选样本做视觉筛查,C04/C05/CVS 做按答案分层抽查。复核发现的明显重复检测、错框、模糊目标已剔除。该边界也适用于评测得分的解释。', '', '## Marker 与图像处理', '', 'P01 的黄色 A 框和 P02 的黄色 A 箭头已画入实际导出 JPEG,也已嵌入 Hugging Face 的图像字节。框来自源 bbox;箭头指向源 bbox 内经视觉筛查的落点,18 处作了修正(实际列表见 curation_report.json)。没有把答案类别文字写入图像。', '', '按原图宽高分别从 430×240 映射坐标;最长边最多 1280 像素,JPEG quality 95。没有裁剪、翻转或更改时间顺序。原图路径、输出尺寸和 SHA256 均可追溯。诊断用的多框复核图不作为模型输入。', '', '## 重新抽样规则', '', '先建立所有题型的合格候选,再按题型配额轮转,并优先选择不足的答案类和视频,避免高频、易生成题占满。普通候选扫描步长 2 秒,CVS 在有效域逐秒扫描;动态候选检查两个端点的真实标签。PR01 按已确认的设计排除 Preparation;其余六个阶段各 50 题。源数据确实包含 Preparation,它仍可用于其他适用视觉题,但不作为 PR01 的答案或干扰项。', '', '同视频同题型普通题至少间隔 10 秒,CVS 至少 3 秒。每个原始帧最多用于 2 题;动态两帧端点由该动态题独占。同类动作题每个动作持续事件至多取一次。CVS 每个连续同标签区间每题型最多 15 帧,允许区间内多个代表帧;结合亮度、清晰度和 dHash 去重。最终选项答案位置在每个题型内计数最多相差 1。复核后的语义类别分布不强行补齐,实际分布见 dataset_statistics.json。', '', 'D02 描述的是同一器械类别在同一目标上的端点动作变化;未提供器械实例 tracking ID,所以不把它解释为同一物理实例的连续追踪。动态样本包含稳定与变化情况,每侧最多占目标配额的 60%(目标 80 题时为 48 题)。D02 因变化候选不足最终为 48 稳定 + 23 变化,稳定占实际 71 题的 67.61%;因此不能宣称所有最终题型都满足实际比例 60% 上限。', '', '## CVS 的区间规则与限制', '', '已核对 [Cholec80-CVS 论文](https://www.nature.com/articles/s41597-023-02073-7) 和官方转换脚本:标注区间内所有帧共享区间标签;有效标注域内未覆盖片段默认三项为 0。**不能把最近一次非零标签一直向后填充。** 官方实现本身可在区间内以 5 fps 输出,原来“一段只取一帧”并非数据集要求。', '', '本版本进一步限制在 Calot triangle dissection 阶段且首次 clipping/cutting 之前。区间两端包含在内;多行覆盖且评分冲突的秒被剔除。V01–V03 分别使用原始三级评分;V04 按该数据集规则 `sum(V01,V02,V03) >= 5`,不是要求三项全为 2,也不是独立临床认证。', '', 'V04 的 3 个阳性问题仅来自 VID66 的 661–675 秒这一个阳性事件;V03 的 2 分同样集中于此。V02 的 2 分仅来自 VID51 的两个区间。这些帧增加视角/遮挡覆盖,不能当成多个独立手术或多个独立阳性事件。已把部分 V04 阴性替换为 VID66 相近手术进度的帧;其余阴性也限制在较晚 Calot,减少容易的阶段线索。', '', '| CVS 题型 | 答案类 | 问题数 | 视频数 | 连续标签区间数 |', '|---|---|---:|---:|---:|'] | |
| for t,aa in stats['cvs'].items(): | |
| for a,st in aa.items():lines.append(f'| {t} | {a} | {st["questions"]} | {len(st["videos"])} | {st["segments"]} |') | |
| lines += ['', '整体 CVS 阴性不妨碍生成 V01–V03:它仍然可能只有某些标准达到 1 或 2 分。结果应报告每项每分值表现;只有一个独立阳性事件的 V04 不能支持可靠的跨手术敏感度结论。', '', '## 文件与复现', '', '- `release/benchmark.jsonl`:全部题目、相对图像路径、GT、原始证据和生成查询。','- `release/images/`:最终模型输入图像,包含实际 marker。','- `release/validation_report.json`:逐题重算、唯一性、图像哈希、分集、复用和答案位置检查。','- `release/curation_report.json`:剔除记录、箭头修正、阴性匹配替换和复核范围。','- `huggingface/data/test-*.parquet`:嵌入图像字节的便携数据集,可直接 load_dataset。','- `docs/Benchmark说明_20260922.md`:本说明;评测完成后另写结果分析。','- `evaluation/`:完整请求协议、原始回答、统计与分析。', '',f'随机种子 `{cfg["seed"]}`;版本 `{cfg["version"]}`;冻结 SHA256 `{sha}`。', '', '```bash', '.venv/bin/python generate.py', '.venv/bin/python select_render.py', '.venv/bin/python curate.py', '.venv/bin/python validate.py', '.venv/bin/python package_release.py', '.venv/bin/python evaluate_openrouter.py', '```', '', '复现视觉决策使用 curation.json;不要在已有评测结果后覆盖冻结问题。源数据需另行放在上述 ori_data 路径。依赖见 requirements-lock.txt。', '', '## 发布与许可', '', 'Hugging Face:`EgoF0102/SceneBench`,已于 2026-09-23 经用户确认改为公开仓库,可使用 Hugging Face 网页 Dataset Viewer 逐条浏览。图像和衍生标注遵循源数据的 CC BY-NC-SA 4.0;需保留源数据引用与署名,限非商业用途,衍生共享使用相同许可。引用 Cholec80/EndoNet、CholecT45/Rendezvous、SSG-VQA 与 Cholec80-CVS。'] | |
| (docs/'Benchmark说明_20260922.md').write_text('\n'.join(lines)+'\n') | |
| features=Features({'id':Value('string'),'split':Value('string'),'task':Value('string'),'family':Value('string'),'question':Value('string'),'options':Sequence(Value('string')),'answer':Value('string'),'answer_index':Value('int32'),'answer_text':Value('string'),'answer_class':Value('string'),'images':Sequence(HFImage()),'video_id':Value('string'),'frame_ids':Sequence(Value('int32')),'episode_id':Value('string'),'marker_json':Value('string'),'provenance_json':Value('string')}) | |
| def converted(r): | |
| x={k:r[k] for k in features if k not in ['images','marker_json','provenance_json']};x['images']=[{'bytes':(release/p).read_bytes(),'path':Path(p).name} for p in r['images']];x['marker_json']=json.dumps(r['marker'],ensure_ascii=False);x['provenance_json']=json.dumps({k:r[k] for k in ['candidate_id','query','tags','source_frame_ids','source_evidence','quality_status','image_metadata']},ensure_ascii=False);return x | |
| (hf/'data').mkdir(exist_ok=True) | |
| shards=6 | |
| for i in range(shards): | |
| subset=rows[i*len(rows)//shards:(i+1)*len(rows)//shards];ds=Dataset.from_list([converted(r) for r in subset],features=features);ds.to_parquet(hf/f'data/test-{i:05d}-of-{shards:05d}.parquet') | |
| check=load_dataset('parquet',data_files={'test':str(hf/'data/test-*.parquet')},split='test');assert len(check)==len(rows);assert check[0]['images'][0].width>0;assert len(check[-1]['images'])==2 | |
| for name in ['FROZEN.json','config.json','validation_report.json','curation_report.json','dataset_statistics.json']:shutil.copy(release/name,hf/name) | |
| (hf/'docs').mkdir(exist_ok=True);shutil.copy(docs/'Benchmark说明_20260922.md',hf/'docs') | |
| (hf/'code').mkdir(exist_ok=True) | |
| for name in ['common.py','generate.py','select_render.py','curate.py','curation.json','validate.py','package_release.py','evaluate_openrouter.py','config.json']: | |
| shutil.copy(root/name,hf/'code'/name) | |
| if (root/'requirements-lock.txt').exists():shutil.copy(root/'requirements-lock.txt',hf/'code') | |
| card=f'''--- | |
| license: cc-by-nc-sa-4.0 | |
| task_categories: | |
| - visual-question-answering | |
| language: | |
| - en | |
| tags: | |
| - surgery | |
| - laparoscopic-cholecystectomy | |
| - scene-graph | |
| size_categories: | |
| - 1K<n<10K | |
| configs: | |
| - config_name: default | |
| data_files: | |
| - split: test | |
| path: data/test-*.parquet | |
| --- | |
| # SceneBench v{cfg['version']} | |
| {len(rows)} source-derived multiple-choice questions across 28 task types and six families, generated anew from nine held-out CholecT45 videos. One test benchmark; no training or validation split is distributed. | |
| | Family | Questions | | |
| |---|---:| | |
| '''+''.join(f'| {f} | {counts[f]} |\n' for f in families)+f''' | |
| ## Loading | |
| ```python | |
| from datasets import load_dataset | |
| ds = load_dataset("EgoF0102/SceneBench", split="test") | |
| row = ds[0] | |
| images = row["images"] # List of PIL images; one, or two in chronological order. | |
| print(row["question"], row["options"], row["answer"]) | |
| ``` | |
| Image bytes are embedded in Parquet. Yellow box A / arrow A is already rendered for P01/P02. Do not pass answer fields, provenance, video IDs, timestamps or source graphs to a direct-VQA baseline. Options are presented in stored order. P03/V04 have 2 options, V01–V03 have 3, all others have 4. The answer letter is determined by answer_index. Each question has one source-derived answer. | |
| ## Sources and split | |
| Test videos: VID02, VID06, VID14, VID23, VID25, VID50, VID51, VID66, VID79. All other videos must remain outside this test split when constructing training data. Indices are zero-based 1 fps indices; original Cholec80 frame index is 25 times this index. | |
| - [Cholec80 / EndoNet](https://arxiv.org/abs/1602.03012): phase and tool presence. | |
| - [CholecT45 / Rendezvous](https://github.com/CAMMA-public/cholect45): images and instrument-verb-target annotations. Cite Nwoye et al., *Rendezvous: Attention Mechanisms for the Recognition of Surgical Action Triplets in Endoscopic Videos*, Medical Image Analysis, 2022. | |
| - [SSG-VQA](https://arxiv.org/abs/2312.10251): supplied scene graphs, object categories, boxes and spatial relations; cite Yuan et al., *Advancing Surgical VQA with Scene Graph Knowledge*, IJCARS 2024 (preprint 2023). See local source provenance for exact records. | |
| - [Cholec80-CVS](https://www.nature.com/articles/s41597-023-02073-7): segmented CVS criterion scores. Follow the original paper and source repositories for full author attribution and citations. | |
| ## Generation and quality | |
| Queries are deterministic functions of source labels. Ambiguous action queries are rejected. Spatial directions use 430×240 bbox-center geometry, a 5% axis margin, and matching positive/inverse relation edges. Graph-detected tool categories are cross-checked against source tool-presence labels. Per-task answer/video balancing, spacing and image deduplication limit repetition; actual counts and distributions are in dataset_statistics.json. Source frames are reused at most twice, and Dynamic endpoints are exclusive to their one pair. Dynamic questions compare two endpoint states, not tracked physical instrument identities. | |
| {cur['dropped']} of {cur['initial']} selected candidates were removed during visual screening; {cur['point_corrections']} anatomy arrow tips were adjusted within the source box. P01/P02/P04/C06 received screening of all selected items; C04/C05/CVS received answer-stratified screening. This was Codex visual screening, not expert surgical adjudication. The source scene graphs contain model-generated detections and can contain residual errors. **This release is source-consistent, not a claim of independently expert-verified gold for every image.** Review scope and exclusions are public in curation_report.json. No baseline predictions were used for curation. | |
| ## CVS interpretation | |
| Only Calot triangle dissection before the first clipping/cutting transition is eligible. Annotated intervals include both endpoints. Uncovered segments inside the valid domain default to (0,0,0); labels are not forward-filled. Conflicting overlapping scores are excluded. V01–V03 use the native 0/1/2 criterion scores; V04 follows the source rule total score >=5. This is a dataset convention, not independent clinical certification. Multiple spaced/deduplicated frames per interval are allowed. | |
| V04 has only three positive frames, all from one event in VID66 (661–675 seconds). V03 score 2 has the same event concentration. V02 score 2 occurs in two VID51 intervals. Multiple frames do not create independent clinical events. Some V04 negatives are matched to VID66 and late Calot. Results for rare criteria must be interpreted at video/event level. | |
| ## Evaluation | |
| The baseline protocol uses `qwen/qwen3-vl-32b-instruct` through OpenRouter, temperature 0, one call per question, only exported images + question/options, returning a single option letter. It is a zero-shot base-Instruct direct-VQA baseline, without SFT/RL or predicted-graph conditioning. Results and a separate Chinese analysis document are added after complete evaluation. Total micro accuracy and descriptive family/task/class breakdowns refer to this same benchmark. | |
| ## License and reproducibility | |
| CC BY-NC-SA 4.0. Images and source-derived annotations retain source attribution, non-commercial restrictions and share-alike terms. See [the license](https://creativecommons.org/licenses/by-nc-sa/4.0/) and original source publications. Export processing adds markers, resizes longest edge to at most 1280 and encodes JPEG quality 95; no crop or flip. | |
| Full Chinese task definitions, real examples, source mapping, sampling and limitations: [Benchmark说明](docs/Benchmark说明_20260922.md). Generator, fixed curation decisions and validator: code/. Credentials and raw unused source data are not included. | |
| Frozen benchmark SHA256: `{sha}`. | |
| ''' | |
| (hf/'README.md').write_text(card);(hf/'LICENSE').write_text('Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International\nhttps://creativecommons.org/licenses/by-nc-sa/4.0/legalcode\nSource images and annotations retain their respective original authors and attribution.\n') | |
| write_json(root/'work/package_report.json',dict(status='pass',parquet_rows=len(check),parquet_shards=shards,benchmark_sha256=sha,embedded_images_verified=True)) | |
| print(json.dumps({'items':len(rows),'families':dict(counts),'sha256':sha,'parquet_check':'pass'}),flush=True) | |