Download cons_memory/caption_memory.py from SitongGong/EvoStream: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/datasets/SitongGong/EvoStream/resolve/main/cons_memory/caption_memory.py
- Command line
-
hf download hf://datasets/SitongGong/EvoStream/cons_memory/caption_memory.py
-
curl -L -o caption_memory.py https://huggingface.co/datasets/SitongGong/EvoStream/resolve/main/cons_memory/caption_memory.py
15.1 kB
| """记忆构造第二阶段:clip caption 生成 + OpenAI 文本 embedding(与 embedding 阶段解耦)。 | |
| 参照 egolife_online_processing_.py 的两条约定: | |
| - caption 模型走 OpenAI 兼容 chat 接口(DashScope compatible-mode / 本地 vLLM serve / | |
| OpenAI 官方均可,--api-base 切换),默认 DashScope Qwen3-VL; | |
| - caption 文本 embedding 用 OpenAI text-embedding-3-small(1536 维), | |
| 走官方 API(注意:不能设 OPENAI_BASE_URL 空串,需删除该变量)。 | |
| 与 EgoLife 多层 caption(30s/5min/1h)的区别:我们保持扁平——每 clip 一次 VLM 调用, | |
| 同时产出 clip 级细粒度 caption 和逐关键帧短 caption(一次调用两级都拿,省一半调用量)。 | |
| 用法: | |
| python caption_memory.py --dataset ovo --limit 2 # 冒烟 | |
| python caption_memory.py --dataset streamarena --lang zh # 中文视频用中文 caption | |
| """ | |
| import argparse | |
| import base64 | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import sys | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import numpy as np | |
| import pandas as pd | |
| import requests | |
| from config import ConsMemoryConfig, LOG_DIR | |
| logger = logging.getLogger("caption_memory") | |
| # 默认 caption 后端:本地 vLLM Qwen3.6-35B-A3B-FP8(用户指定:记忆构造阶段不用 GPT)。 | |
| # 服务在 localhost:8010(2026-08-17 已在运行,vision 实测可用); | |
| # embedding 用 KEY1(sk-proj-yJ5Q... 即各 .env 里未编号的 OPENAI_API_KEY)。 | |
| DEFAULT_API_BASE = "http://localhost:8010/v1" | |
| DEFAULT_MODEL = "Qwen3.6-35B-A3B-FP8" | |
| EMBED_MODEL = "text-embedding-3-small" | |
| EMBED_DIM = 1536 | |
| CAPTION_PROMPT_EN = """You are watching {n} keyframes sampled from a {dur:.0f}-second video clip (timestamps: {ts}). | |
| Write fine-grained factual descriptions. Cover: visible entities and their states, actions in progress or completed, exact counts, any on-screen/printed text, and notable state changes. | |
| Return ONLY valid JSON: | |
| {{"frame_captions": [{n} short captions, one per keyframe in order], "clip_caption": "2-4 sentences describing what happens across this clip"}}""" | |
| CAPTION_PROMPT_ZH = """你正在观看从一段 {dur:.0f} 秒视频片段中采样的 {n} 张关键帧(时间戳:{ts})。 | |
| 请写出细粒度的客观描述,覆盖:可见实体及其状态、正在进行或已完成的动作、精确数量、画面中出现的文字、显著的状态变化。 | |
| 只返回合法 JSON: | |
| {{"frame_captions": [{n} 条简短描述,按关键帧顺序一一对应], "clip_caption": "2-4 句话描述整个片段发生了什么"}}""" | |
| def _b64_image(path: str) -> dict: | |
| with open(path, "rb") as f: | |
| data = base64.b64encode(f.read()).decode() | |
| return {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{data}"}} | |
| def _safe_json(text: str): | |
| if not text: | |
| return None | |
| s = re.sub(r"```(?:json)?", "", text).strip().strip("`") | |
| m = re.search(r"\{.*\}", s, re.DOTALL) | |
| if not m: | |
| return None | |
| try: | |
| return json.loads(m.group(0)) | |
| except json.JSONDecodeError: | |
| return None | |
| GLOBAL_PROMPT_EN = """Below are chronological captions of a {dur:.0f}-second video, one per 10s clip with time ranges. | |
| {captions} | |
| Write a GLOBAL summary of the whole video (5-10 sentences): the setting, the main people/objects, and the storyline of what happens over time. Include approximate timestamps (e.g. "around 120s") for major transitions. Be factual.""" | |
| GLOBAL_PROMPT_ZH = """以下是一段 {dur:.0f} 秒视频的按时间顺序的分段描述(每 10 秒一条,带时间区间)。 | |
| {captions} | |
| 请写出整个视频的全局摘要(5-10 句):场景、主要人物/物体、随时间发生的事件主线。重要转折处标注大致时间戳(如"约 120 秒处")。保持客观。""" | |
| class CaptionClient: | |
| def __init__(self, api_base: str, api_key: str, model: str, lang: str): | |
| self.url = api_base.rstrip("/") + "/chat/completions" | |
| self.headers = {"Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json"} | |
| self.model = model | |
| self.lang = lang | |
| self.tmpl = CAPTION_PROMPT_ZH if lang == "zh" else CAPTION_PROMPT_EN | |
| def text_call(self, prompt: str, max_tokens: int = 800, max_retries: int = 3) -> str: | |
| body = {"model": self.model, | |
| "messages": [{"role": "user", "content": prompt}], | |
| "max_tokens": max_tokens, "temperature": 0.1} | |
| for attempt in range(max_retries): | |
| try: | |
| r = requests.post(self.url, headers=self.headers, json=body, timeout=120) | |
| if r.status_code == 429: | |
| time.sleep(5 * (attempt + 1)); continue | |
| r.raise_for_status() | |
| return r.json()["choices"][0]["message"]["content"] or "" | |
| except Exception as e: | |
| logger.warning("text_call 失败(第%d次): %s", attempt + 1, e) | |
| time.sleep(2 * (attempt + 1)) | |
| return "" | |
| def global_caption(self, cdf, duration: float) -> str: | |
| """全视频 global caption:clip caption 分块层级汇总(长视频两段式)。""" | |
| tmpl = GLOBAL_PROMPT_ZH if self.lang == "zh" else GLOBAL_PROMPT_EN | |
| lines = [f"[{r['t_start']:.0f}-{r['t_end']:.0f}s] {r['caption']}" | |
| for _, r in cdf.iterrows() if r.get("caption")] | |
| if not lines: | |
| return "" | |
| chunk_size = 60 # 60 条 clip caption ≈ 10min 视频一块 | |
| if len(lines) <= chunk_size: | |
| return self.text_call(tmpl.format(dur=duration, captions="\n".join(lines))) | |
| # 长视频:先分块摘要,再汇总 | |
| parts = [] | |
| for s in range(0, len(lines), chunk_size): | |
| seg = lines[s:s + chunk_size] | |
| parts.append(self.text_call(tmpl.format( | |
| dur=duration, captions="\n".join(seg)), max_tokens=400)) | |
| return self.text_call(tmpl.format(dur=duration, captions="\n".join(parts))) | |
| def caption_clip(self, kf_paths: list, kf_times: list, dur: float, | |
| max_retries: int = 3) -> dict: | |
| ts = ", ".join(f"{t:.0f}s" for t in kf_times) | |
| prompt = self.tmpl.format(n=len(kf_paths), dur=dur, ts=ts) | |
| content = [_b64_image(p) for p in kf_paths] + [{"type": "text", "text": prompt}] | |
| body = {"model": self.model, | |
| "messages": [{"role": "user", "content": content}], | |
| "max_tokens": 1024, "temperature": 0.1} | |
| for attempt in range(max_retries): | |
| try: | |
| r = requests.post(self.url, headers=self.headers, json=body, timeout=120) | |
| if r.status_code == 429: | |
| time.sleep(5 * (attempt + 1)); continue | |
| r.raise_for_status() | |
| text = r.json()["choices"][0]["message"]["content"] | |
| parsed = _safe_json(text) | |
| if parsed and parsed.get("clip_caption"): | |
| fcs = parsed.get("frame_captions") or [] | |
| fcs = [str(c) for c in fcs][: len(kf_paths)] | |
| while len(fcs) < len(kf_paths): | |
| fcs.append("") | |
| return {"clip_caption": str(parsed["clip_caption"]), | |
| "frame_captions": fcs} | |
| # JSON 解析失败但有文本:整段当 clip caption 用(帧级留空) | |
| if text and attempt == max_retries - 1: | |
| return {"clip_caption": text.strip()[:2000], | |
| "frame_captions": [""] * len(kf_paths)} | |
| except Exception as e: | |
| logger.warning("caption 调用失败(第%d次): %s", attempt + 1, e) | |
| time.sleep(2 * (attempt + 1)) | |
| return {"clip_caption": "", "frame_captions": [""] * len(kf_paths)} | |
| def embed_texts(texts: list, api_key: str, batch: int = 32, | |
| max_retries: int = 3) -> np.ndarray: | |
| """OpenAI 官方 embedding。空文本返回零向量占位(保持行对齐)。""" | |
| url = "https://api.openai.com/v1/embeddings" | |
| headers = {"Authorization": f"Bearer {api_key}"} | |
| out = np.zeros((len(texts), EMBED_DIM), dtype=np.float32) | |
| todo = [(i, t) for i, t in enumerate(texts) if t and t.strip()] | |
| for s in range(0, len(todo), batch): | |
| chunk = todo[s:s + batch] | |
| for attempt in range(max_retries): | |
| try: | |
| r = requests.post(url, headers=headers, timeout=60, json={ | |
| "model": EMBED_MODEL, | |
| "input": [t[:6000] for _, t in chunk]}) | |
| r.raise_for_status() | |
| for (i, _), d in zip(chunk, r.json()["data"]): | |
| v = np.array(d["embedding"], dtype=np.float32) | |
| out[i] = v / (np.linalg.norm(v) + 1e-9) | |
| break | |
| except Exception as e: | |
| logger.warning("embedding 调用失败(第%d次): %s", attempt + 1, e) | |
| time.sleep(2 * (attempt + 1)) | |
| return out | |
| def process_bank(bank_dir: str, client: CaptionClient, openai_key: str, | |
| concurrency: int) -> dict: | |
| cdf = pd.read_parquet(os.path.join(bank_dir, "clips.parquet")) | |
| fdf = pd.read_parquet(os.path.join(bank_dir, "frames.parquet")) | |
| # ---- 1. 并发生成 clip caption(含逐帧短 caption)---- | |
| results = {} | |
| with ThreadPoolExecutor(max_workers=concurrency) as pool: | |
| futs = {} | |
| for ridx, row in cdf.iterrows(): | |
| kf_paths = [os.path.join(bank_dir, p) for p in row["keyframe_paths"]] | |
| kf_times = sorted( | |
| fdf[fdf["clip_idx"] == row["clip_idx"]]["t"].tolist())[: len(kf_paths)] | |
| futs[pool.submit(client.caption_clip, kf_paths, kf_times or [row["t_start"]], | |
| row["t_end"] - row["t_start"])] = ridx | |
| for fut in as_completed(futs): | |
| results[futs[fut]] = fut.result() | |
| cdf["caption"] = [results[i]["clip_caption"] for i in cdf.index] | |
| # 帧级 caption 按 (clip_idx, t 排序) 对齐回 frames | |
| frame_caps = {} | |
| for ridx, row in cdf.iterrows(): | |
| sub = fdf[fdf["clip_idx"] == row["clip_idx"]].sort_values("t") | |
| for fi, cap in zip(sub.index, results[ridx]["frame_captions"]): | |
| frame_caps[fi] = cap | |
| fdf["caption"] = [frame_caps.get(i, "") for i in fdf.index] | |
| # ---- 2. OpenAI 文本 embedding ---- | |
| c_emb = embed_texts(cdf["caption"].tolist(), openai_key) | |
| f_emb = embed_texts(fdf["caption"].tolist(), openai_key) | |
| cdf["cap_emb"] = [e.astype(np.float16).tobytes() for e in c_emb] | |
| fdf["cap_emb"] = [e.astype(np.float16).tobytes() for e in f_emb] | |
| cdf.to_parquet(os.path.join(bank_dir, "clips.parquet")) | |
| fdf.to_parquet(os.path.join(bank_dir, "frames.parquet")) | |
| meta_path = os.path.join(bank_dir, "meta.json") | |
| with open(meta_path) as f: | |
| meta = json.load(f) | |
| # global caption(用户要求:全视频摘要,带时间戳里程碑) | |
| meta["global_caption"] = client.global_caption(cdf, meta.get("duration_s", 0.0)) | |
| meta["caption_done"] = True | |
| meta["caption_model"] = client.model | |
| meta["embed_model"] = EMBED_MODEL | |
| with open(meta_path, "w") as f: | |
| json.dump(meta, f, ensure_ascii=False, indent=2) | |
| n_empty = int((cdf["caption"].str.len() == 0).sum()) | |
| return {"n_clips": len(cdf), "n_empty_caption": n_empty} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--dataset", required=True, | |
| choices=["ovo", "streamingbench", "streamarena", "egoschema"]) | |
| ap.add_argument("--bank-root", default="") | |
| ap.add_argument("--api-base", default=os.environ.get("CAPTION_API_BASE", DEFAULT_API_BASE)) | |
| ap.add_argument("--model", default=os.environ.get("CAPTION_MODEL", DEFAULT_MODEL)) | |
| ap.add_argument("--api-key", default="", help="默认读 DASHSCOPE_API_KEY / CAPTION_API_KEY") | |
| ap.add_argument("--lang", default="en", choices=["en", "zh"]) | |
| ap.add_argument("--concurrency", type=int, default=8) | |
| ap.add_argument("--limit", type=int, default=0) | |
| ap.add_argument("--overwrite", action="store_true") | |
| ap.add_argument("--num-shards", type=int, default=1) | |
| ap.add_argument("--shard-idx", type=int, default=0) | |
| ap.add_argument("--only-ids", default="", help="只处理该文件列出的 video_id(插队用)") | |
| args = ap.parse_args() | |
| cfg = ConsMemoryConfig() | |
| root = os.path.join(args.bank_root or cfg.out_root, args.dataset) | |
| # 本地 vLLM 不校验 key,占位即可;外部 API 才需要真 key | |
| api_key = (args.api_key or os.environ.get("CAPTION_API_KEY") or "EMPTY") | |
| if "localhost" not in args.api_base and "127.0.0.1" not in args.api_base: | |
| assert api_key != "EMPTY", "外部 caption API 需要 key(--api-key 或 CAPTION_API_KEY)" | |
| # embedding 用 KEY1(EMBED_API_KEY 优先,其次 OPENAI_API_KEY) | |
| openai_key = (os.environ.get("EMBED_API_KEY", "") | |
| or os.environ.get("OPENAI_API_KEY", "")) | |
| assert openai_key, "缺 embedding key:export EMBED_API_KEY=<KEY1> 或 OPENAI_API_KEY" | |
| os.makedirs(LOG_DIR, exist_ok=True) | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="[%(asctime)s] %(levelname)s %(name)s: %(message)s", | |
| handlers=[logging.StreamHandler(), | |
| logging.FileHandler(os.path.join( | |
| LOG_DIR, f"evostream_caption_{args.dataset}.log"))]) | |
| client = CaptionClient(args.api_base, api_key, args.model, args.lang) | |
| n_done = n_skip = n_fail = 0 | |
| banks = sorted(os.listdir(root)) if os.path.isdir(root) else [] | |
| if args.only_ids: | |
| wanted = {l.strip() for l in open(args.only_ids) if l.strip()} | |
| banks = [b for b in banks if b in wanted] | |
| banks = [b for i, b in enumerate(banks) if i % args.num_shards == args.shard_idx] | |
| for name in banks: | |
| bank_dir = os.path.join(root, name) | |
| meta_path = os.path.join(bank_dir, "meta.json") | |
| if not os.path.exists(meta_path): | |
| continue | |
| with open(meta_path) as f: | |
| meta = json.load(f) | |
| if meta.get("caption_done") and not args.overwrite: | |
| n_skip += 1 | |
| continue | |
| if args.limit and n_done + n_fail >= args.limit: | |
| break | |
| try: | |
| t0 = time.time() | |
| stat = process_bank(bank_dir, client, openai_key, args.concurrency) | |
| n_done += 1 | |
| logger.info("[%d done] %s clips=%d 空caption=%d 用时%.1fs", | |
| n_done, name, stat["n_clips"], stat["n_empty_caption"], | |
| time.time() - t0) | |
| if stat["n_empty_caption"] > stat["n_clips"] * 0.2: | |
| logger.warning("%s 空 caption 比例过高(%d/%d),请检查 API", | |
| name, stat["n_empty_caption"], stat["n_clips"]) | |
| except Exception as e: | |
| n_fail += 1 | |
| logger.error("FAIL %s: %s", name, e) | |
| logger.info("caption 完成: done=%d skip=%d fail=%d", n_done, n_skip, n_fail) | |
| if __name__ == "__main__": | |
| main() | |