episodic_dataset / reformat_ann.py
ruisent2's picture
Upload folder using huggingface_hub
a7530e6 verified
Raw
History Blame Contribute Delete
5.52 kB
import json
from collections import defaultdict
import os
import re
def parse_multiple_choice_query(query_text):
"""
Parse a multiple choice query to extract the question and choices.
Example input: "What happened first? A. cut or chop or slice a vegetable, fruit, or meat; B.wash vegetable or fruit or food item"
Returns: question, choices_list
"""
# Split by '?' to separate question from choices
parts = query_text.split('?', 1)
if len(parts) != 2:
raise ValueError(f"Invalid query format: {query_text}")
question = parts[0].strip() + '?'
choices_part = parts[1].strip()
# Parse choices using regex to find A. ... B. ... pattern
choice_pattern = r'([AB]\.\s*[^;]+?)(?=\s*[AB]\.|$)'
matches = re.findall(choice_pattern, choices_part)
if len(matches) != 2:
# Fallback: split by '; ' and clean up
choice_parts = choices_part.split(';')
choices = []
for part in choice_parts:
part = part.strip()
if part.startswith(('A.', 'B.')):
choices.append(part)
if len(choices) != 2:
raise ValueError(f"Could not parse choices from: {choices_part}")
else:
choices = [match.strip() for match in matches]
return question, choices
def reformat_annotations(input_file, output_file, video_folder, is_multiple_choice=False):
"""
Reformat the annotation file to group queries by video_uid.
Args:
input_file: Path to the input JSON file
output_file: Path to the output JSON file
video_folder: Path to the video folder
is_multiple_choice: Whether this is a multiple choice dataset (order queries)
"""
# Load the original data
with open(input_file, 'r') as f:
original_data = json.load(f)
# Group queries by video_uid
video_groups = defaultdict(list)
for item in original_data:
video_uid = item['video_uid']
if is_multiple_choice:
# Parse multiple choice query
try:
question, choices = parse_multiple_choice_query(item['query'])
conversation_item = {
'question': question,
'choices': choices,
'answer': item['answer'].replace('"', ''),
'question_type': item['type']
}
except ValueError as e:
print(f"Error parsing query: {e}")
print(f"Original query: {item['query']}")
continue
else:
# Regular yes/no query
conversation_item = {
'question': item['query'],
'answer': item['answer'],
'question_type': item['type']
}
video_groups[video_uid].append(conversation_item)
# Create the new format
reformatted_data = []
for video_uid, conversations in video_groups.items():
assert not video_uid.endswith(".mp4"), f"Video UID {video_uid} should not end with .mp4"
video_path = os.path.join(video_folder, video_uid + ".mp4")
video_dict = {
'video_id': video_uid,
'video_path': video_path,
'conversations': conversations
}
reformatted_data.append(video_dict)
# Save the reformatted data
with open(output_file, 'w') as f:
json.dump(reformatted_data, f, indent=4)
print(f"Reformatted {len(original_data)} queries from {len(reformatted_data)} videos")
print(f"Output saved to: {output_file}")
def examine_dataset(input_file):
with open(input_file, 'r') as f:
data = json.load(f)
for item in data:
for conversation in item['conversations']:
if 'choices' in conversation:
assert len(conversation['choices']) == 2
assert conversation['answer'] in conversation['choices'], f"Answer {conversation['answer']} is not in choices {conversation['choices']}"
else:
assert conversation['answer'] in ['Yes', 'No']
if __name__ == "__main__":
# # Appearance queries (yes/no questions)
# appearance_types = ["object_appearance", "action_appearance"]
# for question_type in appearance_types:
# video_folder = f"/shared/nas2/yaox11/ruisen/Episodic_Dataset/{question_type}"
# input_file = f"{question_type}_queries_final.json"
# output_file = f"{question_type}_queries_reformatted.json"
# reformat_annotations(input_file, output_file, video_folder, is_multiple_choice=False)
# # Order queries (multiple choice questions)
# order_types = ["object_order", "action_order"]
# for question_type in order_types:
# video_folder = f"/shared/nas2/yaox11/ruisen/Episodic_Dataset/{question_type}"
# input_file = f"{question_type}_queries_final.json"
# output_file = f"{question_type}_queries_reformatted.json"
# reformat_annotations(input_file, output_file, video_folder, is_multiple_choice=True)
examine_dataset("/shared/nas2/yaox11/ruisen/Episodic_Dataset/object_appearance_queries_reformatted.json")
examine_dataset("/shared/nas2/yaox11/ruisen/Episodic_Dataset/action_appearance_queries_reformatted.json")
examine_dataset("/shared/nas2/yaox11/ruisen/Episodic_Dataset/object_order_queries_reformatted.json")
examine_dataset("/shared/nas2/yaox11/ruisen/Episodic_Dataset/action_order_queries_reformatted.json")