zirobtc's picture
Upload full project with correct structure
5acc797 verified
import json
from collections import defaultdict
import numpy as np
TRAIN_JSON_PATH = "./data/miko/train.json"
ACTION_STATS_PATH = "./data/action_statistics.json"
# Constants to prevent instability
MIN_TOTAL_LEN = 1.0 # Floor duration to prevent infinite weights
MAX_WEIGHT = 0.05 # Cap max weight to avoid domination
# Load train.json
with open(TRAIN_JSON_PATH, "r") as f:
dataset = json.load(f)
# Load existing stats if available
try:
with open(ACTION_STATS_PATH, "r") as f:
existing_stats = json.load(f)
except FileNotFoundError:
existing_stats = {}
# Initialize merged stats
merged_stats = defaultdict(lambda: {"total_len": 0.0, "total_weight": 1})
# Copy existing values
for act, stats in existing_stats.items():
merged_stats[act]["total_len"] = stats.get("total_len", 0.0)
merged_stats[act]["total_weight"] = 1
# Aggregate durations from dataset
for entry in dataset:
labels = entry.get("frame_ann", {}).get("labels", [])
for label in labels:
start = label.get("start_t")
end = label.get("end_t")
act_cats = label.get("act_cat", [])
if start is None or end is None:
continue
duration = max(0.01, end - start)
for act in act_cats:
merged_stats[act]["total_len"] += duration
# Recompute weights
cleaned_stats = {}
for act, stats in merged_stats.items():
total_len = max(MIN_TOTAL_LEN, stats["total_len"]) # Floor to avoid tiny durations
if np.isfinite(total_len):
raw_weight = 1.0 / total_len
weight = min(raw_weight, MAX_WEIGHT) # Cap max weight
cleaned_stats[act] = {
"total_len": total_len,
"total_weight": 1,
"weight": weight
}
else:
print(f"⚠️ Skipping act_cat '{act}' due to invalid total_len={stats['total_len']}")
# Normalize weights
total_weight_sum = sum(stats["weight"] for stats in cleaned_stats.values())
if total_weight_sum == 0:
raise ValueError("❌ All weights are zero. Check act_cat labels or durations.")
for stats in cleaned_stats.values():
stats["weight"] /= total_weight_sum
# Save updated statistics
with open(ACTION_STATS_PATH, "w") as f:
json.dump(cleaned_stats, f, indent=2)
print(f"✅ Saved {len(cleaned_stats)} act_cat entries to {ACTION_STATS_PATH}")
print(f"🎯 Final normalized weight sum: {sum(stats['weight'] for stats in cleaned_stats.values()):.4f}")