Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
parquet
Languages:
Portuguese
Size:
1K - 10K
License:
Introduce JBCS split
#7
by
abarbosa - opened
- aes_enem_dataset.py +479 -163
- pyproject.toml +1 -0
aes_enem_dataset.py
CHANGED
|
@@ -15,16 +15,18 @@
|
|
| 15 |
import csv
|
| 16 |
import math
|
| 17 |
import os
|
| 18 |
-
from pathlib import Path
|
| 19 |
import re
|
|
|
|
| 20 |
|
| 21 |
import datasets
|
| 22 |
import numpy as np
|
| 23 |
import pandas as pd
|
|
|
|
| 24 |
from bs4 import BeautifulSoup
|
| 25 |
from tqdm.auto import tqdm
|
| 26 |
|
| 27 |
-
|
|
|
|
| 28 |
|
| 29 |
_CITATION = """
|
| 30 |
@inproceedings{silveira-etal-2024-new,
|
|
@@ -79,7 +81,7 @@ _URLS = {
|
|
| 79 |
"sourceAWithGraders": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceAWithGraders.tar.gz",
|
| 80 |
"sourceB": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceB.tar.gz",
|
| 81 |
"PROPOR2024": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/propor2024.tar.gz",
|
| 82 |
-
"gradesThousand": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/scrapedGradesThousand.tar.gz"
|
| 83 |
}
|
| 84 |
|
| 85 |
|
|
@@ -109,7 +111,7 @@ CSV_HEADER = [
|
|
| 109 |
"general",
|
| 110 |
"specific",
|
| 111 |
"essay_year",
|
| 112 |
-
"reference"
|
| 113 |
]
|
| 114 |
|
| 115 |
CSV_HEADERPROPOR = [
|
|
@@ -119,7 +121,7 @@ CSV_HEADERPROPOR = [
|
|
| 119 |
"essay",
|
| 120 |
"grades",
|
| 121 |
"essay_year",
|
| 122 |
-
"reference"
|
| 123 |
]
|
| 124 |
|
| 125 |
CSV_HEADERTHOUSAND = [
|
|
@@ -131,6 +133,18 @@ CSV_HEADERTHOUSAND = [
|
|
| 131 |
"essay",
|
| 132 |
"source",
|
| 133 |
"supporting_text",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
]
|
| 135 |
|
| 136 |
SOURCE_A_DESC = """
|
|
@@ -183,6 +197,10 @@ GRADES_THOUSAND = """
|
|
| 183 |
TODO
|
| 184 |
"""
|
| 185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
| 188 |
"""
|
|
@@ -192,25 +210,34 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 192 |
To reproduce results from PROPOR paper, please refer to "PROPOR2024" config. Other configs are reproducible now.
|
| 193 |
"""
|
| 194 |
|
| 195 |
-
VERSION = datasets.Version("0.
|
| 196 |
|
| 197 |
# You will be able to load one or the other configurations in the following list with
|
| 198 |
BUILDER_CONFIGS = [
|
| 199 |
-
datasets.BuilderConfig(name="sourceAOnly", version=VERSION, description=SOURCE_A_DESC),
|
| 200 |
datasets.BuilderConfig(
|
| 201 |
-
name="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
),
|
| 203 |
datasets.BuilderConfig(
|
| 204 |
name="sourceB",
|
| 205 |
version=VERSION,
|
| 206 |
description=SOURCE_B_DESC,
|
| 207 |
),
|
| 208 |
-
datasets.BuilderConfig(
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
]
|
| 211 |
|
| 212 |
def _info(self):
|
| 213 |
-
if self.config.name=="PROPOR2024":
|
| 214 |
features = datasets.Features(
|
| 215 |
{
|
| 216 |
"id": datasets.Value("string"),
|
|
@@ -222,18 +249,32 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 222 |
"reference": datasets.Value("string"),
|
| 223 |
}
|
| 224 |
)
|
| 225 |
-
elif self.config.name=="gradesThousand":
|
| 226 |
features = datasets.Features(
|
| 227 |
{
|
| 228 |
"id": datasets.Value("string"),
|
| 229 |
"id_prompt": datasets.Value("string"),
|
| 230 |
"supporting_text": datasets.Value("string"),
|
|
|
|
| 231 |
"essay_text": datasets.Value("string"),
|
| 232 |
"grades": datasets.Sequence(datasets.Value("int16")),
|
| 233 |
"essay_year": datasets.Value("int16"),
|
| 234 |
"source": datasets.Value("string"),
|
| 235 |
}
|
| 236 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
else:
|
| 238 |
features = datasets.Features(
|
| 239 |
{
|
|
@@ -275,7 +316,7 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 275 |
|
| 276 |
def normalize_grades(grades):
|
| 277 |
grades = grades.strip("[]").split(", ")
|
| 278 |
-
grade_mapping = {"0.0": 0, "20": 40}
|
| 279 |
|
| 280 |
# We will remove the rows that match the criteria below
|
| 281 |
if any(
|
|
@@ -308,19 +349,19 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 308 |
for split_case in ["train.csv", "validation.csv", "test.csv"]:
|
| 309 |
filepath = f"{base_path}/propor2024/{split_case}"
|
| 310 |
df = pd.read_csv(filepath)
|
| 311 |
-
|
| 312 |
# Dictionary to track how many times we've seen each (id, id_prompt) pair
|
| 313 |
counts = {}
|
| 314 |
# List to store the reference for each row
|
| 315 |
references = []
|
| 316 |
-
|
| 317 |
# Define the mapping for each occurrence
|
| 318 |
occurrence_to_reference = {
|
| 319 |
0: "crawled_from_web",
|
| 320 |
1: "grader_a",
|
| 321 |
-
2: "grader_b"
|
| 322 |
}
|
| 323 |
-
|
| 324 |
# Iterate through rows in the original order
|
| 325 |
for _, row in df.iterrows():
|
| 326 |
key = (row["id"], row["id_prompt"])
|
|
@@ -329,14 +370,15 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 329 |
ref = occurrence_to_reference.get(count, "unknown")
|
| 330 |
references.append(ref)
|
| 331 |
counts[key] = count + 1
|
| 332 |
-
|
| 333 |
# Add the reference column without changing the order of rows
|
| 334 |
df["reference"] = references
|
| 335 |
df.to_csv(filepath, index=False)
|
| 336 |
|
| 337 |
def _split_generators(self, dl_manager):
|
| 338 |
-
|
| 339 |
-
|
|
|
|
| 340 |
if "PROPOR2024" == self.config.name:
|
| 341 |
base_path = extracted_files["PROPOR2024"]
|
| 342 |
self._preprocess_propor2024(base_path)
|
|
@@ -353,7 +395,9 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 353 |
name=datasets.Split.VALIDATION,
|
| 354 |
# These kwargs will be passed to _generate_examples
|
| 355 |
gen_kwargs={
|
| 356 |
-
"filepath": os.path.join(
|
|
|
|
|
|
|
| 357 |
"split": "validation",
|
| 358 |
},
|
| 359 |
),
|
|
@@ -366,7 +410,20 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 366 |
),
|
| 367 |
]
|
| 368 |
if "gradesThousand" == self.config.name:
|
| 369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
return [
|
| 371 |
datasets.SplitGenerator(
|
| 372 |
name=datasets.Split.TRAIN,
|
|
@@ -392,17 +449,17 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 392 |
},
|
| 393 |
),
|
| 394 |
]
|
| 395 |
-
html_parser = self._process_html_files(extracted_files)
|
| 396 |
if "sourceA" in self.config.name:
|
|
|
|
| 397 |
self._post_process_dataframe(html_parser.sourceA)
|
| 398 |
self._generate_splits(html_parser.sourceA)
|
| 399 |
-
folder_sourceA =
|
| 400 |
return [
|
| 401 |
datasets.SplitGenerator(
|
| 402 |
name=datasets.Split.TRAIN,
|
| 403 |
# These kwargs will be passed to _generate_examples
|
| 404 |
gen_kwargs={
|
| 405 |
-
"filepath":
|
| 406 |
"split": "train",
|
| 407 |
},
|
| 408 |
),
|
|
@@ -410,19 +467,20 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 410 |
name=datasets.Split.VALIDATION,
|
| 411 |
# These kwargs will be passed to _generate_examples
|
| 412 |
gen_kwargs={
|
| 413 |
-
"filepath":
|
| 414 |
"split": "validation",
|
| 415 |
},
|
| 416 |
),
|
| 417 |
datasets.SplitGenerator(
|
| 418 |
name=datasets.Split.TEST,
|
| 419 |
gen_kwargs={
|
| 420 |
-
"filepath":
|
| 421 |
"split": "test",
|
| 422 |
},
|
| 423 |
),
|
| 424 |
]
|
| 425 |
elif self.config.name == "sourceB":
|
|
|
|
| 426 |
self._post_process_dataframe(html_parser.sourceB)
|
| 427 |
return [
|
| 428 |
datasets.SplitGenerator(
|
|
@@ -433,10 +491,155 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 433 |
},
|
| 434 |
),
|
| 435 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
|
| 437 |
-
def _process_html_files(self, paths_dict):
|
| 438 |
html_parser = HTMLParser(paths_dict)
|
| 439 |
-
|
|
|
|
|
|
|
| 440 |
return html_parser
|
| 441 |
|
| 442 |
def _parse_graders_data(self, dirname):
|
|
@@ -457,14 +660,19 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 457 |
grader_b["reference"] = "grader_b"
|
| 458 |
return grader_a, grader_b
|
| 459 |
|
| 460 |
-
def _generate_splits(self, filepath: str, train_size=0.7):
|
|
|
|
| 461 |
df = pd.read_csv(filepath)
|
| 462 |
-
buckets = df.groupby("mapped_year")["id_prompt"].unique().to_dict()
|
| 463 |
-
df.drop("mapped_year", axis=1, inplace=True)
|
| 464 |
train_set = []
|
| 465 |
val_set = []
|
| 466 |
test_set = []
|
| 467 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
np.random.shuffle(prompts)
|
| 469 |
num_prompts = len(prompts)
|
| 470 |
|
|
@@ -501,52 +709,67 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 501 |
val_df = pd.concat(val_set)
|
| 502 |
test_df = pd.concat(test_set)
|
| 503 |
dirname = os.path.dirname(filepath)
|
| 504 |
-
if
|
|
|
|
|
|
|
| 505 |
grader_a, grader_b = self._parse_graders_data(dirname)
|
| 506 |
grader_a_data = pd.merge(
|
| 507 |
-
train_df[["id", "id_prompt","essay", "prompt", "supporting_text"]],
|
| 508 |
-
grader_a.drop(columns=[
|
| 509 |
on=["id", "id_prompt"],
|
| 510 |
how="inner",
|
| 511 |
)
|
| 512 |
grader_b_data = pd.merge(
|
| 513 |
-
train_df[["id", "id_prompt","essay", "prompt", "supporting_text"]],
|
| 514 |
-
grader_b.drop(columns=[
|
| 515 |
on=["id", "id_prompt"],
|
| 516 |
how="inner",
|
| 517 |
)
|
| 518 |
-
train_df = pd.concat([train_df, grader_a_data])
|
| 519 |
-
train_df =
|
|
|
|
|
|
|
| 520 |
|
| 521 |
grader_a_data = pd.merge(
|
| 522 |
-
val_df[["id", "id_prompt","essay", "prompt", "supporting_text"]],
|
| 523 |
-
grader_a.drop(columns=[
|
| 524 |
on=["id", "id_prompt"],
|
| 525 |
how="inner",
|
| 526 |
)
|
| 527 |
grader_b_data = pd.merge(
|
| 528 |
-
val_df[["id", "id_prompt","essay", "prompt", "supporting_text"]],
|
| 529 |
-
grader_b.drop(columns=[
|
| 530 |
on=["id", "id_prompt"],
|
| 531 |
how="inner",
|
| 532 |
)
|
| 533 |
-
val_df = pd.concat([val_df, grader_a_data])
|
| 534 |
-
val_df =
|
| 535 |
|
| 536 |
grader_a_data = pd.merge(
|
| 537 |
-
test_df[["id", "id_prompt","essay", "prompt", "supporting_text"]],
|
| 538 |
-
grader_a.drop(columns=[
|
| 539 |
on=["id", "id_prompt"],
|
| 540 |
how="inner",
|
| 541 |
)
|
| 542 |
grader_b_data = pd.merge(
|
| 543 |
-
test_df[["id", "id_prompt","essay", "prompt", "supporting_text"]],
|
| 544 |
-
grader_b.drop(columns=[
|
| 545 |
on=["id", "id_prompt"],
|
| 546 |
how="inner",
|
| 547 |
)
|
| 548 |
-
test_df = pd.concat([test_df, grader_a_data])
|
| 549 |
-
test_df =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 550 |
# Data Validation Assertions
|
| 551 |
assert (
|
| 552 |
len(set(train_df["id_prompt"]).intersection(set(val_df["id_prompt"]))) == 0
|
|
@@ -570,15 +793,18 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 570 |
for i, row in enumerate(csv_reader):
|
| 571 |
grades = row["grades"].strip("[]")
|
| 572 |
grades = grades.split()
|
| 573 |
-
yield
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
|
|
|
|
|
|
|
|
|
| 582 |
elif self.config.name == "gradesThousand":
|
| 583 |
with open(filepath, encoding="utf-8") as csvfile:
|
| 584 |
next(csvfile)
|
|
@@ -586,16 +812,40 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 586 |
for i, row in enumerate(csv_reader):
|
| 587 |
grades = row["grades"].strip("[]")
|
| 588 |
grades = grades.split(", ")
|
| 589 |
-
yield
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
else:
|
| 600 |
with open(filepath, encoding="utf-8") as csvfile:
|
| 601 |
next(csvfile)
|
|
@@ -603,20 +853,22 @@ class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
|
| 603 |
for i, row in enumerate(csv_reader):
|
| 604 |
grades = row["grades"].strip("[]")
|
| 605 |
grades = grades.split(", ")
|
| 606 |
-
yield
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
|
|
|
|
|
|
| 620 |
|
| 621 |
|
| 622 |
class HTMLParser:
|
|
@@ -655,9 +907,9 @@ class HTMLParser:
|
|
| 655 |
for single_grade in grades:
|
| 656 |
grade = int(single_grade.get_text())
|
| 657 |
final_grades.append(grade)
|
| 658 |
-
assert final_grades[-1] == sum(
|
| 659 |
-
|
| 660 |
-
)
|
| 661 |
else:
|
| 662 |
grades = soup.find("div", class_="redacoes-corrigidas pg-bordercolor7")
|
| 663 |
grades_sum = float(
|
|
@@ -667,9 +919,9 @@ class HTMLParser:
|
|
| 667 |
for idx in range(1, 10, 2):
|
| 668 |
grade = float(grades[idx].get_text().replace(",", "."))
|
| 669 |
final_grades.append(grade)
|
| 670 |
-
assert grades_sum == sum(
|
| 671 |
-
|
| 672 |
-
)
|
| 673 |
final_grades.append(grades_sum)
|
| 674 |
return final_grades
|
| 675 |
elif self.sourceB:
|
|
@@ -680,7 +932,9 @@ class HTMLParser:
|
|
| 680 |
for single_grade in grades:
|
| 681 |
result.append(int(single_grade.get_text()))
|
| 682 |
assert len(result) == 5, "We should have 5 Grades (one per concept) only"
|
| 683 |
-
result.append(
|
|
|
|
|
|
|
| 684 |
return result
|
| 685 |
|
| 686 |
def _get_general_comment(self, soup):
|
|
@@ -787,7 +1041,10 @@ class HTMLParser:
|
|
| 787 |
span.decompose()
|
| 788 |
result = table.find_all("p")
|
| 789 |
result = " ".join(
|
| 790 |
-
[
|
|
|
|
|
|
|
|
|
|
| 791 |
)
|
| 792 |
return result
|
| 793 |
|
|
@@ -831,37 +1088,83 @@ class HTMLParser:
|
|
| 831 |
return new_list
|
| 832 |
|
| 833 |
def _clean_string(self, sentence):
|
| 834 |
-
sentence = sentence.replace("\xa0","").replace("\u200b","")
|
| 835 |
-
sentence =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 836 |
sentence = sentence.replace(" ", " ").replace(". . . ", "...")
|
| 837 |
-
sentence = sentence.replace("(editado)", "").replace("(Editado)","")
|
| 838 |
-
sentence = sentence.replace("(editado e adaptado)", "").replace(
|
|
|
|
|
|
|
| 839 |
sentence = sentence.replace(". com. br", ".com.br")
|
| 840 |
sentence = sentence.replace("[Veja o texto completo aqui]", "")
|
| 841 |
-
return sentence
|
| 842 |
|
| 843 |
def _get_supporting_text(self, soup):
|
| 844 |
if self.sourceA:
|
| 845 |
textos = soup.find_all("ul", class_="article-wording-item")
|
| 846 |
resposta = []
|
| 847 |
for t in textos[:-1]:
|
| 848 |
-
resposta.append(
|
| 849 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 850 |
return resposta
|
| 851 |
else:
|
| 852 |
return ""
|
| 853 |
-
|
| 854 |
def _get_prompt(self, soup):
|
| 855 |
if self.sourceA:
|
| 856 |
prompt = soup.find("div", class_="text").find_all("p")
|
| 857 |
if len(prompt[0].get_text()) < 2:
|
| 858 |
-
return [prompt[1].get_text().replace("\xa0","")]
|
| 859 |
else:
|
| 860 |
-
return [prompt[0].get_text().replace("\xa0","")]
|
| 861 |
-
else:
|
| 862 |
return ""
|
| 863 |
|
| 864 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
for key, filepath in self.paths_dict.items():
|
| 866 |
if key != config_name:
|
| 867 |
continue # TODO improve later, we will only support a single config at a time
|
|
@@ -872,64 +1175,77 @@ class HTMLParser:
|
|
| 872 |
file = self.sourceA if self.sourceA else self.sourceB
|
| 873 |
file_path = Path(file)
|
| 874 |
file_dir = file_path.parent
|
| 875 |
-
sorted_files = sorted(file_dir.iterdir())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
with open(file_path, "w", newline="", encoding="utf8") as final_file:
|
| 877 |
writer = csv.writer(final_file)
|
| 878 |
writer.writerow(CSV_HEADER)
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
import csv
|
| 16 |
import math
|
| 17 |
import os
|
|
|
|
| 18 |
import re
|
| 19 |
+
from pathlib import Path
|
| 20 |
|
| 21 |
import datasets
|
| 22 |
import numpy as np
|
| 23 |
import pandas as pd
|
| 24 |
+
from multiprocessing import Pool, cpu_count
|
| 25 |
from bs4 import BeautifulSoup
|
| 26 |
from tqdm.auto import tqdm
|
| 27 |
|
| 28 |
+
RANDOM_STATE = 42
|
| 29 |
+
np.random.seed(RANDOM_STATE) # Set the seed
|
| 30 |
|
| 31 |
_CITATION = """
|
| 32 |
@inproceedings{silveira-etal-2024-new,
|
|
|
|
| 81 |
"sourceAWithGraders": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceAWithGraders.tar.gz",
|
| 82 |
"sourceB": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceB.tar.gz",
|
| 83 |
"PROPOR2024": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/propor2024.tar.gz",
|
| 84 |
+
"gradesThousand": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/scrapedGradesThousand.tar.gz",
|
| 85 |
}
|
| 86 |
|
| 87 |
|
|
|
|
| 111 |
"general",
|
| 112 |
"specific",
|
| 113 |
"essay_year",
|
| 114 |
+
"reference",
|
| 115 |
]
|
| 116 |
|
| 117 |
CSV_HEADERPROPOR = [
|
|
|
|
| 121 |
"essay",
|
| 122 |
"grades",
|
| 123 |
"essay_year",
|
| 124 |
+
"reference",
|
| 125 |
]
|
| 126 |
|
| 127 |
CSV_HEADERTHOUSAND = [
|
|
|
|
| 133 |
"essay",
|
| 134 |
"source",
|
| 135 |
"supporting_text",
|
| 136 |
+
"prompt",
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
CSV_HEADER_JBCS25 = [
|
| 140 |
+
"id",
|
| 141 |
+
"id_prompt",
|
| 142 |
+
"essay_text",
|
| 143 |
+
"grades",
|
| 144 |
+
"essay_year",
|
| 145 |
+
"supporting_text",
|
| 146 |
+
"prompt",
|
| 147 |
+
"reference",
|
| 148 |
]
|
| 149 |
|
| 150 |
SOURCE_A_DESC = """
|
|
|
|
| 197 |
TODO
|
| 198 |
"""
|
| 199 |
|
| 200 |
+
JBCS2025 = """
|
| 201 |
+
TODO
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
|
| 205 |
class AesEnemDataset(datasets.GeneratorBasedBuilder):
|
| 206 |
"""
|
|
|
|
| 210 |
To reproduce results from PROPOR paper, please refer to "PROPOR2024" config. Other configs are reproducible now.
|
| 211 |
"""
|
| 212 |
|
| 213 |
+
VERSION = datasets.Version("1.0.0")
|
| 214 |
|
| 215 |
# You will be able to load one or the other configurations in the following list with
|
| 216 |
BUILDER_CONFIGS = [
|
|
|
|
| 217 |
datasets.BuilderConfig(
|
| 218 |
+
name="sourceAOnly", version=VERSION, description=SOURCE_A_DESC
|
| 219 |
+
),
|
| 220 |
+
datasets.BuilderConfig(
|
| 221 |
+
name="sourceAWithGraders",
|
| 222 |
+
version=VERSION,
|
| 223 |
+
description=SOURCE_A_WITH_GRADERS,
|
| 224 |
),
|
| 225 |
datasets.BuilderConfig(
|
| 226 |
name="sourceB",
|
| 227 |
version=VERSION,
|
| 228 |
description=SOURCE_B_DESC,
|
| 229 |
),
|
| 230 |
+
datasets.BuilderConfig(
|
| 231 |
+
name="PROPOR2024", version=VERSION, description=PROPOR2024
|
| 232 |
+
),
|
| 233 |
+
datasets.BuilderConfig(
|
| 234 |
+
name="gradesThousand", version=VERSION, description=GRADES_THOUSAND
|
| 235 |
+
),
|
| 236 |
+
datasets.BuilderConfig(name="JBCS2025", version=VERSION, description=JBCS2025),
|
| 237 |
]
|
| 238 |
|
| 239 |
def _info(self):
|
| 240 |
+
if self.config.name == "PROPOR2024":
|
| 241 |
features = datasets.Features(
|
| 242 |
{
|
| 243 |
"id": datasets.Value("string"),
|
|
|
|
| 249 |
"reference": datasets.Value("string"),
|
| 250 |
}
|
| 251 |
)
|
| 252 |
+
elif self.config.name == "gradesThousand":
|
| 253 |
features = datasets.Features(
|
| 254 |
{
|
| 255 |
"id": datasets.Value("string"),
|
| 256 |
"id_prompt": datasets.Value("string"),
|
| 257 |
"supporting_text": datasets.Value("string"),
|
| 258 |
+
"prompt": datasets.Value("string"),
|
| 259 |
"essay_text": datasets.Value("string"),
|
| 260 |
"grades": datasets.Sequence(datasets.Value("int16")),
|
| 261 |
"essay_year": datasets.Value("int16"),
|
| 262 |
"source": datasets.Value("string"),
|
| 263 |
}
|
| 264 |
)
|
| 265 |
+
elif self.config.name == "JBCS2025":
|
| 266 |
+
features = datasets.Features(
|
| 267 |
+
{
|
| 268 |
+
"id": datasets.Value("string"),
|
| 269 |
+
"id_prompt": datasets.Value("string"),
|
| 270 |
+
"essay_text": datasets.Value("string"),
|
| 271 |
+
"grades": datasets.Sequence(datasets.Value("int16")),
|
| 272 |
+
"essay_year": datasets.Value("int16"),
|
| 273 |
+
"supporting_text": datasets.Value("string"),
|
| 274 |
+
"prompt": datasets.Value("string"),
|
| 275 |
+
"reference": datasets.Value("string"),
|
| 276 |
+
}
|
| 277 |
+
)
|
| 278 |
else:
|
| 279 |
features = datasets.Features(
|
| 280 |
{
|
|
|
|
| 316 |
|
| 317 |
def normalize_grades(grades):
|
| 318 |
grades = grades.strip("[]").split(", ")
|
| 319 |
+
grade_mapping = {"0.0": 0, "20": 40, "2.0": 2}
|
| 320 |
|
| 321 |
# We will remove the rows that match the criteria below
|
| 322 |
if any(
|
|
|
|
| 349 |
for split_case in ["train.csv", "validation.csv", "test.csv"]:
|
| 350 |
filepath = f"{base_path}/propor2024/{split_case}"
|
| 351 |
df = pd.read_csv(filepath)
|
| 352 |
+
|
| 353 |
# Dictionary to track how many times we've seen each (id, id_prompt) pair
|
| 354 |
counts = {}
|
| 355 |
# List to store the reference for each row
|
| 356 |
references = []
|
| 357 |
+
|
| 358 |
# Define the mapping for each occurrence
|
| 359 |
occurrence_to_reference = {
|
| 360 |
0: "crawled_from_web",
|
| 361 |
1: "grader_a",
|
| 362 |
+
2: "grader_b",
|
| 363 |
}
|
| 364 |
+
|
| 365 |
# Iterate through rows in the original order
|
| 366 |
for _, row in df.iterrows():
|
| 367 |
key = (row["id"], row["id_prompt"])
|
|
|
|
| 370 |
ref = occurrence_to_reference.get(count, "unknown")
|
| 371 |
references.append(ref)
|
| 372 |
counts[key] = count + 1
|
| 373 |
+
|
| 374 |
# Add the reference column without changing the order of rows
|
| 375 |
df["reference"] = references
|
| 376 |
df.to_csv(filepath, index=False)
|
| 377 |
|
| 378 |
def _split_generators(self, dl_manager):
|
| 379 |
+
if self.config.name != "JBCS2025":
|
| 380 |
+
urls = _URLS[self.config.name]
|
| 381 |
+
extracted_files = dl_manager.download_and_extract({self.config.name: urls})
|
| 382 |
if "PROPOR2024" == self.config.name:
|
| 383 |
base_path = extracted_files["PROPOR2024"]
|
| 384 |
self._preprocess_propor2024(base_path)
|
|
|
|
| 395 |
name=datasets.Split.VALIDATION,
|
| 396 |
# These kwargs will be passed to _generate_examples
|
| 397 |
gen_kwargs={
|
| 398 |
+
"filepath": os.path.join(
|
| 399 |
+
base_path, "propor2024/validation.csv"
|
| 400 |
+
),
|
| 401 |
"split": "validation",
|
| 402 |
},
|
| 403 |
),
|
|
|
|
| 410 |
),
|
| 411 |
]
|
| 412 |
if "gradesThousand" == self.config.name:
|
| 413 |
+
urls = _URLS[self.config.name]
|
| 414 |
+
extracted_files = dl_manager.download_and_extract({self.config.name: urls})
|
| 415 |
+
base_path = f"{extracted_files['gradesThousand']}/scrapedGradesThousand"
|
| 416 |
+
for split in ["train", "validation", "test"]:
|
| 417 |
+
split_filepath = os.path.join(base_path, f"{split}.csv")
|
| 418 |
+
grades_thousand = pd.read_csv(split_filepath)
|
| 419 |
+
grades_thousand[["supporting_text", "prompt"]] = grades_thousand[
|
| 420 |
+
"supporting_text"
|
| 421 |
+
].apply(
|
| 422 |
+
lambda original_text: pd.Series(
|
| 423 |
+
self._extract_prompt_and_clean(original_text)
|
| 424 |
+
)
|
| 425 |
+
)
|
| 426 |
+
grades_thousand.to_csv(split_filepath, index=False)
|
| 427 |
return [
|
| 428 |
datasets.SplitGenerator(
|
| 429 |
name=datasets.Split.TRAIN,
|
|
|
|
| 449 |
},
|
| 450 |
),
|
| 451 |
]
|
|
|
|
| 452 |
if "sourceA" in self.config.name:
|
| 453 |
+
html_parser = self._process_html_files(extracted_files)
|
| 454 |
self._post_process_dataframe(html_parser.sourceA)
|
| 455 |
self._generate_splits(html_parser.sourceA)
|
| 456 |
+
folder_sourceA = Path(html_parser.sourceA).parent
|
| 457 |
return [
|
| 458 |
datasets.SplitGenerator(
|
| 459 |
name=datasets.Split.TRAIN,
|
| 460 |
# These kwargs will be passed to _generate_examples
|
| 461 |
gen_kwargs={
|
| 462 |
+
"filepath": folder_sourceA / "train.csv",
|
| 463 |
"split": "train",
|
| 464 |
},
|
| 465 |
),
|
|
|
|
| 467 |
name=datasets.Split.VALIDATION,
|
| 468 |
# These kwargs will be passed to _generate_examples
|
| 469 |
gen_kwargs={
|
| 470 |
+
"filepath": folder_sourceA / "validation.csv",
|
| 471 |
"split": "validation",
|
| 472 |
},
|
| 473 |
),
|
| 474 |
datasets.SplitGenerator(
|
| 475 |
name=datasets.Split.TEST,
|
| 476 |
gen_kwargs={
|
| 477 |
+
"filepath": folder_sourceA / "test.csv",
|
| 478 |
"split": "test",
|
| 479 |
},
|
| 480 |
),
|
| 481 |
]
|
| 482 |
elif self.config.name == "sourceB":
|
| 483 |
+
html_parser = self._process_html_files(extracted_files)
|
| 484 |
self._post_process_dataframe(html_parser.sourceB)
|
| 485 |
return [
|
| 486 |
datasets.SplitGenerator(
|
|
|
|
| 491 |
},
|
| 492 |
),
|
| 493 |
]
|
| 494 |
+
elif "JBCS2025" == self.config.name:
|
| 495 |
+
extracted_files = dl_manager.download_and_extract(
|
| 496 |
+
{
|
| 497 |
+
"sourceA": _URLS["sourceAWithGraders"],
|
| 498 |
+
"grades_thousand": _URLS["gradesThousand"],
|
| 499 |
+
}
|
| 500 |
+
)
|
| 501 |
+
config_name_source_a = "sourceAWithGraders"
|
| 502 |
+
|
| 503 |
+
html_parser = self._process_html_files(
|
| 504 |
+
paths_dict={config_name_source_a: extracted_files["sourceA"]},
|
| 505 |
+
config_name=config_name_source_a,
|
| 506 |
+
)
|
| 507 |
+
grades_thousand_filedir = (
|
| 508 |
+
Path(extracted_files["grades_thousand"]) / "scrapedGradesThousand"
|
| 509 |
+
)
|
| 510 |
+
self._post_process_dataframe(html_parser.sourceA)
|
| 511 |
+
self._generate_splits(html_parser.sourceA, config_name=config_name_source_a)
|
| 512 |
+
folder_sourceA = Path(html_parser.sourceA).parent
|
| 513 |
+
for split in ["train", "validation", "test"]:
|
| 514 |
+
grades_thousand_df = pd.read_csv(
|
| 515 |
+
grades_thousand_filedir / f"{split}.csv"
|
| 516 |
+
)
|
| 517 |
+
grades_thousand_df["reference"] = "grade_thousand_website"
|
| 518 |
+
sourceA = pd.read_csv(folder_sourceA / f"{split}.csv")
|
| 519 |
+
common_columns = [
|
| 520 |
+
"id",
|
| 521 |
+
"id_prompt",
|
| 522 |
+
"essay_text",
|
| 523 |
+
"grades",
|
| 524 |
+
"essay_year",
|
| 525 |
+
"supporting_text",
|
| 526 |
+
"prompt",
|
| 527 |
+
"reference",
|
| 528 |
+
]
|
| 529 |
+
combined_split = sourceA[
|
| 530 |
+
sourceA.reference.isin(["grader_a", "grader_b"])
|
| 531 |
+
]
|
| 532 |
+
combined_split = combined_split.rename(columns={"essay": "essay_text"})
|
| 533 |
+
grades_thousand_df[["supporting_text", "prompt"]] = grades_thousand_df[
|
| 534 |
+
"supporting_text"
|
| 535 |
+
].apply(
|
| 536 |
+
lambda original_text: pd.Series(
|
| 537 |
+
self._extract_prompt_and_clean(original_text)
|
| 538 |
+
)
|
| 539 |
+
)
|
| 540 |
+
final_split = pd.concat(
|
| 541 |
+
[combined_split[common_columns], grades_thousand_df[common_columns]]
|
| 542 |
+
)
|
| 543 |
+
final_split["grades"] = final_split["grades"].str.replace(",", "")
|
| 544 |
+
final_split = final_split.sample(
|
| 545 |
+
frac=1, random_state=RANDOM_STATE
|
| 546 |
+
).reset_index(drop=True)
|
| 547 |
+
# overwrites the sourceA data
|
| 548 |
+
final_split.to_csv(folder_sourceA / f"{split}.csv", index=False)
|
| 549 |
+
return [
|
| 550 |
+
datasets.SplitGenerator(
|
| 551 |
+
name=datasets.Split.TRAIN,
|
| 552 |
+
# These kwargs will be passed to _generate_examples
|
| 553 |
+
gen_kwargs={
|
| 554 |
+
"filepath": folder_sourceA / "train.csv",
|
| 555 |
+
"split": "train",
|
| 556 |
+
},
|
| 557 |
+
),
|
| 558 |
+
datasets.SplitGenerator(
|
| 559 |
+
name=datasets.Split.VALIDATION,
|
| 560 |
+
# These kwargs will be passed to _generate_examples
|
| 561 |
+
gen_kwargs={
|
| 562 |
+
"filepath": folder_sourceA / "validation.csv",
|
| 563 |
+
"split": "validation",
|
| 564 |
+
},
|
| 565 |
+
),
|
| 566 |
+
datasets.SplitGenerator(
|
| 567 |
+
name=datasets.Split.TEST,
|
| 568 |
+
gen_kwargs={
|
| 569 |
+
"filepath": folder_sourceA / "test.csv",
|
| 570 |
+
"split": "test",
|
| 571 |
+
},
|
| 572 |
+
),
|
| 573 |
+
]
|
| 574 |
+
|
| 575 |
+
def _extract_prompt_and_clean(self, text: str):
|
| 576 |
+
"""
|
| 577 |
+
1) Find an uppercase block matching "PROPOSTA DE REDACAO/REDAÇÃO"
|
| 578 |
+
(with flexible spacing and accents) anywhere in 'text'.
|
| 579 |
+
2) Capture everything from there until the next heading that
|
| 580 |
+
starts a line (TEXTO..., TEXTOS..., INSTRUÇÕES...) or end-of-text.
|
| 581 |
+
3) Remove that captured block from the original, returning:
|
| 582 |
+
(supporting_text, prompt)
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
# Regex explanation:
|
| 586 |
+
# (?m) => MULTILINE, so ^ can match start of lines
|
| 587 |
+
# 1) PROPOSTA\s+DE\s+REDA(?:C|Ç)(?:AO|ÃO)
|
| 588 |
+
# - "PROPOSTA", then one-or-more spaces/newlines,
|
| 589 |
+
# then "DE", then spaces, then "REDA(C|Ç)",
|
| 590 |
+
# and either "AO" or "ÃO" (uppercase).
|
| 591 |
+
# - This part may skip diacritic or accent variations in "REDAÇÃO" vs. "REDACAO".
|
| 592 |
+
#
|
| 593 |
+
# 2) (?:.*?\n?)*? => a non-greedy capture of subsequent lines
|
| 594 |
+
# (including possible newlines). We use [\s\S]*? as an alternative.
|
| 595 |
+
#
|
| 596 |
+
# 3) Lookahead (?=^(?:TEXTO|TEXTOS|INSTRUÇÕES|\Z))
|
| 597 |
+
# means: stop right before a line that starts with "TEXTO", "TEXTOS",
|
| 598 |
+
# or "INSTRUÇÕES", OR the very end of the text (\Z).
|
| 599 |
+
#
|
| 600 |
+
# If found, that entire portion is group(1).
|
| 601 |
+
def force_newline_after_proposta(text: str) -> str:
|
| 602 |
+
"""
|
| 603 |
+
If we see "PROPOSTA DE REDAÇÃO" immediately followed by some
|
| 604 |
+
non-whitespace character (like "A"), insert two newlines.
|
| 605 |
+
E.g., "PROPOSTA DE REDAÇÃOA partir..." becomes
|
| 606 |
+
"PROPOSTA DE REDAÇÃO\n\nA partir..."
|
| 607 |
+
"""
|
| 608 |
+
# This pattern looks for:
|
| 609 |
+
# (PROPOSTA DE REDAÇÃO)
|
| 610 |
+
# (?=\S) meaning "immediately followed by a NON-whitespace character"
|
| 611 |
+
# then we replace that with "PROPOSTA DE REDAÇÃO\n\n"
|
| 612 |
+
pattern = re.compile(r"(?=\S)(PROPOSTA DE REDAÇÃO)(?=\S)")
|
| 613 |
+
return pattern.sub(r"\n\1\n\n", text)
|
| 614 |
+
|
| 615 |
+
text = force_newline_after_proposta(text)
|
| 616 |
+
pattern = re.compile(
|
| 617 |
+
r"(?m)" # MULTILINE
|
| 618 |
+
r"("
|
| 619 |
+
r"PROPOSTA\s+DE\s+REDA(?:C|Ç)(?:AO|ÃO)" # e.g. PROPOSTA DE REDACAO / REDAÇÃO
|
| 620 |
+
r"(?:[\s\S]*?)" # lazily grab the subsequent text
|
| 621 |
+
r")"
|
| 622 |
+
r"(?=(?:TEXTO|TEXTOS|INSTRUÇÕES|TExTO|\Z))"
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
match = pattern.search(text)
|
| 626 |
+
if match:
|
| 627 |
+
prompt = match.group(1).strip()
|
| 628 |
+
# Remove that block from the original:
|
| 629 |
+
start, end = match.span(1)
|
| 630 |
+
main_text = text[:start] + text[end:]
|
| 631 |
+
else:
|
| 632 |
+
# No match => keep entire text in supporting_text, prompt empty
|
| 633 |
+
prompt = ""
|
| 634 |
+
main_text = text
|
| 635 |
+
|
| 636 |
+
return main_text.strip(), prompt.strip()
|
| 637 |
|
| 638 |
+
def _process_html_files(self, paths_dict, config_name=None):
|
| 639 |
html_parser = HTMLParser(paths_dict)
|
| 640 |
+
if config_name is None:
|
| 641 |
+
config_name = self.config.name
|
| 642 |
+
html_parser.parse(config_name)
|
| 643 |
return html_parser
|
| 644 |
|
| 645 |
def _parse_graders_data(self, dirname):
|
|
|
|
| 660 |
grader_b["reference"] = "grader_b"
|
| 661 |
return grader_a, grader_b
|
| 662 |
|
| 663 |
+
def _generate_splits(self, filepath: str, train_size=0.7, config_name=None):
|
| 664 |
+
np.random.seed(RANDOM_STATE)
|
| 665 |
df = pd.read_csv(filepath)
|
|
|
|
|
|
|
| 666 |
train_set = []
|
| 667 |
val_set = []
|
| 668 |
test_set = []
|
| 669 |
+
df = df.sort_values(by=["essay_year", "id_prompt"]).reset_index(drop=True)
|
| 670 |
+
buckets = {}
|
| 671 |
+
for key, group in df.groupby("mapped_year"):
|
| 672 |
+
buckets[key] = sorted(group["id_prompt"].unique())
|
| 673 |
+
df.drop("mapped_year", axis=1, inplace=True)
|
| 674 |
+
for year in sorted(buckets.keys()):
|
| 675 |
+
prompts = buckets[year]
|
| 676 |
np.random.shuffle(prompts)
|
| 677 |
num_prompts = len(prompts)
|
| 678 |
|
|
|
|
| 709 |
val_df = pd.concat(val_set)
|
| 710 |
test_df = pd.concat(test_set)
|
| 711 |
dirname = os.path.dirname(filepath)
|
| 712 |
+
if config_name is None:
|
| 713 |
+
config_name = self.config.name
|
| 714 |
+
if config_name == "sourceAWithGraders":
|
| 715 |
grader_a, grader_b = self._parse_graders_data(dirname)
|
| 716 |
grader_a_data = pd.merge(
|
| 717 |
+
train_df[["id", "id_prompt", "essay", "prompt", "supporting_text"]],
|
| 718 |
+
grader_a.drop(columns=["essay"]),
|
| 719 |
on=["id", "id_prompt"],
|
| 720 |
how="inner",
|
| 721 |
)
|
| 722 |
grader_b_data = pd.merge(
|
| 723 |
+
train_df[["id", "id_prompt", "essay", "prompt", "supporting_text"]],
|
| 724 |
+
grader_b.drop(columns=["essay"]),
|
| 725 |
on=["id", "id_prompt"],
|
| 726 |
how="inner",
|
| 727 |
)
|
| 728 |
+
train_df = pd.concat([train_df, grader_a_data, grader_b_data])
|
| 729 |
+
train_df = train_df.sort_values(by=["id", "id_prompt"]).reset_index(
|
| 730 |
+
drop=True
|
| 731 |
+
)
|
| 732 |
|
| 733 |
grader_a_data = pd.merge(
|
| 734 |
+
val_df[["id", "id_prompt", "essay", "prompt", "supporting_text"]],
|
| 735 |
+
grader_a.drop(columns=["essay"]),
|
| 736 |
on=["id", "id_prompt"],
|
| 737 |
how="inner",
|
| 738 |
)
|
| 739 |
grader_b_data = pd.merge(
|
| 740 |
+
val_df[["id", "id_prompt", "essay", "prompt", "supporting_text"]],
|
| 741 |
+
grader_b.drop(columns=["essay"]),
|
| 742 |
on=["id", "id_prompt"],
|
| 743 |
how="inner",
|
| 744 |
)
|
| 745 |
+
val_df = pd.concat([val_df, grader_a_data, grader_b_data])
|
| 746 |
+
val_df = val_df.sort_values(by=["id", "id_prompt"]).reset_index(drop=True)
|
| 747 |
|
| 748 |
grader_a_data = pd.merge(
|
| 749 |
+
test_df[["id", "id_prompt", "essay", "prompt", "supporting_text"]],
|
| 750 |
+
grader_a.drop(columns=["essay"]),
|
| 751 |
on=["id", "id_prompt"],
|
| 752 |
how="inner",
|
| 753 |
)
|
| 754 |
grader_b_data = pd.merge(
|
| 755 |
+
test_df[["id", "id_prompt", "essay", "prompt", "supporting_text"]],
|
| 756 |
+
grader_b.drop(columns=["essay"]),
|
| 757 |
on=["id", "id_prompt"],
|
| 758 |
how="inner",
|
| 759 |
)
|
| 760 |
+
test_df = pd.concat([test_df, grader_a_data, grader_b_data])
|
| 761 |
+
test_df = test_df.sort_values(by=["id", "id_prompt"]).reset_index(drop=True)
|
| 762 |
+
|
| 763 |
+
train_df = train_df.sample(frac=1, random_state=RANDOM_STATE).reset_index(
|
| 764 |
+
drop=True
|
| 765 |
+
)
|
| 766 |
+
val_df = val_df.sample(frac=1, random_state=RANDOM_STATE).reset_index(
|
| 767 |
+
drop=True
|
| 768 |
+
)
|
| 769 |
+
test_df = test_df.sample(frac=1, random_state=RANDOM_STATE).reset_index(
|
| 770 |
+
drop=True
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
# Data Validation Assertions
|
| 774 |
assert (
|
| 775 |
len(set(train_df["id_prompt"]).intersection(set(val_df["id_prompt"]))) == 0
|
|
|
|
| 793 |
for i, row in enumerate(csv_reader):
|
| 794 |
grades = row["grades"].strip("[]")
|
| 795 |
grades = grades.split()
|
| 796 |
+
yield (
|
| 797 |
+
i,
|
| 798 |
+
{
|
| 799 |
+
"id": row["id"],
|
| 800 |
+
"id_prompt": row["id_prompt"],
|
| 801 |
+
"essay_title": row["title"],
|
| 802 |
+
"essay_text": row["essay"],
|
| 803 |
+
"grades": grades,
|
| 804 |
+
"essay_year": row["essay_year"],
|
| 805 |
+
"reference": row["reference"],
|
| 806 |
+
},
|
| 807 |
+
)
|
| 808 |
elif self.config.name == "gradesThousand":
|
| 809 |
with open(filepath, encoding="utf-8") as csvfile:
|
| 810 |
next(csvfile)
|
|
|
|
| 812 |
for i, row in enumerate(csv_reader):
|
| 813 |
grades = row["grades"].strip("[]")
|
| 814 |
grades = grades.split(", ")
|
| 815 |
+
yield (
|
| 816 |
+
i,
|
| 817 |
+
{
|
| 818 |
+
"id": row["id"],
|
| 819 |
+
"id_prompt": row["id_prompt"],
|
| 820 |
+
"supporting_text": row["supporting_text"],
|
| 821 |
+
"prompt": row["prompt"],
|
| 822 |
+
"essay_text": row["essay"],
|
| 823 |
+
"grades": grades,
|
| 824 |
+
"essay_year": row["essay_year"],
|
| 825 |
+
"author": row["author"],
|
| 826 |
+
"source": row["source"],
|
| 827 |
+
},
|
| 828 |
+
)
|
| 829 |
+
elif self.config.name == "JBCS2025":
|
| 830 |
+
with open(filepath, encoding="utf-8") as csvfile:
|
| 831 |
+
next(csvfile)
|
| 832 |
+
csv_reader = csv.DictReader(csvfile, fieldnames=CSV_HEADER_JBCS25)
|
| 833 |
+
for i, row in enumerate(csv_reader):
|
| 834 |
+
grades = row["grades"].strip("[]")
|
| 835 |
+
grades = grades.split()
|
| 836 |
+
yield (
|
| 837 |
+
i,
|
| 838 |
+
{
|
| 839 |
+
"id": row["id"],
|
| 840 |
+
"id_prompt": row["id_prompt"],
|
| 841 |
+
"essay_text": row["essay_text"],
|
| 842 |
+
"grades": grades,
|
| 843 |
+
"essay_year": row["essay_year"],
|
| 844 |
+
"supporting_text": row["supporting_text"],
|
| 845 |
+
"prompt": row["prompt"],
|
| 846 |
+
"reference": row["reference"],
|
| 847 |
+
},
|
| 848 |
+
)
|
| 849 |
else:
|
| 850 |
with open(filepath, encoding="utf-8") as csvfile:
|
| 851 |
next(csvfile)
|
|
|
|
| 853 |
for i, row in enumerate(csv_reader):
|
| 854 |
grades = row["grades"].strip("[]")
|
| 855 |
grades = grades.split(", ")
|
| 856 |
+
yield (
|
| 857 |
+
i,
|
| 858 |
+
{
|
| 859 |
+
"id": row["id"],
|
| 860 |
+
"id_prompt": row["id_prompt"],
|
| 861 |
+
"prompt": row["prompt"],
|
| 862 |
+
"supporting_text": row["supporting_text"],
|
| 863 |
+
"essay_title": row["title"],
|
| 864 |
+
"essay_text": row["essay"],
|
| 865 |
+
"grades": grades,
|
| 866 |
+
"essay_year": row["essay_year"],
|
| 867 |
+
"general_comment": row["general"],
|
| 868 |
+
"specific_comment": row["specific"],
|
| 869 |
+
"reference": row["reference"],
|
| 870 |
+
},
|
| 871 |
+
)
|
| 872 |
|
| 873 |
|
| 874 |
class HTMLParser:
|
|
|
|
| 907 |
for single_grade in grades:
|
| 908 |
grade = int(single_grade.get_text())
|
| 909 |
final_grades.append(grade)
|
| 910 |
+
assert final_grades[-1] == sum(final_grades[:-1]), (
|
| 911 |
+
"Grading sum is not making sense"
|
| 912 |
+
)
|
| 913 |
else:
|
| 914 |
grades = soup.find("div", class_="redacoes-corrigidas pg-bordercolor7")
|
| 915 |
grades_sum = float(
|
|
|
|
| 919 |
for idx in range(1, 10, 2):
|
| 920 |
grade = float(grades[idx].get_text().replace(",", "."))
|
| 921 |
final_grades.append(grade)
|
| 922 |
+
assert grades_sum == sum(final_grades), (
|
| 923 |
+
"Grading sum is not making sense"
|
| 924 |
+
)
|
| 925 |
final_grades.append(grades_sum)
|
| 926 |
return final_grades
|
| 927 |
elif self.sourceB:
|
|
|
|
| 932 |
for single_grade in grades:
|
| 933 |
result.append(int(single_grade.get_text()))
|
| 934 |
assert len(result) == 5, "We should have 5 Grades (one per concept) only"
|
| 935 |
+
result.append(
|
| 936 |
+
sum(result)
|
| 937 |
+
) # Add sum as a sixt element to keep the same pattern
|
| 938 |
return result
|
| 939 |
|
| 940 |
def _get_general_comment(self, soup):
|
|
|
|
| 1041 |
span.decompose()
|
| 1042 |
result = table.find_all("p")
|
| 1043 |
result = " ".join(
|
| 1044 |
+
[
|
| 1045 |
+
paragraph.get_text().replace("\xa0", "").strip()
|
| 1046 |
+
for paragraph in result
|
| 1047 |
+
]
|
| 1048 |
)
|
| 1049 |
return result
|
| 1050 |
|
|
|
|
| 1088 |
return new_list
|
| 1089 |
|
| 1090 |
def _clean_string(self, sentence):
|
| 1091 |
+
sentence = sentence.replace("\xa0", "").replace("\u200b", "")
|
| 1092 |
+
sentence = (
|
| 1093 |
+
sentence.replace(".", ". ")
|
| 1094 |
+
.replace("?", "? ")
|
| 1095 |
+
.replace("!", "! ")
|
| 1096 |
+
.replace(")", ") ")
|
| 1097 |
+
.replace(":", ": ")
|
| 1098 |
+
.replace("”", "” ")
|
| 1099 |
+
)
|
| 1100 |
sentence = sentence.replace(" ", " ").replace(". . . ", "...")
|
| 1101 |
+
sentence = sentence.replace("(editado)", "").replace("(Editado)", "")
|
| 1102 |
+
sentence = sentence.replace("(editado e adaptado)", "").replace(
|
| 1103 |
+
"(Editado e adaptado)", ""
|
| 1104 |
+
)
|
| 1105 |
sentence = sentence.replace(". com. br", ".com.br")
|
| 1106 |
sentence = sentence.replace("[Veja o texto completo aqui]", "")
|
| 1107 |
+
return sentence
|
| 1108 |
|
| 1109 |
def _get_supporting_text(self, soup):
|
| 1110 |
if self.sourceA:
|
| 1111 |
textos = soup.find_all("ul", class_="article-wording-item")
|
| 1112 |
resposta = []
|
| 1113 |
for t in textos[:-1]:
|
| 1114 |
+
resposta.append(
|
| 1115 |
+
t.find("h3", class_="item-titulo").get_text().replace("\xa0", "")
|
| 1116 |
+
)
|
| 1117 |
+
resposta.append(
|
| 1118 |
+
self._clean_string(
|
| 1119 |
+
t.find("div", class_="item-descricao").get_text()
|
| 1120 |
+
)
|
| 1121 |
+
)
|
| 1122 |
return resposta
|
| 1123 |
else:
|
| 1124 |
return ""
|
| 1125 |
+
|
| 1126 |
def _get_prompt(self, soup):
|
| 1127 |
if self.sourceA:
|
| 1128 |
prompt = soup.find("div", class_="text").find_all("p")
|
| 1129 |
if len(prompt[0].get_text()) < 2:
|
| 1130 |
+
return [prompt[1].get_text().replace("\xa0", "")]
|
| 1131 |
else:
|
| 1132 |
+
return [prompt[0].get_text().replace("\xa0", "")]
|
| 1133 |
+
else:
|
| 1134 |
return ""
|
| 1135 |
|
| 1136 |
+
def _process_all_prompts(self, sub_folders, file_dir, reference, prompts_to_ignore):
|
| 1137 |
+
"""
|
| 1138 |
+
Process all prompt folders in parallel and return all rows to write.
|
| 1139 |
+
|
| 1140 |
+
Args:
|
| 1141 |
+
sub_folders (list): List of prompt folder names (or Paths).
|
| 1142 |
+
file_dir (str): Base directory where prompts are located.
|
| 1143 |
+
reference: Reference info to include in each row.
|
| 1144 |
+
prompts_to_ignore (collection): Prompts to be ignored.
|
| 1145 |
+
|
| 1146 |
+
Returns:
|
| 1147 |
+
list: A list of all rows to write to the CSV.
|
| 1148 |
+
"""
|
| 1149 |
+
|
| 1150 |
+
args_list = [
|
| 1151 |
+
(prompt_folder, file_dir, reference, prompts_to_ignore, self)
|
| 1152 |
+
for prompt_folder in sub_folders
|
| 1153 |
+
]
|
| 1154 |
+
|
| 1155 |
+
all_rows = []
|
| 1156 |
+
# Use a Pool to parallelize processing.
|
| 1157 |
+
with Pool(processes=cpu_count()) as pool:
|
| 1158 |
+
# Using imap allows us to update the progress bar.
|
| 1159 |
+
for rows in tqdm(
|
| 1160 |
+
pool.imap(HTMLParser._process_prompt_folder, args_list),
|
| 1161 |
+
total=len(args_list),
|
| 1162 |
+
desc="Processing prompts",
|
| 1163 |
+
):
|
| 1164 |
+
all_rows.extend(rows)
|
| 1165 |
+
return all_rows
|
| 1166 |
+
|
| 1167 |
+
def parse(self, config_name: str):
|
| 1168 |
for key, filepath in self.paths_dict.items():
|
| 1169 |
if key != config_name:
|
| 1170 |
continue # TODO improve later, we will only support a single config at a time
|
|
|
|
| 1175 |
file = self.sourceA if self.sourceA else self.sourceB
|
| 1176 |
file_path = Path(file)
|
| 1177 |
file_dir = file_path.parent
|
| 1178 |
+
sorted_files = sorted(file_dir.iterdir(), key=lambda p: p.name)
|
| 1179 |
+
sub_folders = [name for name in sorted_files if name.suffix != ".csv"]
|
| 1180 |
+
reference = "crawled_from_web"
|
| 1181 |
+
all_rows = self._process_all_prompts(
|
| 1182 |
+
sub_folders, file_dir, reference, PROMPTS_TO_IGNORE
|
| 1183 |
+
)
|
| 1184 |
with open(file_path, "w", newline="", encoding="utf8") as final_file:
|
| 1185 |
writer = csv.writer(final_file)
|
| 1186 |
writer.writerow(CSV_HEADER)
|
| 1187 |
+
for row in all_rows:
|
| 1188 |
+
writer.writerow(row)
|
| 1189 |
+
|
| 1190 |
+
@staticmethod
|
| 1191 |
+
def _process_prompt_folder(args):
|
| 1192 |
+
"""
|
| 1193 |
+
Process one prompt folder and return a list of rows to write to CSV.
|
| 1194 |
+
Args:
|
| 1195 |
+
args (tuple): Contains:
|
| 1196 |
+
- prompt_folder: The folder name (or Path object) for the prompt.
|
| 1197 |
+
- file_dir: The base directory.
|
| 1198 |
+
- reference: Reference info to include in each row.
|
| 1199 |
+
- prompts_to_ignore: A collection of prompts to skip.
|
| 1200 |
+
- instance: An instance of the class that contains the parsing methods.
|
| 1201 |
+
Returns:
|
| 1202 |
+
list: A list of rows (each row is a list) to write to CSV.
|
| 1203 |
+
"""
|
| 1204 |
+
prompt_folder, file_dir, reference, prompts_to_ignore, instance = args
|
| 1205 |
+
rows = []
|
| 1206 |
+
# Skip folders that should be ignored.
|
| 1207 |
+
if prompt_folder in prompts_to_ignore:
|
| 1208 |
+
return rows
|
| 1209 |
+
# Build the full path for the prompt folder.
|
| 1210 |
+
prompt = os.path.join(file_dir, prompt_folder)
|
| 1211 |
+
# List and sort the HTML files.
|
| 1212 |
+
try:
|
| 1213 |
+
sorted_prompts = sorted(os.listdir(prompt))
|
| 1214 |
+
except Exception as e:
|
| 1215 |
+
print(f"Error listing directory {prompt}: {e}")
|
| 1216 |
+
return rows
|
| 1217 |
+
# Process the common "Prompt.html" once.
|
| 1218 |
+
soup_prompt = instance.apply_soup(prompt, "Prompt.html")
|
| 1219 |
+
essay_year = instance._get_essay_year(soup_prompt)
|
| 1220 |
+
essay_supporting_text = "\n".join(instance._get_supporting_text(soup_prompt))
|
| 1221 |
+
essay_prompt = "\n".join(instance._get_prompt(soup_prompt))
|
| 1222 |
+
# Process each essay file except the prompt itself.
|
| 1223 |
+
for essay_filename in sorted_prompts:
|
| 1224 |
+
if essay_filename == "Prompt.html":
|
| 1225 |
+
continue
|
| 1226 |
+
soup_text = instance.apply_soup(prompt, essay_filename)
|
| 1227 |
+
essay_title = instance._clean_title(instance._get_title(soup_text))
|
| 1228 |
+
essay_grades = instance._get_grades(soup_text)
|
| 1229 |
+
essay_text = instance._get_essay(soup_text)
|
| 1230 |
+
general_comment = instance._get_general_comment(soup_text).strip()
|
| 1231 |
+
specific_comment = instance._get_specific_comment(
|
| 1232 |
+
soup_text, general_comment
|
| 1233 |
+
)
|
| 1234 |
+
# Create a row with all the information.
|
| 1235 |
+
row = [
|
| 1236 |
+
essay_filename,
|
| 1237 |
+
prompt_folder
|
| 1238 |
+
if not hasattr(prompt_folder, "name")
|
| 1239 |
+
else prompt_folder.name,
|
| 1240 |
+
essay_prompt,
|
| 1241 |
+
essay_supporting_text,
|
| 1242 |
+
essay_title,
|
| 1243 |
+
essay_text,
|
| 1244 |
+
essay_grades,
|
| 1245 |
+
general_comment,
|
| 1246 |
+
specific_comment,
|
| 1247 |
+
essay_year,
|
| 1248 |
+
reference,
|
| 1249 |
+
]
|
| 1250 |
+
rows.append(row)
|
| 1251 |
+
return rows
|
pyproject.toml
CHANGED
|
@@ -9,5 +9,6 @@ dependencies = [
|
|
| 9 |
"datasets>=3.2.0",
|
| 10 |
"ipdb>=0.13.13",
|
| 11 |
"pandas>=2.2.3",
|
|
|
|
| 12 |
"tqdm>=4.67.1",
|
| 13 |
]
|
|
|
|
| 9 |
"datasets>=3.2.0",
|
| 10 |
"ipdb>=0.13.13",
|
| 11 |
"pandas>=2.2.3",
|
| 12 |
+
"ruff>=0.9.4",
|
| 13 |
"tqdm>=4.67.1",
|
| 14 |
]
|