Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
parquet
Languages:
Portuguese
Size:
1K - 10K
License:
include sourceB dataset
Browse files47 unmodified lines484950515253545556575859606111 unmodified lines73747576777879808182838485868788893 unmodified lines9394959697989910010110210310410510610710810911011111211311411510 unmodified lines1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771785 unmodified lines1841851861871881891902 unmodified lines1931941951961971981993 unmodified lines20320420520620720820921021151 unmodified lines2632642652662672682692702712722732742752762772782792802812829 unmodified lines29229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843910 unmodified lines45045145245345445545645745845946018 unmodified lines47948048148248348448548648748848949049149249349449549649749849950050150250350450550650747 unmodified lines_URLS = {"sourceA": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceA.tar.gz?download=true",}PROMPTS_TO_IGNORE = ["brasileiros-tem-pessima-educacao-argumentativa-segundo-cientista","carta-convite-discutir-discriminacao-na-escola","informacao-no-rotulo-de-produtos-transgenicos",]CSV_HEADER = ["id","id_prompt",11 unmodified linesVERSION = datasets.Version("0.0.1")# This is an example of a dataset with multiple configurations.# If you don't want/need to define several sub-sets in your dataset,# just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.# If you need to make complex sub-parts in the datasets with configurable options# You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig# BUILDER_CONFIG_CLASS = MyBuilderConfig# You will be able to load one or the other configurations in the following list with# data = datasets.load_dataset('my_dataset', 'first_domain')# data = datasets.load_dataset('my_dataset', 'second_domain')BUILDER_CONFIGS = [datasets.BuilderConfig(name="sourceA", version=VERSION, description="TODO"),datasets.BuilderConfig(3 unmodified lines),]DEFAULT_CONFIG_NAME = "sourceA" # It's not mandatory to have a default configuration. Just use one if it make sense.def _info(self):# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the datasetif (self.config.name == "sourceA"): # This is the name of the configuration selected in BUILDER_CONFIGS abovefeatures = datasets.Features({"id": datasets.Value("string"),"id_prompt": datasets.Value("string"),"essay_title": datasets.Value("string"),"essay_text": datasets.Value("string"),"grades": datasets.Sequence(datasets.Value("int16")),"essay_year": datasets.Value("int16"),})return datasets.DatasetInfo(# This is the description that will appear on the datasets page.description=_DESCRIPTION,10 unmodified linescitation=_CITATION,)def _split_generators(self, dl_manager):# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.nameurls = _URLS[self.config.name]extracted_files = dl_manager.download_and_extract({"sourceA": urls})html_parser = self._process_html_files(extracted_files)self._generate_splits(html_parser.sourceA)return [datasets.SplitGenerator(name=datasets.Split.TRAIN,# These kwargs will be passed to _generate_examplesgen_kwargs={"filepath": os.path.join(extracted_files["sourceA"], "sourceA", "train.csv"),"split": "train",},),datasets.SplitGenerator(name=datasets.Split.VALIDATION,# These kwargs will be passed to _generate_examplesgen_kwargs={"filepath": os.path.join(extracted_files["sourceA"], "sourceA", "validation.csv"),"split": "validation",},),datasets.SplitGenerator(name=datasets.Split.TEST,# These kwargs will be passed to _generate_examplesgen_kwargs={"filepath": os.path.join(extracted_files["sourceA"], "sourceA", "test.csv"),"split": "test",},),]def _process_html_files(self, paths_dict):html_parser = HTMLParser(paths_dict)html_parser.parse()return html_parserdef _generate_splits(self, filepath: str, train_size=0.7):def map_year(year):if year <= 2017:return "<=2017"5 unmodified lines# We will remove the rows that match the criteria belowif any(single_grade in grades[:-1] #we ignore the sum, and only check the concetpsfor single_grade in ["50", "100", "150", "0.5", "1.0", "1.5"]):return None2 unmodified linesint(grade_mapping.get(grade_concept, grade_concept))for grade_concept in grades[:-1]]# Calculate and append the sum of the mapped grades as the last elementmapped_grades.append(sum(mapped_grades))return mapped_grades3 unmodified linesdf["essay_year"] = df["essay_year"].astype("int")df["mapped_year"] = df["essay_year"].apply(map_year)df["grades"] = df["grades"].apply(normalize_grades)df = df.dropna()buckets = df.groupby("mapped_year")["id_prompt"].unique().to_dict()df.drop('mapped_year', axis=1, inplace=True)train_set = []val_set = []test_set = []51 unmodified lines# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`def _generate_examples(self, filepath, split):if self.config.name == "sourceA":with open(filepath, encoding="utf-8") as csvfile:next(csvfile)csv_reader = csv.DictReader(csvfile, fieldnames=CSV_HEADER)for i, row in enumerate(csv_reader):grades = row["grades"].strip("[]").split(", ")yield i, {"id": row["id"],"id_prompt": row["id_prompt"],"essay_title": row["title"],"essay_text": row["essay"],"grades": grades,"essay_year": row["essay_year"],}class HTMLParser:9 unmodified linessoup = BeautifulSoup(conteudo, "html.parser")return soup@staticmethoddef _get_title(soup):title = soup.find("div", class_="container-composition")if title is None:title = soup.find("h1", class_="pg-color10").get_text()else:title = title.h2.get_text()title = title.replace("\xa0", "")return title@staticmethoddef _get_grades(soup):grades = soup.find("section", class_="results-table")final_grades = []if grades is not None:grades = grades.find_all("span", class_="points")assert len(grades) == 6, f"Missing grades: {len(grades)}"for single_grade in grades:grade = int(single_grade.get_text())final_grades.append(grade)assert final_grades[-1] == sum(final_grades[:-1]), "Grading sum is not making sense"else:grades = soup.find("div", class_="redacoes-corrigidas pg-bordercolor7")grades_sum = float(soup.find("th", class_="noBorder-left").get_text().replace(",", "."))grades = grades.find_all("td")[:10]for idx in range(1, 10, 2):grade = float(grades[idx].get_text().replace(",", "."))final_grades.append(grade)assert grades_sum == sum(final_grades), "Grading sum is not making sense"final_grades.append(grades_sum)return final_grades@staticmethoddef _get_general_comment(soup):def get_general_comment_aux(soup):result = soup.find("article", class_="list-item c")if result is not None:result = result.find("div", class_="description")return result.get_text()else:result = soup.find("p", style="margin: 0px 0px 11px;")if result is not None:return result.get_text()else:result = soup.find("p", style="margin: 0px;")if result is not None:return result.get_text()else:result = soup.find("p", style="margin: 0px; text-align: justify;")if result is not None:return result.get_text()else:return ""text = soup.find("div", class_="text")if text is not None:text = text.find("p")if (text is None) or (len(text.get_text()) < 2):return get_general_comment_aux(soup)return text.get_text()else:return get_general_comment_aux(soup)@staticmethoddef _get_specific_comment(soup):result = soup.find("div", class_="text")if result is not None:result = result.find_all("li")cms = []if result != []:for item in result:text = item.get_text()if text != "\xa0":cms.append(text)return cmselse:result = soup.find("div", class_="text").find_all("p")for item in result:text = item.get_text()if text != "\xa0":cms.append(text)return cmselse:result = soup.find_all("article", class_="list-item c")if len(result) < 2:return ["First if"]result = result[1].find_all("p")cms = []for item in result:text = item.get_text()if text != "\xa0":cms.append(text)return cms@staticmethoddef _get_essay(soup):essay = soup.find("div", class_="text-composition")if essay is not None:essay = essay.find_all("p")for f in essay:while f.find("span", style="color:#00b050") is not None:f.find("span", style="color:#00b050").decompose()while f.find("span", class_="certo") is not None:f.find("span", class_="certo").decompose()result = []for paragraph in essay:result.append(paragraph.get_text())return resultelse:essay = soup.find("div", {"id": "texto"})essay.find("section", class_="list-items").decompose()essay = essay.find_all("p")for f in essay:while f.find("span", class_="certo") is not None:f.find("span", class_="certo").decompose()result = []for paragraph in essay:result.append(paragraph.get_text())return result@staticmethoddef _get_essay_year(soup):pattern = r"redações corrigidas - \w+/\d+"first_occurrence = re.search(pattern, soup.get_text().lower())matched_url = first_occurrence.group(0) if first_occurrence else Noneyear_pattern = r"\d{4}"return re.search(year_pattern, matched_url).group(0)def _clean_title(self, title):smaller_index = title.find("[")if smaller_index == -1:return titleelse:bigger_index = title.find("]")new_title = title[:smaller_index] + title[bigger_index + 1 :]return self._clean_title(new_title.replace(" ", " "))def _clean_list(self, list):if list == []:10 unmodified linesnew_list.append(phrase)return new_listdef parse(self):for key, filepath in self.paths_dict.items():full_path = os.path.join(filepath, key)if key == "sourceA":self.sourceA = f"{full_path}/sourceA.csv"with open(f"{full_path}/{key}.csv", "w", newline="", encoding="utf8") as final_file:18 unmodified linescontinueprompt = os.path.join(full_path, prompt_folder)prompt_essays = [name for name in os.listdir(prompt)]essay_year = HTMLParser._get_essay_year(self.apply_soup(prompt, "Prompt.html"))for essay in prompt_essays:soup_text = self.apply_soup(prompt, essay)if essay == "Prompt.html":continueessay_title = self._clean_title(HTMLParser._get_title(soup_text).replace(";", ","))essay_grades = HTMLParser._get_grades(soup_text)general_comment = HTMLParser._get_general_comment(soup_text).strip()specific_comment = HTMLParser._get_specific_comment(soup_text)if general_comment in specific_comment:specific_comment.remove(general_comment)if (len(specific_comment) > 1) and (len(specific_comment[0]) < 2):specific_comment = specific_comment[1:]essay_text = self._clean_list(HTMLParser._get_essay(soup_text))specific_comment = self._clean_list(specific_comment)writer.writerow([essay,47 unmodified lines48495051525354555657585960616263646566676869707111 unmodified lines838485868788893 unmodified lines9394959697989910010110210310410510610710810911010 unmodified lines1211221231241251261275 unmodified lines1331341351361371381391402 unmodified lines1431441451461471483 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322451 unmodified lines2762772782792802812822832842852862872882892902912922932949 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848910 unmodified lines50050150250350450550650750850951051151251351418 unmodified lines53353453553653753853954054154254354454554654754854955055155247 unmodified lines_URLS = {"sourceA": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceA.tar.gz?download=true","sourceB": "https://huggingface.co/datasets/kamel-usp/aes_enem_dataset/resolve/main/sourceB.tar.gz?download=true",}PROMPTS_TO_IGNORE = ["brasileiros-tem-pessima-educacao-argumentativa-segundo-cientista","carta-convite-discutir-discriminacao-na-escola","informacao-no-rotulo-de-produtos-transgenicos",]# Essays to IgnoreESSAY_TO_IGNORE = ["direitos-em-conflito-liberdade-de-expressao-e-intimidade/2.html","terceirizacao-avanco-ou-retrocesso/2.html","artes-e-educacao-fisica-opcionais-ou-obrigatorias/2.html","violencia-e-drogas-o-papel-do-usuario/0.html","internacao-compulsoria-de-dependentes-de-crack/0.html",]CSV_HEADER = ["id","id_prompt",11 unmodified linesVERSION = datasets.Version("0.0.1")# You will be able to load one or the other configurations in the following list withBUILDER_CONFIGS = [datasets.BuilderConfig(name="sourceA", version=VERSION, description="TODO"),datasets.BuilderConfig(3 unmodified lines),]def _info(self):features = datasets.Features({"id": datasets.Value("string"),"id_prompt": datasets.Value("string"),"essay_title": datasets.Value("string"),"essay_text": datasets.Value("string"),"grades": datasets.Sequence(datasets.Value("int16")),"essay_year": datasets.Value("int16"),})return datasets.DatasetInfo(# This is the description that will appear on the datasets page.description=_DESCRIPTION,10 unmodified linescitation=_CITATION,)def _post_process_dataframe(self, filepath):def map_year(year):if year <= 2017:return "<=2017"5 unmodified lines# We will remove the rows that match the criteria belowif any(single_gradein grades[:-1] # we ignore the sum, and only check the concetpsfor single_grade in ["50", "100", "150", "0.5", "1.0", "1.5"]):return None2 unmodified linesint(grade_mapping.get(grade_concept, grade_concept))for grade_concept in grades[:-1]]# Calculate and append the sum of the mapped grades as the last elementmapped_grades.append(sum(mapped_grades))return mapped_grades3 unmodified linesdf["essay_year"] = df["essay_year"].astype("int")df["mapped_year"] = df["essay_year"].apply(map_year)df["grades"] = df["grades"].apply(normalize_grades)df = df.dropna(subset=["grades"])df = df[~(df["id_prompt"] + "/" + df["id"]).isin(ESSAY_TO_IGNORE)] # arbitrary removal of zero graded essaysdf.to_csv(filepath, index=False)def _split_generators(self, dl_manager):urls = _URLS[self.config.name]extracted_files = dl_manager.download_and_extract({self.config.name: urls})html_parser = self._process_html_files(extracted_files)if self.config.name == "sourceA":self._post_process_dataframe(html_parser.sourceA)self._generate_splits(html_parser.sourceA)return [datasets.SplitGenerator(name=datasets.Split.TRAIN,# These kwargs will be passed to _generate_examplesgen_kwargs={"filepath": os.path.join(extracted_files["sourceA"], "sourceA", "train.csv"),"split": "train",},),datasets.SplitGenerator(name=datasets.Split.VALIDATION,# These kwargs will be passed to _generate_examplesgen_kwargs={"filepath": os.path.join(extracted_files["sourceA"], "sourceA", "validation.csv"),"split": "validation",},),datasets.SplitGenerator(name=datasets.Split.TEST,gen_kwargs={"filepath": os.path.join(extracted_files["sourceA"], "sourceA", "test.csv"),"split": "test",},),]elif self.config.name == "sourceB":self._post_process_dataframe(html_parser.sourceB)return [datasets.SplitGenerator(name="full",gen_kwargs={"filepath": os.path.join(extracted_files["sourceB"], "sourceB", "sourceB.csv"),"split": "full",},),]def _process_html_files(self, paths_dict):html_parser = HTMLParser(paths_dict)html_parser.parse(self.config.name)return html_parserdef _generate_splits(self, filepath: str, train_size=0.7):df = pd.read_csv(filepath)buckets = df.groupby("mapped_year")["id_prompt"].unique().to_dict()df.drop("mapped_year", axis=1, inplace=True)train_set = []val_set = []test_set = []51 unmodified lines# method parameters are unpacked from `gen_kwargs` as given in `_split_generators`def _generate_examples(self, filepath, split):with open(filepath, encoding="utf-8") as csvfile:next(csvfile)csv_reader = csv.DictReader(csvfile, fieldnames=CSV_HEADER)for i, row in enumerate(csv_reader):grades = row["grades"].strip("[]").split(", ")yield i, {"id": row["id"],"id_prompt": row["id_prompt"],"essay_title": row["title"],"essay_text": row["essay"],"grades": grades,"essay_year": row["essay_year"],}class HTMLParser:9 unmodified linessoup = BeautifulSoup(conteudo, "html.parser")return soupdef _get_title(self, soup):if self.sourceA:title = soup.find("div", class_="container-composition")if title is None:title = soup.find("h1", class_="pg-color10").get_text()else:title = title.h2.get_text()title = title.replace("\xa0", "")return title.replace(";", ",")elif self.sourceB:title = soup.find("h1", class_="titulo-conteudo").get_text()return title.strip("- Banco de redações").strip()def _get_grades(self, soup):if self.sourceA:grades = soup.find("section", class_="results-table")final_grades = []if grades is not None:grades = grades.find_all("span", class_="points")assert len(grades) == 6, f"Missing grades: {len(grades)}"for single_grade in grades:grade = int(single_grade.get_text())final_grades.append(grade)assert final_grades[-1] == sum(final_grades[:-1]), "Grading sum is not making sense"else:grades = soup.find("div", class_="redacoes-corrigidas pg-bordercolor7")grades_sum = float(soup.find("th", class_="noBorder-left").get_text().replace(",", "."))grades = grades.find_all("td")[:10]for idx in range(1, 10, 2):grade = float(grades[idx].get_text().replace(",", "."))final_grades.append(grade)assert grades_sum == sum(final_grades), "Grading sum is not making sense"final_grades.append(grades_sum)return final_gradeselif self.sourceB:table = soup.find("table", {"id": "redacoes_corrigidas"})grades = table.find_all("td", class_="simple-td")grades = grades[3:]result = []for single_grade in grades:result.append(int(single_grade.get_text()))return resultdef _get_general_comment(self, soup):if self.sourceA:def get_general_comment_aux(soup):result = soup.find("article", class_="list-item c")if result is not None:result = result.find("div", class_="description")return result.get_text()else:result = soup.find("p", style="margin: 0px 0px 11px;")if result is not None:return result.get_text()else:result = soup.find("p", style="margin: 0px;")if result is not None:return result.get_text()else:result = soup.find("p", style="margin: 0px; text-align: justify;")if result is not None:return result.get_text()else:return ""text = soup.find("div", class_="text")if text is not None:text = text.find("p")if (text is None) or (len(text.get_text()) < 2):return get_general_comment_aux(soup)return text.get_text()else:return get_general_comment_aux(soup)elif self.sourceB:return ""def _get_specific_comment(self, soup, general_comment):if self.sourceA:result = soup.find("div", class_="text")cms = []if result is not None:result = result.find_all("li")if result != []:for item in result:text = item.get_text()if text != "\xa0":cms.append(text)else:result = soup.find("div", class_="text").find_all("p")for item in result:text = item.get_text()if text != "\xa0":cms.append(text)else:result = soup.find_all("article", class_="list-item c")if len(result) < 2:return ["First if"]result = result[1].find_all("p")for item in result:text = item.get_text()if text != "\xa0":cms.append(text)specific_comment = cms.copy()if general_comment in specific_comment:specific_comment.remove(general_comment)if (len(specific_comment) > 1) and (len(specific_comment[0]) < 2):specific_comment = specific_comment[1:]return self._clean_list(specific_comment)elif self.sourceB:return ""def _get_essay(self, soup):if self.sourceA:essay = soup.find("div", class_="text-composition")result = []if essay is not None:essay = essay.find_all("p")for f in essay:while f.find("span", style="color:#00b050") is not None:f.find("span", style="color:#00b050").decompose()while f.find("span", class_="certo") is not None:f.find("span", class_="certo").decompose()for paragraph in essay:result.append(paragraph.get_text())else:essay = soup.find("div", {"id": "texto"})essay.find("section", class_="list-items").decompose()essay = essay.find_all("p")for f in essay:while f.find("span", class_="certo") is not None:f.find("span", class_="certo").decompose()for paragraph in essay:result.append(paragraph.get_text())return " ".join(self._clean_list(result))elif self.sourceB:table = soup.find("article", class_="texto-conteudo entire")table = soup.find("div", class_="area-redacao-corrigida")if table is None:result = Noneelse:for span in soup.find_all("span"):span.decompose()result = table.find_all("p")result = " ".join([paragraph.get_text().strip() for paragraph in result])return resultdef _get_essay_year(self, soup):if self.sourceA:pattern = r"redações corrigidas - \w+/\d+"first_occurrence = re.search(pattern, soup.get_text().lower())matched_url = first_occurrence.group(0) if first_occurrence else Noneyear_pattern = r"\d{4}"return re.search(year_pattern, matched_url).group(0)elif self.sourceB:pattern = r"Enviou seu texto em.*?(\d{4})"match = re.search(pattern, soup.get_text())return match.group(1) if match else -1def _clean_title(self, title):if self.sourceA:smaller_index = title.find("[")if smaller_index == -1:return titleelse:bigger_index = title.find("]")new_title = title[:smaller_index] + title[bigger_index + 1 :]return self._clean_title(new_title.replace(" ", " "))elif self.sourceB:return titledef _clean_list(self, list):if list == []:10 unmodified linesnew_list.append(phrase)return new_listdef parse(self, config_name):for key, filepath in self.paths_dict.items():if key != config_name:continue # TODO improve later, we will only support a single config at a timefull_path = os.path.join(filepath, key)if config_name == "sourceA":self.sourceA = f"{full_path}/sourceA.csv"elif config_name == "sourceB":self.sourceB = f"{full_path}/sourceB.csv"with open(f"{full_path}/{key}.csv", "w", newline="", encoding="utf8") as final_file:18 unmodified linescontinueprompt = os.path.join(full_path, prompt_folder)prompt_essays = [name for name in os.listdir(prompt)]essay_year = self._get_essay_year(self.apply_soup(prompt, "Prompt.html"))for essay in prompt_essays:soup_text = self.apply_soup(prompt, essay)if essay == "Prompt.html":continueessay_title = self._clean_title(self._get_title(soup_text))essay_grades = self._get_grades(soup_text)essay_text = self._get_essay(soup_text)general_comment = self._get_general_comment(soup_text).strip()specific_comment = self._get_specific_comment(soup_text, general_comment)writer.writerow([essay,
aes_enem_dataset.py+274-229