File size: 4,660 Bytes
ff68b4e
 
 
6f0bb8a
ff68b4e
 
 
 
6f0bb8a
ff68b4e
6f0bb8a
ff68b4e
 
 
 
 
6f0bb8a
ff68b4e
 
 
 
 
 
 
 
 
 
 
 
79c4323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff68b4e
6f0bb8a
ff68b4e
 
6f0bb8a
 
ff68b4e
 
 
79c4323
 
6f0bb8a
79c4323
 
ff68b4e
79c4323
 
 
 
 
 
 
 
ff68b4e
79c4323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff68b4e
 
 
 
 
 
 
79c4323
 
 
 
 
 
 
 
 
 
 
 
 
 
ff68b4e
 
 
 
 
 
 
 
 
 
 
6f0bb8a
 
ff68b4e
6f0bb8a
ff68b4e
 
 
6f0bb8a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import json
import os
from datasets import Dataset, Image
from transformers import CLIPProcessor, CLIPModel, AutoTokenizer, AutoModel
from PIL import Image as PILImage
import torch
from tqdm import tqdm

def preprocess_multimodal_data(raw_json_path, image_dir, dataset_name, text_model_name, clip_model_name, output_dir):
    """
    Preprocesses raw JSON and image data into a Hugging Face Dataset, using DeepSeek-R1 for text embeddings.

    Args:
        raw_json_path (str): Path to the raw JSON file.
        image_dir (str): Directory containing the images.
        dataset_name (str): Name of the Hugging Face Dataset.
        text_model_name (str): Name of the text model (DeepSeek-R1) from Hugging Face Transformers.
        clip_model_name (str): Name of the CLIP model from Hugging Face Transformers.
        output_dir (str): Directory where the dataset repository will be saved.
    """

    # Load data from JSON
    with open(raw_json_path, 'r') as f:
        data = json.load(f)

    # Initialize lists to store data
    images = []
    questions = []
    answers = []
    ids = []
    subjects = []
    topics = []
    options = []
    certification_levels = []
    difficulty_levels = []
    grade_levels = []
    learning_objectives = []
    question_types = []
    time_requireds = []
    keywords_list = []
    sources = []
    years = []
    sections = []
    languages = []

    # Load CLIP, DeepSeek-R1, and Tokenizer
    clip_processor = CLIPProcessor.from_pretrained(clip_model_name)
    clip_model = CLIPModel.from_pretrained(clip_model_name).to("cuda")
    text_model = AutoModel.from_pretrained(text_model_name).to("cuda")
    tokenizer = AutoTokenizer.from_pretrained(text_model_name)

    # Process each data point
    for i, item in enumerate(tqdm(data, desc="Processing data")):
        question = item.get('question', '')
        answer = item.get('answer', '')
        image = None
        image_path = item.get('image', None)
        id_field = str(i)

        if image_path:
            try:
                full_image_path = os.path.join(image_dir, image_path)
                image = PILImage.open(full_image_path).convert("RGB")
            except FileNotFoundError:
                print(f"Warning: Image not found at {full_image_path}")
            except Exception as e:
                print(f"Warning: Error processing image {full_image_path}: {e}")

        images.append(image)
        questions.append(question)
        answers.append(answer)
        ids.append(id_field)
        subjects.append(item.get('subject', None))
        topics.append(item.get('topic', None))
        options.append(item.get('options', None))
        certification_levels.append(item.get('certification_level', None))
        difficulty_levels.append(item.get('difficulty_level', None))
        grade_levels.append(item.get('grade_level', None))
        learning_objectives.append(item.get('learning_objective', None))
        question_types.append(item.get('question_type', None))
        time_requireds.append(item.get('time_required', None))
        keywords_list.append(item.get('keywords', None))
        sources.append(item.get('source', None))
        years.append(item.get('year', None))
        sections.append(item.get('section', None))
        languages.append(item.get('language', None))

    # Create Hugging Face Dataset
    dataset_dict = {
        'image': images,
        'question': questions,
        'answer': answers,
        'id': ids,
        'subject': subjects,
        'topic': topics,
        'options': options,
        'certification_level': certification_levels,
        'difficulty_level': difficulty_levels,
        'grade_level': grade_levels,
        'learning_objective': learning_objectives,
        'question_type': question_types,
        'time_required': time_requireds,
        'keywords': keywords_list,
        'source': sources,
        'year': years,
        'section': sections,
        'language': languages,
    }

    dataset = Dataset.from_dict(dataset_dict)
    dataset = dataset.cast_column("image", Image())

    # Save to Hugging Face Dataset repository
    dataset.save_to_disk(os.path.join(output_dir, dataset_name))

    print(f"Dataset '{dataset_name}' saved to {os.path.join(output_dir, dataset_name)}")

# Example Usage:
raw_json_path = 'your_data.json'
image_dir = 'your_image_dir'
dataset_name = 'my_multimodal_dataset'
text_model_name = 'deepseek-ai/deepseek-rl-7b-chat' #Deepseek R1
clip_model_name = 'openai/clip-vit-base-patch32'
output_dir = 'my_datasets'

preprocess_multimodal_data(raw_json_path, image_dir, dataset_name, text_model_name, clip_model_name, output_dir)