Datasets:

Modalities:
Image
Languages:
Bengali
Size:
< 1K
Tags:
math
DOI:
Libraries:
Datasets
License:
azminetoushikwasi commited on
Commit
61802a9
·
verified ·
1 Parent(s): ddba9e8

Delete bcs-math/check_dataset.py

Browse files
Files changed (1) hide show
  1. bcs-math/check_dataset.py +0 -241
bcs-math/check_dataset.py DELETED
@@ -1,241 +0,0 @@
1
- # Cohere For AI Community, Danylo Boiko, 2024
2
-
3
- import os
4
- import json
5
- import argparse
6
-
7
- from typing import Union, Literal, Optional
8
-
9
- from pydantic import BaseModel, ValidationError, field_validator, model_validator
10
- from pydantic_core.core_schema import ValidationInfo
11
- from rich.console import Console
12
- from rich.panel import Panel
13
- from rich.syntax import Syntax
14
- from rich.text import Text
15
- from rich.tree import Tree
16
-
17
-
18
- MIN_OPTIONS_COUNT = 4
19
-
20
-
21
- class EntrySchema(BaseModel):
22
- language: str
23
- country: str
24
- file_name: str
25
- source: str
26
- license: str
27
- level: str
28
- category_en: str
29
- category_original_lang: str
30
- original_question_num: Union[int, str]
31
- question: str
32
- options: list[str]
33
- answer: int
34
- image_png: Optional[str]
35
- image_information: Optional[Literal["useful", "essential"]]
36
- image_type: Optional[Literal["graph", "table", "diagram", "scientific formula", "text", "figure", "map", "photo"]]
37
- parallel_question_id: Optional[tuple[str, int]]
38
-
39
- @staticmethod
40
- def _validate_string(value: str) -> str:
41
- if not value.strip():
42
- raise ValueError("Value cannot be empty or whitespace")
43
-
44
- if value.startswith(" ") or value.endswith(" "):
45
- raise ValueError("Value cannot have leading or trailing spaces")
46
-
47
- return value
48
-
49
- @staticmethod
50
- def _validate_image(image_name: str, config: ValidationInfo) -> None:
51
- images_path = config.context.get("images_path")
52
-
53
- if os.path.basename(image_name) != image_name:
54
- raise ValueError(f"The image name '{image_name}' must not include directories")
55
-
56
- if not os.path.isfile(os.path.join(images_path, image_name)):
57
- raise ValueError(f"The specified image '{image_name}' does not exist in {images_path}")
58
-
59
- @field_validator("language")
60
- def validate_language(cls, language: str, config: ValidationInfo) -> str:
61
- dataset_language = config.context.get("dataset_language")
62
-
63
- if language != dataset_language:
64
- raise ValueError(f"Expected '{dataset_language}', but got '{language}'")
65
-
66
- return cls._validate_string(language)
67
-
68
- @field_validator("options")
69
- def validate_options(cls, options: list[str], config: ValidationInfo) -> list[str]:
70
- for option in options:
71
- cls._validate_string(option)
72
-
73
- if option.lower().endswith(".png"):
74
- cls._validate_image(option, config)
75
-
76
- if len(options) < MIN_OPTIONS_COUNT:
77
- raise ValueError(f"Expected at least {MIN_OPTIONS_COUNT} options, but got {len(options)}")
78
-
79
- if len(set(options)) != len(options):
80
- raise ValueError("All values must be unique")
81
-
82
- return options
83
-
84
- @field_validator("answer")
85
- def validate_answer(cls, answer: int, config: ValidationInfo) -> int:
86
- options_count = len(config.data.get("options", []))
87
-
88
- if options_count > 0 and not (0 <= answer < options_count):
89
- raise ValueError(f"Expected value from 0 to {options_count - 1}, but got {answer}")
90
-
91
- return answer
92
-
93
- @field_validator("image_png")
94
- def validate_image_png(cls, image_png: Optional[str], config: ValidationInfo) -> Optional[str]:
95
- if isinstance(image_png, str):
96
- cls._validate_string(image_png)
97
-
98
- if not image_png.lower().endswith(".png"):
99
- raise ValueError(f"The file '{image_png}' is not a PNG image")
100
-
101
- cls._validate_image(image_png, config)
102
-
103
- return image_png
104
-
105
- @field_validator("parallel_question_id")
106
- def validate_parallel_question_id(cls, parallel_question_id: Optional[tuple[str, int]]) -> Optional[tuple[str, int]]:
107
- if isinstance(parallel_question_id, tuple) and isinstance(parallel_question_id[0], str):
108
- cls._validate_string(parallel_question_id[0])
109
-
110
- return parallel_question_id
111
-
112
- @field_validator(
113
- "country", "file_name", "source", "license", "level", "category_en",
114
- "category_original_lang", "original_question_num", "question"
115
- )
116
- def validate_string_fields(cls, value: Optional[str]) -> Optional[str]:
117
- return cls._validate_string(value) if isinstance(value, str) else value
118
-
119
- @model_validator(mode="after")
120
- def validate_image_data(cls, model: "EntrySchema") -> "EntrySchema":
121
- image_data = [model.image_png, model.image_information, model.image_type]
122
-
123
- if any(image_data) and not all(image_data):
124
- raise ValueError(
125
- "All fields related to image data (prefixed with 'image_') must be specified if any one of them is specified"
126
- )
127
-
128
- return model
129
-
130
- class Config:
131
- extra = "forbid"
132
-
133
-
134
- class EntryError:
135
- def __init__(self, index: int, message: str, location: Optional[tuple] = None) -> None:
136
- self.index = index
137
- self.message = message
138
- self.location = location
139
-
140
- def __str__(self) -> str:
141
- message = self.message.removeprefix("Value error, ")
142
-
143
- if self.location:
144
- location = str(self.location).strip(",()")
145
- return f"Location: {location}, error: {message.lower()}"
146
-
147
- return message
148
-
149
-
150
- class DatasetValidator:
151
- def __init__(self, json_file: str, language_code: str) -> None:
152
- self.json_file: str = json_file
153
- self.json_entries: list[dict] = []
154
- self.language_code: str = language_code.lower()
155
- self.images_path: str = os.path.join(os.path.dirname(json_file), "images")
156
- self.console: Console = Console()
157
- self.errors: list[EntryError] = []
158
-
159
- def validate(self) -> None:
160
- self.console.print("Starting validation...", style="green")
161
- self.console.print(f"JSON file: {self.json_file}", style="cyan")
162
- self.console.print(f"Images path: {self.images_path}", style="cyan")
163
- self.console.print(f"Language code: {self.language_code}", style="cyan")
164
-
165
- if not self._load_json():
166
- return
167
-
168
- self._validate_entries()
169
- self._print_validation_report()
170
-
171
- def _load_json(self) -> bool:
172
- try:
173
- with open(self.json_file, "r", encoding="utf-8") as file:
174
- entries = json.load(file)
175
-
176
- if not isinstance(entries, list):
177
- raise ValueError("The file must contain a JSON array (list of entries)")
178
-
179
- self.json_entries = entries
180
- return True
181
- except Exception as e:
182
- self.console.print(f"Error loading file {self.json_file}: {e}", style="red")
183
- return False
184
-
185
- def _validate_entries(self) -> None:
186
- seen_entries = {}
187
-
188
- for index, entry in enumerate(self.json_entries):
189
- try:
190
- entry_model = EntrySchema.model_validate(entry, context={
191
- "dataset_language": self.language_code,
192
- "images_path": self.images_path,
193
- })
194
-
195
- entry_hash = (entry_model.question, tuple(option for option in entry_model.options))
196
-
197
- if entry_hash not in seen_entries:
198
- seen_entries[entry_hash] = index
199
- else:
200
- self.errors.append(EntryError(index, f"Duplicate of entry with index {seen_entries[entry_hash]}"))
201
- except ValidationError as e:
202
- self.errors.extend([
203
- EntryError(index, error.get("msg"), error.get("loc", None)) for error in e.errors()
204
- ])
205
-
206
- def _print_validation_report(self) -> None:
207
- if len(self.errors) == 0:
208
- return self.console.print("Congratulations, the JSON file is valid!", style="green")
209
-
210
- self.console.print("The following errors were found, fix them and try again:", style="red")
211
-
212
- for error in self.errors:
213
- self.console.print(Panel(self._create_error_tree(error), expand=False, border_style="red"))
214
-
215
- def _create_error_tree(self, error: EntryError) -> Tree:
216
- entry = self.json_entries[error.index]
217
-
218
- tree = Tree(f"Error in entry with index {error.index}", style="red")
219
- tree.add(Text(str(error), style="yellow"))
220
-
221
- question_node = tree.add("Question")
222
- question_node.add(Syntax(entry.get("question", "N/A"), "text", word_wrap=True))
223
-
224
- options_node = tree.add("Options")
225
- for option_num, option_value in enumerate(entry.get("options", []), 1):
226
- options_node.add(f"{option_num}. {option_value}")
227
-
228
- answer_node = tree.add("Answer")
229
- answer_node.add(str(entry.get("answer", "N/A")))
230
-
231
- return tree
232
-
233
-
234
- if __name__ == '__main__':
235
- parser = argparse.ArgumentParser()
236
- parser.add_argument("--json_file", type=str, required=True, help="Path to the JSON file to be validated")
237
- parser.add_argument("--language_code", type=str, required=True, help="The language code for the dataset")
238
- args = parser.parse_args()
239
-
240
- validator = DatasetValidator(args.json_file, args.language_code)
241
- validator.validate()