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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding: utf-8
|
| 3 |
+
# Cleaned and enhanced InternVideo2 6B evaluation script with structured logging
|
| 4 |
+
# Source:
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import subprocess
|
| 9 |
+
import logging
|
| 10 |
+
import json
|
| 11 |
+
import argparse
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import cv2
|
| 16 |
+
import torch
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
+
from huggingface_hub import hf_hub_download, HfApi, login
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def setup_logging(log_level=logging.INFO, log_file=None):
|
| 22 |
+
handlers = []
|
| 23 |
+
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 24 |
+
if log_file:
|
| 25 |
+
handlers.append(logging.FileHandler(log_file))
|
| 26 |
+
handlers.append(logging.StreamHandler(sys.stdout))
|
| 27 |
+
logging.basicConfig(level=log_level, format=fmt, handlers=handlers)
|
| 28 |
+
logging.info("Logging initialized.")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def run_command(cmd, cwd=None):
|
| 32 |
+
logging.debug(f"Running command: {cmd} (cwd={cwd})")
|
| 33 |
+
result = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
|
| 34 |
+
if result.returncode != 0:
|
| 35 |
+
logging.error(f"Command failed: {cmd}\nSTDOUT: {result.stdout}\nSTDERR: {result.stderr}")
|
| 36 |
+
raise RuntimeError(f"Command '{cmd}' failed (exit code {result.returncode})")
|
| 37 |
+
logging.debug(f"Command succeeded, output: {result.stdout.strip()}")
|
| 38 |
+
return result.stdout.strip()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def download_checkpoint(repo_id: str, filename: str) -> str:
|
| 42 |
+
logging.info(f"Downloading {filename} from {repo_id}...")
|
| 43 |
+
path = hf_hub_download(repo_id=repo_id, filename=filename)
|
| 44 |
+
logging.info(f"Downloaded vision checkpoint to {path}")
|
| 45 |
+
return path
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_config(config_path: str, vision_ckpt_path: str):
|
| 49 |
+
from demo.config import Config, eval_dict_leaf
|
| 50 |
+
logging.info(f"Loading config from {config_path}")
|
| 51 |
+
cfg = Config.from_file(config_path)
|
| 52 |
+
cfg = eval_dict_leaf(cfg)
|
| 53 |
+
cfg.model.vision_ckpt_path = vision_ckpt_path
|
| 54 |
+
cfg.model.vision_encoder.pretrained = vision_ckpt_path
|
| 55 |
+
cfg.pretrained_path = vision_ckpt_path
|
| 56 |
+
logging.debug(f"Config loaded: {cfg}")
|
| 57 |
+
return cfg
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def process_videos(
|
| 61 |
+
json_path: str,
|
| 62 |
+
model,
|
| 63 |
+
config,
|
| 64 |
+
output_prefix: str,
|
| 65 |
+
num_frames_override: int = None
|
| 66 |
+
):
|
| 67 |
+
"""
|
| 68 |
+
Run inference over each video, write outputs.
|
| 69 |
+
If num_frames_override is given, use it; otherwise use config.num_frames.
|
| 70 |
+
"""
|
| 71 |
+
from demo.utils import retrieve_text, _frame_from_video
|
| 72 |
+
|
| 73 |
+
logging.info(f"Reading evaluation data from {json_path}")
|
| 74 |
+
data = json.loads(Path(json_path).read_text())
|
| 75 |
+
preds, logits = [], []
|
| 76 |
+
|
| 77 |
+
# choose frame window size
|
| 78 |
+
num_frames = num_frames_override if num_frames_override is not None else config.num_frames
|
| 79 |
+
logging.info(f"Using window size: {num_frames} frames")
|
| 80 |
+
|
| 81 |
+
for video_path, phrase, _ in data:
|
| 82 |
+
logging.info("\n--- Starting new video ---")
|
| 83 |
+
full_video = Path("photography-model") / video_path
|
| 84 |
+
logging.info(f"Processing {full_video} with phrase '{phrase}'")
|
| 85 |
+
frames = list(_frame_from_video(cv2.VideoCapture(str(full_video))))
|
| 86 |
+
scores = []
|
| 87 |
+
|
| 88 |
+
for j in tqdm(range(len(frames) - (num_frames - 1)), desc=Path(video_path).stem):
|
| 89 |
+
_, probs = retrieve_text(
|
| 90 |
+
frames[j : j + num_frames], [phrase],
|
| 91 |
+
model=model, topk=1, config=config
|
| 92 |
+
)
|
| 93 |
+
scores.append(probs[0])
|
| 94 |
+
|
| 95 |
+
best_idx = int(np.argmax(scores) + 1)
|
| 96 |
+
preds.append(best_idx)
|
| 97 |
+
logits.append(list(zip(map(float, scores), range(1, len(scores) + 1))))
|
| 98 |
+
logging.info(f"Video result: predicted frame {best_idx}\n")
|
| 99 |
+
|
| 100 |
+
preds_file = f"{output_prefix}-t{num_frames}.json"
|
| 101 |
+
logits_file = f"{output_prefix}-logits-t{num_frames}.json"
|
| 102 |
+
logging.info(f"Writing predictions to {preds_file}")
|
| 103 |
+
Path(preds_file).write_text(json.dumps(preds, indent=2))
|
| 104 |
+
logging.info(f"Writing logits to {logits_file}")
|
| 105 |
+
Path(logits_file).write_text(json.dumps(logits, indent=2))
|
| 106 |
+
|
| 107 |
+
return preds_file, logits_file
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def upload_results(token: str, upload_files: list, repo_id: str):
|
| 111 |
+
logging.info("Logging into Hugging Face Hub...")
|
| 112 |
+
login(token)
|
| 113 |
+
api = HfApi()
|
| 114 |
+
for file_path in upload_files:
|
| 115 |
+
logging.info(f"Uploading {file_path} to {repo_id}")
|
| 116 |
+
api.upload_file(
|
| 117 |
+
path_or_fileobj=file_path,
|
| 118 |
+
path_in_repo=Path(file_path).name,
|
| 119 |
+
repo_id=repo_id,
|
| 120 |
+
repo_type="dataset",
|
| 121 |
+
)
|
| 122 |
+
logging.info("Upload complete.")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def main():
|
| 126 |
+
parser = argparse.ArgumentParser(
|
| 127 |
+
description="Evaluate InternVideo2 sliding-window retrieval."
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--num_frames",
|
| 131 |
+
type=int,
|
| 132 |
+
default=None,
|
| 133 |
+
help="Manually set the number of frames per window."
|
| 134 |
+
)
|
| 135 |
+
args = parser.parse_args()
|
| 136 |
+
|
| 137 |
+
setup_logging()
|
| 138 |
+
|
| 139 |
+
# ensure IV2 repo
|
| 140 |
+
iv2_path = Path('~/IV2').expanduser()
|
| 141 |
+
if not iv2_path.exists():
|
| 142 |
+
logging.info("Cloning IV2 repository...")
|
| 143 |
+
run_command('git clone https://github.com/qingy1337/IV2.git ~/IV2')
|
| 144 |
+
|
| 145 |
+
os.chdir(iv2_path / 'InternVideo2' / 'multi_modality')
|
| 146 |
+
sys.path.append(os.getcwd())
|
| 147 |
+
run_command('git checkout fix-6b', cwd=os.getcwd())
|
| 148 |
+
|
| 149 |
+
MODEL_NAME = '6B'
|
| 150 |
+
vision_ckpt = download_checkpoint(
|
| 151 |
+
repo_id="OpenGVLab/InternVideo2-Stage2_6B-224p-f4",
|
| 152 |
+
filename="internvideo2-s2_6b-224p-f4.pt"
|
| 153 |
+
)
|
| 154 |
+
config = load_config('scripts/pretraining/stage2/6B/config.py', vision_ckpt)
|
| 155 |
+
from demo.utils import setup_internvideo2
|
| 156 |
+
model, tokenizer = setup_internvideo2(config)
|
| 157 |
+
|
| 158 |
+
if not Path('photography-model').exists():
|
| 159 |
+
run_command('git clone https://github.com/ruo2019/photography-model.git')
|
| 160 |
+
|
| 161 |
+
prefix = f"ACT75-V5-InternVideo-{MODEL_NAME}"
|
| 162 |
+
preds_file, logits_file = process_videos(
|
| 163 |
+
'photography-model/rustyjar/ACT75.json',
|
| 164 |
+
model, config, prefix,
|
| 165 |
+
num_frames_override=args.num_frames
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
upload_results(
|
| 169 |
+
os.getenv('HF_TOKEN', ''),
|
| 170 |
+
[preds_file, logits_file],
|
| 171 |
+
'qingy2024/InternVideo2-Data'
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if __name__ == '__main__':
|
| 176 |
+
main()
|