Upload folder using huggingface_hub
Browse files
low_high_cost/RUNBOOK.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# low_high_cost 继续训练数据流水线
|
| 2 |
+
|
| 3 |
+
目标:把 `datas/low_high_cost/extracted/final_output/prompt.jsonl` 转成现有
|
| 4 |
+
`scripts/training/edit-model/train.py` 已经支持的 `shared_records` 格式。
|
| 5 |
+
|
| 6 |
+
当前推荐方向是 `low_to_high`:
|
| 7 |
+
|
| 8 |
+
- `vace_video/control` = `low_cost_video`
|
| 9 |
+
- `video/target` = `high_cost_video`
|
| 10 |
+
- prompt = low -> high 的增强指令
|
| 11 |
+
|
| 12 |
+
注意:原始 `high2low_prompt` 是反方向,不能直接当 low -> high prompt 使用。
|
| 13 |
+
|
| 14 |
+
## 0. 检查原始数据
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
cd /mnt/si002961ale4/default/lgy/shiying/low-high-new
|
| 18 |
+
|
| 19 |
+
python3 - <<'PY'
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
p = Path("datas/low_high_cost/extracted/final_output/prompt.jsonl")
|
| 22 |
+
print("prompt exists", p.exists())
|
| 23 |
+
print("rows", sum(1 for _ in p.open(encoding="utf-8")) if p.exists() else 0)
|
| 24 |
+
print("high dirs", len(list(Path("datas/low_high_cost/extracted/final_output/high_cost_video").glob("*"))))
|
| 25 |
+
print("low dirs", len(list(Path("datas/low_high_cost/extracted/final_output/low_cost_video").glob("*"))))
|
| 26 |
+
PY
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## 1. 不用 API,先用固定 low -> high 模板生成 records
|
| 30 |
+
|
| 31 |
+
这个版本最快,可以直接 smoke training。
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
python3 datas/low_high_cost/build_low_high_cost_records.py \
|
| 35 |
+
--repo-root . \
|
| 36 |
+
--root datas/low_high_cost/extracted/final_output \
|
| 37 |
+
--output out/edit_model_face_stage1/shared_records.low_high_cost.template_low2high.jsonl \
|
| 38 |
+
--direction low_to_high \
|
| 39 |
+
--prompt-source template \
|
| 40 |
+
--require-files
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
验证:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
python3 datas/low_high_cost/validate_records.py \
|
| 47 |
+
--repo-root . \
|
| 48 |
+
--records out/edit_model_face_stage1/shared_records.low_high_cost.template_low2high.jsonl \
|
| 49 |
+
--show 2 \
|
| 50 |
+
--fail-on-missing
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
## 2. 可选:用 API 反写 prompt
|
| 54 |
+
|
| 55 |
+
不要把 key 写进文件。远程运行时用环境变量:
|
| 56 |
+
|
| 57 |
+
```bash
|
| 58 |
+
export LOW_HIGH_COST_API_KEY="sk-..."
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
### 2.1 文本反写模式
|
| 62 |
+
|
| 63 |
+
只使用原始 `high2low_prompt`,速度快、成本低,但不会看视频内容。
|
| 64 |
+
|
| 65 |
+
先 dry-run:
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
python3 datas/low_high_cost/invert_high2low_prompts_api.py \
|
| 69 |
+
--input datas/low_high_cost/extracted/final_output/prompt.jsonl \
|
| 70 |
+
--output datas/low_high_cost/outputs/low2high_prompts_api.jsonl \
|
| 71 |
+
--model gpt-4o \
|
| 72 |
+
--limit 3 \
|
| 73 |
+
--dry-run
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
少量真实调用测试:
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
python3 datas/low_high_cost/invert_high2low_prompts_api.py \
|
| 80 |
+
--input datas/low_high_cost/extracted/final_output/prompt.jsonl \
|
| 81 |
+
--output datas/low_high_cost/outputs/low2high_prompts_api.jsonl \
|
| 82 |
+
--base-url http://35.220.164.252:3888/v1 \
|
| 83 |
+
--api-key-env LOW_HIGH_COST_API_KEY \
|
| 84 |
+
--model gpt-4o \
|
| 85 |
+
--limit 3 \
|
| 86 |
+
--input-cost-per-1m 0 \
|
| 87 |
+
--output-cost-per-1m 0
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
`input-cost-per-1m` 和 `output-cost-per-1m` 可以按模型广场价格填;脚本会在每条和最后 summary 打印 token 与估算费用。
|
| 91 |
+
|
| 92 |
+
批量跑时去掉 `--limit`。脚本支持 resume:已有成功 `id` 会跳过。
|
| 93 |
+
|
| 94 |
+
### 2.2 视频感知反写模式
|
| 95 |
+
|
| 96 |
+
正式 prompt 更推荐这个模式:同时给模型 low/high 视频抽帧和原始 `high2low_prompt`,让 VLM 根据真实视觉差异生成 `low2high_prompt`。
|
| 97 |
+
|
| 98 |
+
少量 dry-run:
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
python3 datas/low_high_cost/invert_high2low_prompts_api.py \
|
| 102 |
+
--input datas/low_high_cost/extracted/final_output/prompt.jsonl \
|
| 103 |
+
--output datas/low_high_cost/outputs/low2high_prompts_video_api.jsonl \
|
| 104 |
+
--repo-root . \
|
| 105 |
+
--root datas/low_high_cost/extracted/final_output \
|
| 106 |
+
--model gpt-4o \
|
| 107 |
+
--limit 3 \
|
| 108 |
+
--use-video \
|
| 109 |
+
--max-frames 3 \
|
| 110 |
+
--resize 448 \
|
| 111 |
+
--dry-run
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
少量真实调用:
|
| 115 |
+
|
| 116 |
+
```bash
|
| 117 |
+
python3 datas/low_high_cost/invert_high2low_prompts_api.py \
|
| 118 |
+
--input datas/low_high_cost/extracted/final_output/prompt.jsonl \
|
| 119 |
+
--output datas/low_high_cost/outputs/low2high_prompts_video_api.jsonl \
|
| 120 |
+
--repo-root . \
|
| 121 |
+
--root datas/low_high_cost/extracted/final_output \
|
| 122 |
+
--base-url http://35.220.164.252:3888/v1 \
|
| 123 |
+
--api-key-env LOW_HIGH_COST_API_KEY \
|
| 124 |
+
--model gpt-4o \
|
| 125 |
+
--limit 3 \
|
| 126 |
+
--use-video \
|
| 127 |
+
--max-frames 3 \
|
| 128 |
+
--resize 448 \
|
| 129 |
+
--input-cost-per-1m 0 \
|
| 130 |
+
--output-cost-per-1m 0
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
本地 VLM 部署时,把 `--base-url` 和 `--model` 换成模型服务对应值即可。对 10 万条全量数据,建议先用 `--max-frames 2` 或 `3` 做成本和速度测试。
|
| 134 |
+
|
| 135 |
+
### 2.3 不部署服务,直接加载本地 VLM
|
| 136 |
+
|
| 137 |
+
如果不想启动 vLLM/OpenAI-compatible 服务,可以直接用 `transformers` 加载本地模型。这个方式启动慢一些,但 smoke test 最简单。
|
| 138 |
+
|
| 139 |
+
```bash
|
| 140 |
+
python3 datas/low_high_cost/invert_high2low_prompts_api.py \
|
| 141 |
+
--backend local \
|
| 142 |
+
--input datas/low_high_cost/extracted/final_output/prompt.jsonl \
|
| 143 |
+
--output datas/low_high_cost/outputs/low2high_prompts_video_qwen3vl32b_local_smoke3.jsonl \
|
| 144 |
+
--repo-root . \
|
| 145 |
+
--root datas/low_high_cost/extracted/final_output \
|
| 146 |
+
--model Qwen3-VL-32B-Instruct \
|
| 147 |
+
--local-model-dir models/Qwen3-VL-32B-Instruct \
|
| 148 |
+
--local-dtype bfloat16 \
|
| 149 |
+
--local-device-map auto \
|
| 150 |
+
--limit 3 \
|
| 151 |
+
--use-video \
|
| 152 |
+
--max-frames 3 \
|
| 153 |
+
--resize 448 \
|
| 154 |
+
--max-new-tokens 512
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
如果显存不够,��把 `--max-frames 3` 改成 `--max-frames 2`。如果本机 `transformers` 版本不支持 Qwen3-VL,需要先升级 transformers/qwen-vl-utils,或者改用 vLLM 服务方式。
|
| 158 |
+
|
| 159 |
+
## 3. 用 API 反写结果生成 records
|
| 160 |
+
|
| 161 |
+
```bash
|
| 162 |
+
python3 datas/low_high_cost/build_low_high_cost_records.py \
|
| 163 |
+
--repo-root . \
|
| 164 |
+
--root datas/low_high_cost/extracted/final_output \
|
| 165 |
+
--output out/edit_model_face_stage1/shared_records.low_high_cost.api_low2high.jsonl \
|
| 166 |
+
--direction low_to_high \
|
| 167 |
+
--prompt-source auto \
|
| 168 |
+
--inverted-prompts datas/low_high_cost/outputs/low2high_prompts_api.jsonl \
|
| 169 |
+
--require-files
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
`--prompt-source auto` 会优先使用 API 的 `low2high_prompt`;某条没有 API 结果时回退到固定模板。
|
| 173 |
+
|
| 174 |
+
## 4. 继续训练命令
|
| 175 |
+
|
| 176 |
+
先用不启动真实训练的方式生成 `metadata.train.csv` 和 `metadata.val.csv`:
|
| 177 |
+
|
| 178 |
+
```bash
|
| 179 |
+
cd /mnt/si002961ale4/default/lgy/shiying/low-high-new
|
| 180 |
+
|
| 181 |
+
export PYTHONPATH=src
|
| 182 |
+
|
| 183 |
+
/opt/conda/bin/python3 scripts/training/edit-model/train.py \
|
| 184 |
+
--dataset out/edit_model_face_stage1/shared_records.low_high_cost.api_low2high.jsonl \
|
| 185 |
+
--output-dir out/edit_model_face_stage1/base_sft_low_high_cost_8gpu_full \
|
| 186 |
+
--stage base_sft \
|
| 187 |
+
--recipe official_vace14b_continue \
|
| 188 |
+
--launcher accelerate \
|
| 189 |
+
--python-executable /opt/conda/bin/python3 \
|
| 190 |
+
--accelerate-num-processes 8 \
|
| 191 |
+
--accelerate-config-file scripts/training/edit-model/accelerate_config_8gpu_bf16.yaml \
|
| 192 |
+
--models-root models \
|
| 193 |
+
--dataset-num-workers 1 \
|
| 194 |
+
--save-steps 5000 \
|
| 195 |
+
--model-init-device cpu
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
检查:
|
| 199 |
+
|
| 200 |
+
```bash
|
| 201 |
+
head -5 out/edit_model_face_stage1/base_sft_low_high_cost_8gpu_full/real_train/metadata.train.csv
|
| 202 |
+
head -5 out/edit_model_face_stage1/base_sft_low_high_cost_8gpu_full/real_train/metadata.val.csv
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
确认无误后加 `--run-real-train`。
|
| 206 |
+
|
| 207 |
+
latent text / vace hint / vace context 版本只需要沿用原来的训练参数,把 `--dataset` 和 `--output-dir` 换掉。
|
low_high_cost/build_low_high_cost_records.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert low_high_cost prompt.jsonl into edit-model shared_records JSONL."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
DEFAULT_ROOT = Path("datas/low_high_cost/extracted/final_output")
|
| 13 |
+
DEFAULT_TEMPLATE_PROMPT = (
|
| 14 |
+
"Transform this low-cost video into its high-cost cinematic version. "
|
| 15 |
+
"Restore richer production design, refined lighting, color grading, materials, wardrobe, "
|
| 16 |
+
"environment detail, and cinematic atmosphere while preserving the original layout, identity, "
|
| 17 |
+
"actions, camera motion, and scene semantics."
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 22 |
+
rows: list[dict[str, Any]] = []
|
| 23 |
+
if not path.exists():
|
| 24 |
+
raise FileNotFoundError(path)
|
| 25 |
+
for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
| 26 |
+
if not line.strip():
|
| 27 |
+
continue
|
| 28 |
+
try:
|
| 29 |
+
rows.append(json.loads(line))
|
| 30 |
+
except json.JSONDecodeError as exc:
|
| 31 |
+
raise ValueError(f"{path}:{line_no}: invalid JSON: {exc}") from exc
|
| 32 |
+
return rows
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def load_inversions(path: Path | None) -> dict[str, str]:
|
| 36 |
+
if path is None:
|
| 37 |
+
return {}
|
| 38 |
+
out: dict[str, str] = {}
|
| 39 |
+
for row in read_jsonl(path):
|
| 40 |
+
sample_id = str(row.get("id", "") or row.get("source_sample_id", "") or "").strip()
|
| 41 |
+
prompt = str(row.get("low2high_prompt", "") or "").strip()
|
| 42 |
+
if sample_id and prompt and not row.get("api_error"):
|
| 43 |
+
out[sample_id] = prompt
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def make_rel(path: Path, repo_root: Path) -> str:
|
| 48 |
+
try:
|
| 49 |
+
return path.resolve().relative_to(repo_root.resolve()).as_posix()
|
| 50 |
+
except ValueError:
|
| 51 |
+
return path.as_posix()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def scene_group(row: dict[str, Any]) -> str:
|
| 55 |
+
rel = str(row.get("high_cost_path", "") or row.get("low_cost_path", "") or "")
|
| 56 |
+
if "/" in rel:
|
| 57 |
+
return rel.split("/")[-2]
|
| 58 |
+
sample_id = str(row.get("id", "") or "")
|
| 59 |
+
return sample_id.split("-Scene-")[0] if "-Scene-" in sample_id else sample_id.split("_part")[0]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def choose_prompt(
|
| 63 |
+
row: dict[str, Any],
|
| 64 |
+
*,
|
| 65 |
+
direction: str,
|
| 66 |
+
prompt_source: str,
|
| 67 |
+
inversions: dict[str, str],
|
| 68 |
+
template_prompt: str,
|
| 69 |
+
) -> tuple[str, str]:
|
| 70 |
+
sample_id = str(row.get("id", "") or "").strip()
|
| 71 |
+
high2low_prompt = str(row.get("high2low_prompt", "") or "").strip()
|
| 72 |
+
|
| 73 |
+
if direction == "high_to_low":
|
| 74 |
+
if prompt_source in {"original", "auto"}:
|
| 75 |
+
return high2low_prompt, "high2low_prompt"
|
| 76 |
+
if prompt_source == "template":
|
| 77 |
+
return (
|
| 78 |
+
"Transform this high-cost cinematic video into a lower-cost everyday version while "
|
| 79 |
+
"preserving layout, identity, actions, and camera motion.",
|
| 80 |
+
"template",
|
| 81 |
+
)
|
| 82 |
+
return "", "empty"
|
| 83 |
+
|
| 84 |
+
if prompt_source in {"inverted", "auto"} and sample_id in inversions:
|
| 85 |
+
return inversions[sample_id], "low2high_prompt_api"
|
| 86 |
+
if prompt_source in {"template", "auto"}:
|
| 87 |
+
return template_prompt, "template"
|
| 88 |
+
if prompt_source == "original":
|
| 89 |
+
return high2low_prompt, "high2low_prompt_wrong_direction"
|
| 90 |
+
return "", "empty"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def build_record(
|
| 94 |
+
row: dict[str, Any],
|
| 95 |
+
*,
|
| 96 |
+
root: Path,
|
| 97 |
+
repo_root: Path,
|
| 98 |
+
direction: str,
|
| 99 |
+
prompt_source: str,
|
| 100 |
+
inversions: dict[str, str],
|
| 101 |
+
template_prompt: str,
|
| 102 |
+
) -> dict[str, Any]:
|
| 103 |
+
sample_id = str(row.get("id", "") or "").strip()
|
| 104 |
+
high_abs = root / str(row.get("high_cost_path", "") or "")
|
| 105 |
+
low_abs = root / str(row.get("low_cost_path", "") or "")
|
| 106 |
+
|
| 107 |
+
if direction == "low_to_high":
|
| 108 |
+
low_video_path = make_rel(low_abs, repo_root)
|
| 109 |
+
high_video_path = make_rel(high_abs, repo_root)
|
| 110 |
+
else:
|
| 111 |
+
low_video_path = make_rel(high_abs, repo_root)
|
| 112 |
+
high_video_path = make_rel(low_abs, repo_root)
|
| 113 |
+
|
| 114 |
+
prompt, prompt_source_used = choose_prompt(
|
| 115 |
+
row,
|
| 116 |
+
direction=direction,
|
| 117 |
+
prompt_source=prompt_source,
|
| 118 |
+
inversions=inversions,
|
| 119 |
+
template_prompt=template_prompt,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
group = scene_group(row)
|
| 123 |
+
return {
|
| 124 |
+
"sample_id": f"low_high_cost__{direction}__{sample_id}",
|
| 125 |
+
"source_dataset": "low_high_cost",
|
| 126 |
+
"source_type": "low_high_cost_pair",
|
| 127 |
+
"source_sample_id": sample_id,
|
| 128 |
+
"source_group_id": group,
|
| 129 |
+
"direction": direction,
|
| 130 |
+
"low_video_path": low_video_path,
|
| 131 |
+
"high_video_path": high_video_path,
|
| 132 |
+
"low_video_exists": (repo_root / low_video_path).exists() if not Path(low_video_path).is_absolute() else Path(low_video_path).exists(),
|
| 133 |
+
"high_video_exists": (repo_root / high_video_path).exists() if not Path(high_video_path).is_absolute() else Path(high_video_path).exists(),
|
| 134 |
+
"raw_prompt": prompt,
|
| 135 |
+
"normalized_prompt": prompt,
|
| 136 |
+
"compiled_edit_prompt": prompt,
|
| 137 |
+
"prompt_source": prompt_source_used,
|
| 138 |
+
"high2low_prompt_original": str(row.get("high2low_prompt", "") or ""),
|
| 139 |
+
"high_cost_path_original": str(row.get("high_cost_path", "") or ""),
|
| 140 |
+
"low_cost_path_original": str(row.get("low_cost_path", "") or ""),
|
| 141 |
+
"reference_image_path": "",
|
| 142 |
+
"scene_archetype": {"archetype_id": group, "scene_hint": group},
|
| 143 |
+
"style_family": "low_high_cost",
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 148 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 149 |
+
with path.open("w", encoding="utf-8") as f:
|
| 150 |
+
for row in rows:
|
| 151 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def main() -> None:
|
| 155 |
+
parser = argparse.ArgumentParser()
|
| 156 |
+
parser.add_argument("--repo-root", type=Path, default=Path("."))
|
| 157 |
+
parser.add_argument("--root", type=Path, default=DEFAULT_ROOT)
|
| 158 |
+
parser.add_argument("--prompt-jsonl", type=Path, default=None)
|
| 159 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 160 |
+
parser.add_argument("--direction", choices=["low_to_high", "high_to_low"], default="low_to_high")
|
| 161 |
+
parser.add_argument("--prompt-source", choices=["auto", "template", "inverted", "original", "empty"], default="auto")
|
| 162 |
+
parser.add_argument("--inverted-prompts", type=Path, default=None)
|
| 163 |
+
parser.add_argument("--template-prompt", default=DEFAULT_TEMPLATE_PROMPT)
|
| 164 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 165 |
+
parser.add_argument("--require-files", action="store_true")
|
| 166 |
+
args = parser.parse_args()
|
| 167 |
+
|
| 168 |
+
prompt_jsonl = args.prompt_jsonl or (args.root / "prompt.jsonl")
|
| 169 |
+
source_rows = read_jsonl(prompt_jsonl)
|
| 170 |
+
if args.limit:
|
| 171 |
+
source_rows = source_rows[: args.limit]
|
| 172 |
+
|
| 173 |
+
inversions = load_inversions(args.inverted_prompts)
|
| 174 |
+
records = [
|
| 175 |
+
build_record(
|
| 176 |
+
row,
|
| 177 |
+
root=args.root,
|
| 178 |
+
repo_root=args.repo_root,
|
| 179 |
+
direction=args.direction,
|
| 180 |
+
prompt_source=args.prompt_source,
|
| 181 |
+
inversions=inversions,
|
| 182 |
+
template_prompt=args.template_prompt,
|
| 183 |
+
)
|
| 184 |
+
for row in source_rows
|
| 185 |
+
]
|
| 186 |
+
if args.require_files:
|
| 187 |
+
records = [r for r in records if r["low_video_exists"] and r["high_video_exists"]]
|
| 188 |
+
|
| 189 |
+
write_jsonl(args.output, records)
|
| 190 |
+
summary = {
|
| 191 |
+
"source": str(prompt_jsonl),
|
| 192 |
+
"output": str(args.output),
|
| 193 |
+
"direction": args.direction,
|
| 194 |
+
"prompt_source": args.prompt_source,
|
| 195 |
+
"source_rows": len(source_rows),
|
| 196 |
+
"written_records": len(records),
|
| 197 |
+
"missing_low": sum(not r["low_video_exists"] for r in records),
|
| 198 |
+
"missing_high": sum(not r["high_video_exists"] for r in records),
|
| 199 |
+
"empty_prompt": sum(not str(r.get("raw_prompt", "")).strip() for r in records),
|
| 200 |
+
"inverted_prompts_loaded": len(inversions),
|
| 201 |
+
}
|
| 202 |
+
args.output.with_suffix(args.output.suffix + ".summary.json").write_text(
|
| 203 |
+
json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
|
| 204 |
+
encoding="utf-8",
|
| 205 |
+
)
|
| 206 |
+
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
if __name__ == "__main__":
|
| 210 |
+
main()
|
low_high_cost/extracted/final_output/README.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Low-High Cost Video Dataset
|
| 2 |
+
|
| 3 |
+
这是一个用于视频生成/转换研究的数据集,包含**高成本(high-cost)**和**低成本(low-cost)**视频的配对数据。
|
| 4 |
+
|
| 5 |
+
## 数据概述
|
| 6 |
+
|
| 7 |
+
| 统计项 | 数量 |
|
| 8 |
+
|--------|------|
|
| 9 |
+
| 视频场景组数量 | 447 组 |
|
| 10 |
+
| 视频片段总数 | 102,881 对 |
|
| 11 |
+
| 标注文件 | 1 个 (prompt.jsonl) |
|
| 12 |
+
|
| 13 |
+
## 目录结构
|
| 14 |
+
|
| 15 |
+
```
|
| 16 |
+
final_output/
|
| 17 |
+
├── prompt.jsonl # 标注文件(所有视频对的元数据)
|
| 18 |
+
├── high_cost_video/ # 高成本视频(高质量/高保真版本)
|
| 19 |
+
│ ├── 10-o/
|
| 20 |
+
│ │ ├── 10-Scene-0016_part1.mp4
|
| 21 |
+
│ │ ├── 10-Scene-0019_part1.mp4
|
| 22 |
+
│ │ └── ...
|
| 23 |
+
│ ├── 11-o/
|
| 24 |
+
│ ├── 12-o/
|
| 25 |
+
│ └── ...
|
| 26 |
+
└── low_cost_video/ # 低成本视频(低质量/简化版本)
|
| 27 |
+
├── 10-o/
|
| 28 |
+
│ ├── 10-Scene-0016_part1.mp4
|
| 29 |
+
│ ├── 10-Scene-0019_part1.mp4
|
| 30 |
+
│ └── ...
|
| 31 |
+
├── 11-o/
|
| 32 |
+
└── ...
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## 文件命名规则
|
| 36 |
+
|
| 37 |
+
### 目录命名
|
| 38 |
+
- 格式:`{数字}[-序号]-o`
|
| 39 |
+
- 示例:`10-o`, `11-o`, `22_1-o`, `22_2-o`
|
| 40 |
+
- 说明:同一组编号(如 `22_*`)的视频可能来自同一来源的不同片段
|
| 41 |
+
|
| 42 |
+
### 视频文件命名
|
| 43 |
+
- 格式:`{组编号}-Scene-{场景编号}_part{分段编号}.mp4`
|
| 44 |
+
- 示例:`10-Scene-0016_part1.mp4`
|
| 45 |
+
- 说明:
|
| 46 |
+
- `part1` / `part2` / `part3` 等表示同一场景的连续分段
|
| 47 |
+
- 高成本和低成本版本**共享相同的命名**,方便配对
|
| 48 |
+
|
| 49 |
+
## prompt.jsonl 格式
|
| 50 |
+
|
| 51 |
+
每行是一个独立的 JSON 对象,表示一对视频的标注信息:
|
| 52 |
+
|
| 53 |
+
```json
|
| 54 |
+
{
|
| 55 |
+
"id": "10-Scene-0016_part1",
|
| 56 |
+
"high_cost_path": "high_cost_video/10-o/10-Scene-0016_part1.mp4",
|
| 57 |
+
"low_cost_path": "low_cost_video/10-o/10-Scene-0016_part1.mp4",
|
| 58 |
+
"high2low_prompt": "1. Remove or replace the white hat...\n2. Replace the sparkly headband..."
|
| 59 |
+
}
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### 字段说明
|
| 63 |
+
|
| 64 |
+
| 字段 | 类型 | 描述 |
|
| 65 |
+
|------|------|------|
|
| 66 |
+
| `id` | string | 视频片段的唯一标识符 |
|
| 67 |
+
| `high_cost_path` | string | 高成本视频的相对路径 |
|
| 68 |
+
| `low_cost_path` | string | 低成本视频的相对路径 |
|
| 69 |
+
| `high2low_prompt` | string | 将高质量视频转换为低质量版本的详细指令 |
|
| 70 |
+
|
| 71 |
+
## 数据用途
|
| 72 |
+
|
| 73 |
+
此数据集适用于以下研究场景:
|
| 74 |
+
|
| 75 |
+
1. **视频质量转换**:训练模型学习如何将高保真视频转换为低质量版本
|
| 76 |
+
2. **风格迁移**:学习从精致风格到简约日常风格的转换
|
| 77 |
+
3. **视频增强**:反向工程——从低质量恢复高质量
|
| 78 |
+
4. **对比学习**:研究高/低质量视频对之间的特征差异
|
| 79 |
+
|
| 80 |
+
## 使用示例
|
| 81 |
+
|
| 82 |
+
```python
|
| 83 |
+
import json
|
| 84 |
+
|
| 85 |
+
# 读取标注
|
| 86 |
+
with open("prompt.jsonl", "r") as f:
|
| 87 |
+
for line in f:
|
| 88 |
+
data = json.loads(line)
|
| 89 |
+
print(f"ID: {data['id']}")
|
| 90 |
+
print(f"High Cost: {data['high_cost_path']}")
|
| 91 |
+
print(f"Low Cost: {data['low_cost_path']}")
|
| 92 |
+
print(f"Prompt: {data['high2low_prompt'][:100]}...")
|
| 93 |
+
break # 只展示第一条
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
## 注意事项
|
| 97 |
+
|
| 98 |
+
- 高成本视频和低成本视频**一一对应**,文件名前缀完全一致
|
| 99 |
+
- `high2low_prompt` 是将高成本视频转换为低成本视频的操作指令列表
|
| 100 |
+
- 视频内容可能涉及人物穿着、场景复杂度、光照效果等多维度的质量差异
|
| 101 |
+
|
low_high_cost/extracted/final_output/prompt.jsonl
ADDED
|
File without changes
|
low_high_cost/invert_high2low_prompts_api.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Rewrite high->low prompts into low->high prompts with API or a local VLM."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import base64
|
| 8 |
+
import io
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
SYSTEM_PROMPT = """You rewrite video editing instructions.
|
| 18 |
+
The input describes how to turn a high-cost/high-production video into a low-cost/simplified video.
|
| 19 |
+
Rewrite it into the reverse direction: low-cost video -> high-cost cinematic video.
|
| 20 |
+
Return strict JSON only."""
|
| 21 |
+
|
| 22 |
+
VIDEO_SYSTEM_PROMPT = """You are a video-edit prompt planner for low-cost to high-cost cinematic enhancement.
|
| 23 |
+
You compare sampled frames from a low-cost video and its paired high-cost video, then write a training prompt.
|
| 24 |
+
Return strict JSON only."""
|
| 25 |
+
|
| 26 |
+
USER_TEMPLATE = """Sample id: {sample_id}
|
| 27 |
+
|
| 28 |
+
Original high-to-low instruction:
|
| 29 |
+
{high2low_prompt}
|
| 30 |
+
|
| 31 |
+
Write a concise low-to-high instruction for training a video edit model.
|
| 32 |
+
Requirements:
|
| 33 |
+
- Preserve the original layout, identity, camera motion, timing, and scene semantics.
|
| 34 |
+
- Ask for high-cost cinematic improvement: production design, lighting, color grading, materials, wardrobe, background detail, atmosphere, and visual polish.
|
| 35 |
+
- Do not mention that this is a reverse rewrite.
|
| 36 |
+
- Do not ask to change the story into unrelated content.
|
| 37 |
+
- Output JSON with exactly these keys:
|
| 38 |
+
- low2high_prompt: string
|
| 39 |
+
- transformation_tags: array of short strings
|
| 40 |
+
- confidence: number from 0 to 1
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
VIDEO_USER_TEMPLATE = """Sample id: {sample_id}
|
| 44 |
+
|
| 45 |
+
We have a paired video edit dataset:
|
| 46 |
+
- LOW frames: ordinary / low-cost version used as source/control video.
|
| 47 |
+
- HIGH frames: cinematic / high-cost target video, often with visual effects, unusual appearance, period/fantasy/scifi styling, richer costume, grander setting, better lighting, color grading, materials, atmosphere, and production design.
|
| 48 |
+
|
| 49 |
+
Original high-to-low instruction used to create the pair:
|
| 50 |
+
{high2low_prompt}
|
| 51 |
+
|
| 52 |
+
Task:
|
| 53 |
+
Write the corresponding low-to-high edit instruction for training a video edit model.
|
| 54 |
+
|
| 55 |
+
Requirements:
|
| 56 |
+
- Use both LOW and HIGH frames. Describe the concrete visible transformation from low to high.
|
| 57 |
+
- Reverse each recoverable high-to-low edit when possible.
|
| 58 |
+
- Preserve original layout, identity, action, camera motion, timing, shot scale, and scene semantics.
|
| 59 |
+
- Anchor new cinematic/high-cost details to visible carriers in the LOW video: people, clothing, props, background, architecture, light sources, atmosphere, materials, or scene geometry.
|
| 60 |
+
- Mention high-cost elements only if they are supported by the HIGH frames or original instruction.
|
| 61 |
+
- Avoid generic wording like "make it cinematic" alone; include specific visual changes.
|
| 62 |
+
- Do not invent unrelated story events.
|
| 63 |
+
- Do not mention that this is a reverse rewrite.
|
| 64 |
+
- Output JSON with exactly these keys:
|
| 65 |
+
- low2high_prompt: string
|
| 66 |
+
- transformation_tags: array of short strings
|
| 67 |
+
- confidence: number from 0 to 1
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 72 |
+
rows: list[dict[str, Any]] = []
|
| 73 |
+
for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
| 74 |
+
if not line.strip():
|
| 75 |
+
continue
|
| 76 |
+
try:
|
| 77 |
+
rows.append(json.loads(line))
|
| 78 |
+
except json.JSONDecodeError as exc:
|
| 79 |
+
raise ValueError(f"{path}:{line_no}: invalid JSON: {exc}") from exc
|
| 80 |
+
return rows
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def append_jsonl(path: Path, row: dict[str, Any]) -> None:
|
| 84 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 85 |
+
with path.open("a", encoding="utf-8") as f:
|
| 86 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 87 |
+
f.flush()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def load_done_ids(path: Path) -> set[str]:
|
| 91 |
+
if not path.exists():
|
| 92 |
+
return set()
|
| 93 |
+
done: set[str] = set()
|
| 94 |
+
for row in read_jsonl(path):
|
| 95 |
+
sample_id = str(row.get("id", "") or "").strip()
|
| 96 |
+
if sample_id and not row.get("api_error"):
|
| 97 |
+
done.add(sample_id)
|
| 98 |
+
return done
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def parse_response(text: str) -> dict[str, Any]:
|
| 102 |
+
text = text.strip()
|
| 103 |
+
if text.startswith("```"):
|
| 104 |
+
text = text.strip("`").strip()
|
| 105 |
+
if text.startswith("json"):
|
| 106 |
+
text = text[4:].strip()
|
| 107 |
+
data = json.loads(text)
|
| 108 |
+
prompt = str(data.get("low2high_prompt", "") or "").strip()
|
| 109 |
+
if not prompt:
|
| 110 |
+
raise ValueError("missing low2high_prompt")
|
| 111 |
+
tags = data.get("transformation_tags", [])
|
| 112 |
+
if not isinstance(tags, list):
|
| 113 |
+
tags = []
|
| 114 |
+
try:
|
| 115 |
+
confidence = float(data.get("confidence", 0.0))
|
| 116 |
+
except (TypeError, ValueError):
|
| 117 |
+
confidence = 0.0
|
| 118 |
+
return {
|
| 119 |
+
"low2high_prompt": prompt,
|
| 120 |
+
"transformation_tags": [str(x) for x in tags[:20]],
|
| 121 |
+
"confidence": max(0.0, min(1.0, confidence)),
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def sample_video_frames(video_path: Path, max_frames: int, resize: int) -> list[str]:
|
| 126 |
+
import imageio.v3 as iio
|
| 127 |
+
from PIL import Image
|
| 128 |
+
|
| 129 |
+
if max_frames <= 0:
|
| 130 |
+
return []
|
| 131 |
+
try:
|
| 132 |
+
meta = iio.immeta(video_path)
|
| 133 |
+
except Exception:
|
| 134 |
+
meta = {}
|
| 135 |
+
raw_frame_count = meta.get("nframes") or 0
|
| 136 |
+
try:
|
| 137 |
+
frame_count_float = float(raw_frame_count)
|
| 138 |
+
except (TypeError, ValueError, OverflowError):
|
| 139 |
+
frame_count_float = 0.0
|
| 140 |
+
frame_count = int(frame_count_float) if math.isfinite(frame_count_float) and frame_count_float > 0 else 0
|
| 141 |
+
|
| 142 |
+
frames = []
|
| 143 |
+
if frame_count > 0 and frame_count < 1_000_000:
|
| 144 |
+
if max_frames == 1:
|
| 145 |
+
indices = [frame_count // 2]
|
| 146 |
+
else:
|
| 147 |
+
indices = [round(i * (frame_count - 1) / (max_frames - 1)) for i in range(max_frames)]
|
| 148 |
+
for idx in indices:
|
| 149 |
+
try:
|
| 150 |
+
frames.append(iio.imread(video_path, index=int(idx)))
|
| 151 |
+
except Exception:
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
if not frames:
|
| 155 |
+
try:
|
| 156 |
+
for idx, frame in enumerate(iio.imiter(video_path)):
|
| 157 |
+
if idx % 24 == 0:
|
| 158 |
+
frames.append(frame)
|
| 159 |
+
if len(frames) >= max_frames:
|
| 160 |
+
break
|
| 161 |
+
except Exception as exc:
|
| 162 |
+
raise RuntimeError(f"failed to decode {video_path}: {exc}") from exc
|
| 163 |
+
|
| 164 |
+
encoded: list[str] = []
|
| 165 |
+
for frame in frames[:max_frames]:
|
| 166 |
+
image = Image.fromarray(frame).convert("RGB")
|
| 167 |
+
if resize > 0:
|
| 168 |
+
image.thumbnail((resize, resize))
|
| 169 |
+
buffer = io.BytesIO()
|
| 170 |
+
image.save(buffer, format="JPEG", quality=85)
|
| 171 |
+
encoded.append(base64.b64encode(buffer.getvalue()).decode("ascii"))
|
| 172 |
+
return encoded
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def sample_video_pil_frames(video_path: Path, max_frames: int, resize: int) -> list[Any]:
|
| 176 |
+
import base64 as base64_module
|
| 177 |
+
from PIL import Image
|
| 178 |
+
|
| 179 |
+
frames_b64 = sample_video_frames(video_path, max_frames, resize)
|
| 180 |
+
images = []
|
| 181 |
+
for frame_b64 in frames_b64:
|
| 182 |
+
images.append(Image.open(io.BytesIO(base64_module.b64decode(frame_b64))).convert("RGB"))
|
| 183 |
+
return images
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def image_part(label: str, frame_b64: str) -> list[dict[str, Any]]:
|
| 187 |
+
return [
|
| 188 |
+
{"type": "text", "text": label},
|
| 189 |
+
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{frame_b64}"}},
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def resolve_pair_paths(row: dict[str, Any], root: Path, repo_root: Path) -> tuple[Path, Path]:
|
| 194 |
+
low = root / str(row.get("low_cost_path", "") or "")
|
| 195 |
+
high = root / str(row.get("high_cost_path", "") or "")
|
| 196 |
+
if not low.is_absolute():
|
| 197 |
+
low = repo_root / low
|
| 198 |
+
if not high.is_absolute():
|
| 199 |
+
high = repo_root / high
|
| 200 |
+
return low, high
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def build_api_messages(
|
| 204 |
+
*,
|
| 205 |
+
sample_id: str,
|
| 206 |
+
high2low_prompt: str,
|
| 207 |
+
use_video: bool,
|
| 208 |
+
row: dict[str, Any],
|
| 209 |
+
repo_root: Path,
|
| 210 |
+
root: Path,
|
| 211 |
+
max_frames: int,
|
| 212 |
+
resize: int,
|
| 213 |
+
) -> list[dict[str, Any]]:
|
| 214 |
+
if use_video:
|
| 215 |
+
low_video, high_video = resolve_pair_paths(row, root, repo_root)
|
| 216 |
+
low_frames = sample_video_frames(low_video, max_frames, resize)
|
| 217 |
+
high_frames = sample_video_frames(high_video, max_frames, resize)
|
| 218 |
+
content: list[dict[str, Any]] = [
|
| 219 |
+
{"type": "text", "text": VIDEO_USER_TEMPLATE.format(sample_id=sample_id, high2low_prompt=high2low_prompt)}
|
| 220 |
+
]
|
| 221 |
+
for idx, frame in enumerate(low_frames):
|
| 222 |
+
content.extend(image_part(f"LOW frame {idx + 1}", frame))
|
| 223 |
+
for idx, frame in enumerate(high_frames):
|
| 224 |
+
content.extend(image_part(f"HIGH frame {idx + 1}", frame))
|
| 225 |
+
return [
|
| 226 |
+
{"role": "system", "content": VIDEO_SYSTEM_PROMPT},
|
| 227 |
+
{"role": "user", "content": content},
|
| 228 |
+
]
|
| 229 |
+
return [
|
| 230 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 231 |
+
{"role": "user", "content": USER_TEMPLATE.format(sample_id=sample_id, high2low_prompt=high2low_prompt)},
|
| 232 |
+
]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def build_local_messages(
|
| 236 |
+
*,
|
| 237 |
+
sample_id: str,
|
| 238 |
+
high2low_prompt: str,
|
| 239 |
+
use_video: bool,
|
| 240 |
+
row: dict[str, Any],
|
| 241 |
+
repo_root: Path,
|
| 242 |
+
root: Path,
|
| 243 |
+
max_frames: int,
|
| 244 |
+
resize: int,
|
| 245 |
+
) -> list[dict[str, Any]]:
|
| 246 |
+
if use_video:
|
| 247 |
+
low_video, high_video = resolve_pair_paths(row, root, repo_root)
|
| 248 |
+
low_frames = sample_video_pil_frames(low_video, max_frames, resize)
|
| 249 |
+
high_frames = sample_video_pil_frames(high_video, max_frames, resize)
|
| 250 |
+
content: list[dict[str, Any]] = [
|
| 251 |
+
{"type": "text", "text": VIDEO_USER_TEMPLATE.format(sample_id=sample_id, high2low_prompt=high2low_prompt)}
|
| 252 |
+
]
|
| 253 |
+
for idx, image in enumerate(low_frames):
|
| 254 |
+
content.append({"type": "text", "text": f"LOW frame {idx + 1}"})
|
| 255 |
+
content.append({"type": "image", "image": image})
|
| 256 |
+
for idx, image in enumerate(high_frames):
|
| 257 |
+
content.append({"type": "text", "text": f"HIGH frame {idx + 1}"})
|
| 258 |
+
content.append({"type": "image", "image": image})
|
| 259 |
+
return [
|
| 260 |
+
{"role": "system", "content": VIDEO_SYSTEM_PROMPT},
|
| 261 |
+
{"role": "user", "content": content},
|
| 262 |
+
]
|
| 263 |
+
return [
|
| 264 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 265 |
+
{"role": "user", "content": USER_TEMPLATE.format(sample_id=sample_id, high2low_prompt=high2low_prompt)},
|
| 266 |
+
]
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def collect_local_images(messages: list[dict[str, Any]]) -> list[Any]:
|
| 270 |
+
images = []
|
| 271 |
+
for message in messages:
|
| 272 |
+
content = message.get("content")
|
| 273 |
+
if not isinstance(content, list):
|
| 274 |
+
continue
|
| 275 |
+
for part in content:
|
| 276 |
+
if isinstance(part, dict) and part.get("type") == "image":
|
| 277 |
+
images.append(part.get("image"))
|
| 278 |
+
return images
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def load_local_model(model_dir: Path, dtype: str, device_map: str) -> tuple[Any, Any]:
|
| 282 |
+
import torch
|
| 283 |
+
from transformers import AutoProcessor
|
| 284 |
+
|
| 285 |
+
try:
|
| 286 |
+
from transformers import AutoModelForImageTextToText
|
| 287 |
+
model_cls = AutoModelForImageTextToText
|
| 288 |
+
except ImportError:
|
| 289 |
+
from transformers import AutoModelForVision2Seq
|
| 290 |
+
model_cls = AutoModelForVision2Seq
|
| 291 |
+
|
| 292 |
+
dtype_map = {
|
| 293 |
+
"auto": "auto",
|
| 294 |
+
"bfloat16": torch.bfloat16,
|
| 295 |
+
"float16": torch.float16,
|
| 296 |
+
"float32": torch.float32,
|
| 297 |
+
}
|
| 298 |
+
torch_dtype = dtype_map.get(dtype, "auto")
|
| 299 |
+
processor = AutoProcessor.from_pretrained(str(model_dir), trust_remote_code=True)
|
| 300 |
+
model = model_cls.from_pretrained(
|
| 301 |
+
str(model_dir),
|
| 302 |
+
torch_dtype=torch_dtype,
|
| 303 |
+
device_map=device_map,
|
| 304 |
+
trust_remote_code=True,
|
| 305 |
+
)
|
| 306 |
+
model.eval()
|
| 307 |
+
return model, processor
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def local_generate(
|
| 311 |
+
*,
|
| 312 |
+
model: Any,
|
| 313 |
+
processor: Any,
|
| 314 |
+
messages: list[dict[str, Any]],
|
| 315 |
+
max_new_tokens: int,
|
| 316 |
+
) -> tuple[str, dict[str, int]]:
|
| 317 |
+
import torch
|
| 318 |
+
|
| 319 |
+
prompt_text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 320 |
+
images = collect_local_images(messages)
|
| 321 |
+
kwargs: dict[str, Any] = {"text": [prompt_text], "return_tensors": "pt"}
|
| 322 |
+
if images:
|
| 323 |
+
kwargs["images"] = images
|
| 324 |
+
inputs = processor(**kwargs)
|
| 325 |
+
model_device = next(model.parameters()).device
|
| 326 |
+
inputs = {k: v.to(model_device) if hasattr(v, "to") else v for k, v in inputs.items()}
|
| 327 |
+
input_len = int(inputs["input_ids"].shape[-1])
|
| 328 |
+
with torch.inference_mode():
|
| 329 |
+
generated = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
|
| 330 |
+
output_ids = generated[:, input_len:]
|
| 331 |
+
text = processor.batch_decode(output_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 332 |
+
usage = {
|
| 333 |
+
"prompt_tokens": input_len,
|
| 334 |
+
"completion_tokens": int(output_ids.shape[-1]),
|
| 335 |
+
"total_tokens": int(generated.shape[-1]),
|
| 336 |
+
}
|
| 337 |
+
return text, usage
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def estimate_cost(usage: Any, input_per_1m: float, output_per_1m: float) -> dict[str, Any]:
|
| 341 |
+
prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0) if usage else 0
|
| 342 |
+
completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0) if usage else 0
|
| 343 |
+
total_tokens = int(getattr(usage, "total_tokens", 0) or prompt_tokens + completion_tokens) if usage else 0
|
| 344 |
+
cost = prompt_tokens / 1_000_000 * input_per_1m + completion_tokens / 1_000_000 * output_per_1m
|
| 345 |
+
return {
|
| 346 |
+
"prompt_tokens": prompt_tokens,
|
| 347 |
+
"completion_tokens": completion_tokens,
|
| 348 |
+
"total_tokens": total_tokens,
|
| 349 |
+
"estimated_cost_usd": round(cost, 6),
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def main() -> None:
|
| 354 |
+
parser = argparse.ArgumentParser()
|
| 355 |
+
parser.add_argument("--backend", choices=["api", "local"], default="api")
|
| 356 |
+
parser.add_argument("--input", type=Path, default=Path("datas/low_high_cost/extracted/final_output/prompt.jsonl"))
|
| 357 |
+
parser.add_argument("--output", type=Path, default=Path("datas/low_high_cost/outputs/low2high_prompts_api.jsonl"))
|
| 358 |
+
parser.add_argument("--repo-root", type=Path, default=Path("."))
|
| 359 |
+
parser.add_argument("--root", type=Path, default=Path("datas/low_high_cost/extracted/final_output"))
|
| 360 |
+
parser.add_argument("--base-url", default="http://35.220.164.252:3888/v1")
|
| 361 |
+
parser.add_argument("--api-key-env", default="LOW_HIGH_COST_API_KEY")
|
| 362 |
+
parser.add_argument("--model", default="gpt-4o")
|
| 363 |
+
parser.add_argument("--local-model-dir", type=Path, default=None)
|
| 364 |
+
parser.add_argument("--local-dtype", choices=["auto", "bfloat16", "float16", "float32"], default="bfloat16")
|
| 365 |
+
parser.add_argument("--local-device-map", default="auto")
|
| 366 |
+
parser.add_argument("--max-new-tokens", type=int, default=512)
|
| 367 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 368 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 369 |
+
parser.add_argument("--use-video", action="store_true")
|
| 370 |
+
parser.add_argument("--max-frames", type=int, default=3)
|
| 371 |
+
parser.add_argument("--resize", type=int, default=448)
|
| 372 |
+
parser.add_argument("--input-cost-per-1m", type=float, default=0.0)
|
| 373 |
+
parser.add_argument("--output-cost-per-1m", type=float, default=0.0)
|
| 374 |
+
parser.add_argument("--sleep", type=float, default=0.0)
|
| 375 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 376 |
+
args = parser.parse_args()
|
| 377 |
+
|
| 378 |
+
rows = read_jsonl(args.input)
|
| 379 |
+
if args.limit:
|
| 380 |
+
rows = rows[: args.limit]
|
| 381 |
+
done = load_done_ids(args.output)
|
| 382 |
+
pending = [r for r in rows if str(r.get("id", "") or "") not in done]
|
| 383 |
+
|
| 384 |
+
if args.dry_run:
|
| 385 |
+
print(f"dry run: rows={len(rows)} done={len(done)} pending={len(pending)}")
|
| 386 |
+
if pending:
|
| 387 |
+
sample = pending[0]
|
| 388 |
+
payload = {"id": sample.get("id"), "high2low_prompt": sample.get("high2low_prompt", "")[:800]}
|
| 389 |
+
if args.use_video:
|
| 390 |
+
low, high = resolve_pair_paths(sample, args.root, args.repo_root)
|
| 391 |
+
payload.update({"low_video": str(low), "high_video": str(high), "max_frames": args.max_frames, "resize": args.resize})
|
| 392 |
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
| 393 |
+
return
|
| 394 |
+
|
| 395 |
+
client = None
|
| 396 |
+
local_model = None
|
| 397 |
+
local_processor = None
|
| 398 |
+
if args.backend == "api":
|
| 399 |
+
api_key = os.environ.get(args.api_key_env)
|
| 400 |
+
if not api_key:
|
| 401 |
+
raise RuntimeError(f"Set {args.api_key_env} before calling the API")
|
| 402 |
+
from openai import OpenAI
|
| 403 |
+
|
| 404 |
+
client = OpenAI(api_key=api_key, base_url=args.base_url)
|
| 405 |
+
else:
|
| 406 |
+
model_dir = args.local_model_dir or Path(args.model)
|
| 407 |
+
local_model, local_processor = load_local_model(model_dir, args.local_dtype, args.local_device_map)
|
| 408 |
+
processed = 0
|
| 409 |
+
total_prompt_tokens = 0
|
| 410 |
+
total_completion_tokens = 0
|
| 411 |
+
total_cost = 0.0
|
| 412 |
+
|
| 413 |
+
for row in pending:
|
| 414 |
+
sample_id = str(row.get("id", "") or "").strip()
|
| 415 |
+
high2low_prompt = str(row.get("high2low_prompt", "") or "").strip()
|
| 416 |
+
result: dict[str, Any]
|
| 417 |
+
try:
|
| 418 |
+
if args.backend == "api":
|
| 419 |
+
messages = build_api_messages(
|
| 420 |
+
sample_id=sample_id,
|
| 421 |
+
high2low_prompt=high2low_prompt,
|
| 422 |
+
use_video=args.use_video,
|
| 423 |
+
row=row,
|
| 424 |
+
repo_root=args.repo_root,
|
| 425 |
+
root=args.root,
|
| 426 |
+
max_frames=args.max_frames,
|
| 427 |
+
resize=args.resize,
|
| 428 |
+
)
|
| 429 |
+
response = client.chat.completions.create(
|
| 430 |
+
model=args.model,
|
| 431 |
+
messages=messages,
|
| 432 |
+
temperature=args.temperature,
|
| 433 |
+
response_format={"type": "json_object"},
|
| 434 |
+
)
|
| 435 |
+
response_text = response.choices[0].message.content or "{}"
|
| 436 |
+
usage_cost = estimate_cost(response.usage, args.input_cost_per_1m, args.output_cost_per_1m)
|
| 437 |
+
else:
|
| 438 |
+
messages = build_local_messages(
|
| 439 |
+
sample_id=sample_id,
|
| 440 |
+
high2low_prompt=high2low_prompt,
|
| 441 |
+
use_video=args.use_video,
|
| 442 |
+
row=row,
|
| 443 |
+
repo_root=args.repo_root,
|
| 444 |
+
root=args.root,
|
| 445 |
+
max_frames=args.max_frames,
|
| 446 |
+
resize=args.resize,
|
| 447 |
+
)
|
| 448 |
+
response_text, local_usage = local_generate(
|
| 449 |
+
model=local_model,
|
| 450 |
+
processor=local_processor,
|
| 451 |
+
messages=messages,
|
| 452 |
+
max_new_tokens=args.max_new_tokens,
|
| 453 |
+
)
|
| 454 |
+
usage_cost = {**local_usage, "estimated_cost_usd": 0.0}
|
| 455 |
+
parsed = parse_response(response_text)
|
| 456 |
+
result = {
|
| 457 |
+
"id": sample_id,
|
| 458 |
+
**parsed,
|
| 459 |
+
"api_model": args.model,
|
| 460 |
+
"backend": args.backend,
|
| 461 |
+
"prompt_mode": "video_pair" if args.use_video else "text_only",
|
| 462 |
+
"max_frames_per_video": args.max_frames if args.use_video else 0,
|
| 463 |
+
**usage_cost,
|
| 464 |
+
"api_error": "",
|
| 465 |
+
}
|
| 466 |
+
except Exception as exc:
|
| 467 |
+
result = {
|
| 468 |
+
"id": sample_id,
|
| 469 |
+
"low2high_prompt": "",
|
| 470 |
+
"transformation_tags": [],
|
| 471 |
+
"confidence": 0.0,
|
| 472 |
+
"api_model": args.model,
|
| 473 |
+
"backend": args.backend,
|
| 474 |
+
"prompt_mode": "video_pair" if args.use_video else "text_only",
|
| 475 |
+
"max_frames_per_video": args.max_frames if args.use_video else 0,
|
| 476 |
+
"prompt_tokens": 0,
|
| 477 |
+
"completion_tokens": 0,
|
| 478 |
+
"total_tokens": 0,
|
| 479 |
+
"estimated_cost_usd": 0.0,
|
| 480 |
+
"api_error": f"{type(exc).__name__}: {exc}",
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
append_jsonl(args.output, result)
|
| 484 |
+
processed += 1
|
| 485 |
+
total_prompt_tokens += int(result.get("prompt_tokens", 0) or 0)
|
| 486 |
+
total_completion_tokens += int(result.get("completion_tokens", 0) or 0)
|
| 487 |
+
total_cost += float(result.get("estimated_cost_usd", 0.0) or 0.0)
|
| 488 |
+
print(
|
| 489 |
+
f"processed={processed} id={sample_id} error={bool(result.get('api_error'))} "
|
| 490 |
+
f"cost=${float(result.get('estimated_cost_usd', 0.0) or 0.0):.6f}",
|
| 491 |
+
flush=True,
|
| 492 |
+
)
|
| 493 |
+
if args.sleep:
|
| 494 |
+
time.sleep(args.sleep)
|
| 495 |
+
|
| 496 |
+
summary = {
|
| 497 |
+
"input": str(args.input),
|
| 498 |
+
"output": str(args.output),
|
| 499 |
+
"model": args.model,
|
| 500 |
+
"processed": processed,
|
| 501 |
+
"prompt_tokens": total_prompt_tokens,
|
| 502 |
+
"completion_tokens": total_completion_tokens,
|
| 503 |
+
"estimated_cost_usd": round(total_cost, 6),
|
| 504 |
+
}
|
| 505 |
+
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
if __name__ == "__main__":
|
| 509 |
+
main()
|
low_high_cost/validate_records.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Validate low_high_cost shared_records before launching training."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from collections import Counter
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
REQUIRED_FIELDS = ["sample_id", "low_video_path", "high_video_path", "raw_prompt"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def read_jsonl(path: Path) -> list[dict[str, Any]]:
|
| 17 |
+
rows: list[dict[str, Any]] = []
|
| 18 |
+
for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
| 19 |
+
if not line.strip():
|
| 20 |
+
continue
|
| 21 |
+
try:
|
| 22 |
+
rows.append(json.loads(line))
|
| 23 |
+
except json.JSONDecodeError as exc:
|
| 24 |
+
raise ValueError(f"{path}:{line_no}: invalid JSON: {exc}") from exc
|
| 25 |
+
return rows
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def exists(path_text: str, repo_root: Path) -> bool:
|
| 29 |
+
path = Path(path_text)
|
| 30 |
+
if path.is_absolute():
|
| 31 |
+
return path.exists()
|
| 32 |
+
return (repo_root / path).exists()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main() -> None:
|
| 36 |
+
parser = argparse.ArgumentParser()
|
| 37 |
+
parser.add_argument("--records", type=Path, required=True)
|
| 38 |
+
parser.add_argument("--repo-root", type=Path, default=Path("."))
|
| 39 |
+
parser.add_argument("--show", type=int, default=5)
|
| 40 |
+
parser.add_argument("--fail-on-missing", action="store_true")
|
| 41 |
+
args = parser.parse_args()
|
| 42 |
+
|
| 43 |
+
rows = read_jsonl(args.records)
|
| 44 |
+
sample_ids = [str(r.get("sample_id", "") or "") for r in rows]
|
| 45 |
+
duplicate_ids = [k for k, v in Counter(sample_ids).items() if k and v > 1]
|
| 46 |
+
|
| 47 |
+
missing_fields = {field: 0 for field in REQUIRED_FIELDS}
|
| 48 |
+
missing_low: list[str] = []
|
| 49 |
+
missing_high: list[str] = []
|
| 50 |
+
empty_prompt: list[str] = []
|
| 51 |
+
prompt_sources = Counter()
|
| 52 |
+
groups = Counter()
|
| 53 |
+
|
| 54 |
+
for row in rows:
|
| 55 |
+
for field in REQUIRED_FIELDS:
|
| 56 |
+
if not str(row.get(field, "") or "").strip():
|
| 57 |
+
missing_fields[field] += 1
|
| 58 |
+
sample_id = str(row.get("sample_id", "") or "")
|
| 59 |
+
if not exists(str(row.get("low_video_path", "") or ""), args.repo_root):
|
| 60 |
+
missing_low.append(sample_id)
|
| 61 |
+
if not exists(str(row.get("high_video_path", "") or ""), args.repo_root):
|
| 62 |
+
missing_high.append(sample_id)
|
| 63 |
+
if not str(row.get("raw_prompt", "") or "").strip():
|
| 64 |
+
empty_prompt.append(sample_id)
|
| 65 |
+
prompt_sources[str(row.get("prompt_source", "") or "unknown")] += 1
|
| 66 |
+
groups[str(row.get("source_group_id", "") or "unknown")] += 1
|
| 67 |
+
|
| 68 |
+
summary = {
|
| 69 |
+
"records": str(args.records),
|
| 70 |
+
"rows": len(rows),
|
| 71 |
+
"unique_sample_ids": len(set(sample_ids)),
|
| 72 |
+
"duplicate_sample_ids": len(duplicate_ids),
|
| 73 |
+
"missing_fields": missing_fields,
|
| 74 |
+
"missing_low_video": len(missing_low),
|
| 75 |
+
"missing_high_video": len(missing_high),
|
| 76 |
+
"empty_prompt": len(empty_prompt),
|
| 77 |
+
"num_groups": len(groups),
|
| 78 |
+
"prompt_sources": dict(prompt_sources),
|
| 79 |
+
"top_groups": groups.most_common(10),
|
| 80 |
+
"examples": rows[: args.show],
|
| 81 |
+
"missing_examples": {
|
| 82 |
+
"low": missing_low[: args.show],
|
| 83 |
+
"high": missing_high[: args.show],
|
| 84 |
+
"empty_prompt": empty_prompt[: args.show],
|
| 85 |
+
"duplicate_ids": duplicate_ids[: args.show],
|
| 86 |
+
},
|
| 87 |
+
}
|
| 88 |
+
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
| 89 |
+
|
| 90 |
+
if args.fail_on_missing and (duplicate_ids or missing_low or missing_high or empty_prompt or any(missing_fields.values())):
|
| 91 |
+
raise SystemExit(1)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
main()
|