dataomni / Monkeypox /extract_unique_questions.py
Luxuriant16's picture
Add files using upload-large-folder tool
7fe89e2 verified
import json
import os
import random
import csv
from typing import List, Dict
from PIL import Image
def get_random_image_path(answer: str) -> str:
"""
Get a random image path from the correct Monkeypox/images subdirectory based on the answer.
Avoid images already used in the original JSON.
Save with linux-style path.
"""
# Map answer to directory
answer_to_dir = {
'Chickenpox': 'Monkeypox/images/chickenpox',
'Cowpox': 'Monkeypox/images/cowpox',
'Dermoscopy.': 'Monkeypox/images', # All images in all subfolders
'Measles': 'Monkeypox/images/measles',
'Monkeypox': 'Monkeypox/images/monkeypox',
'No': 'Monkeypox/images/healthy',
'Smallpox': 'Monkeypox/images/smallpox',
}
if answer not in answer_to_dir:
raise ValueError(f"Unknown answer type: {answer}")
# Load existing image filenames from the original JSON file
with open('../Original_open/Monkeypox Skin Image 2022.json', 'r') as f:
original_data = json.load(f)
# Extract just the filename (e.g., ch_0001.jpg) from the image_path
used_filenames = {os.path.basename(item['image_path']) for item in original_data}
# For Dermoscopy., collect all images from all subfolders
if answer == 'Dermoscopy.':
all_dirs = [
'Monkeypox/images/chickenpox',
'Monkeypox/images/cowpox',
'Monkeypox/images/measles',
'Monkeypox/images/monkeypox',
'Monkeypox/images/healthy',
'Monkeypox/images/smallpox',
]
all_files = []
for d in all_dirs:
for fname in os.listdir(d):
if fname.lower().endswith('.jpg'):
all_files.append((d, fname))
candidates = [(d, f) for d, f in all_files if f not in used_filenames]
if not candidates:
raise ValueError(f"No unused images found for answer: {answer}")
chosen_dir, chosen_file = random.choice(candidates)
return f"{chosen_dir}/{chosen_file}"
else:
image_dir = answer_to_dir[answer]
all_files = [f for f in os.listdir(image_dir) if f.lower().endswith('.jpg')]
candidates = [f for f in all_files if f not in used_filenames]
if not candidates:
raise ValueError(f"No unused images found for answer: {answer}")
chosen_file = random.choice(candidates)
return f"{image_dir}/{chosen_file}"
def extract_unique_questions(json_data: List[Dict]) -> Dict[str, Dict]:
"""
Extract unique questions from the JSON data where questions with different answers are considered different.
Saves the complete original question item for each unique question.
Args:
json_data (List[Dict]): List of dictionaries containing question data
Returns:
Dict[str, Dict]: Dictionary mapping unique questions to their complete original items
"""
unique_questions = {}
for item in json_data:
question = item['question']
answer = item['gt_answer']
# Create a key that combines question and answer to ensure uniqueness
key = f"{question}|{answer}"
if key not in unique_questions:
# Create a copy of the item to avoid modifying the original
new_item = item.copy()
# Replace the image path with a random one based on the answer
new_item['image_path'] = get_random_image_path(answer)
unique_questions[key] = new_item
return unique_questions
def extend_to_100_questions(unique_questions: Dict[str, Dict]) -> List[Dict]:
"""
Extend the number of questions to 100 by randomly duplicating existing questions.
Args:
unique_questions (Dict[str, Dict]): Dictionary of unique questions
Returns:
List[Dict]: List of 100 questions
"""
questions_list = list(unique_questions.values())
current_count = len(questions_list)
# If we already have more than 100 questions, just return the first 100
if current_count >= 200:
return questions_list#[:100]
# Calculate how many more questions we need
needed = 200 - current_count
# Randomly select questions to duplicate
for _ in range(needed):
# Select a random question
random_question = random.choice(questions_list)
# Create a copy of the question
new_question = random_question.copy()
# Generate a new random image path based on the answer
new_question['image_path'] = get_random_image_path(new_question['gt_answer'])
# Add to the list
questions_list.append(new_question)
return questions_list
def refill_question_ids(questions: List[Dict]) -> List[Dict]:
"""
Refill question_ids with sequential IDs.
Args:
questions (List[Dict]): List of questions
Returns:
List[Dict]: List of questions with sequential IDs
"""
for i, question in enumerate(questions):
# Format the ID with leading zeros to maintain 4 digits
question['question_id'] = f"Monkeypox_{i:04d}"
return questions
def main():
# Set random seed for reproducibility
random.seed(42)
# First convert all BMP images to JPG
# convert_bmp_to_jpg()
# Read the JSON file
with open('../Original_open/Monkeypox Skin Image 2022.json', 'r') as f:
data = json.load(f)
# Print all unique answers
unique_answers = set(item['gt_answer'] for item in data)
print("\nUnique answers in the original file:")
for answer in sorted(unique_answers):
print(f"- {answer}")
print(f"\nTotal number of unique answers: {len(unique_answers)}")
# Extract unique questions
unique_questions = extract_unique_questions(data)
# Save the unique questions first
unique_questions_list = list(unique_questions.values())
with open('Monkeypox/monkeypox_unique_questions_original.json', 'w') as f:
json.dump(unique_questions_list, f, indent=4)
print(f"\nOriginal unique questions have been saved to 'Monkeypox/monkeypox_unique_questions_original.json'")
print(f"Number of unique questions: {len(unique_questions_list)}")
# Extend to 100 questions
extended_questions = extend_to_100_questions(unique_questions)
# Refill question IDs sequentially
final_questions = refill_question_ids(extended_questions)
# Save the extended questions to a new JSON file
with open('Monkeypox/monkeypox_unique_questions_extended.json', 'w') as f:
json.dump(final_questions, f, indent=4)
print(f"\nExtended questions have been saved to 'Monkeypox/monkeypox_unique_questions_extended.json'")
print(f"Extended to {len(final_questions)} questions")
if __name__ == "__main__":
main()