AfriSenti-twitter-sentiment / AfriSenti-twitter-sentiment.py
shmuhammad's picture
Rename AfriSenti.py to AfriSenti-twitter-sentiment.py
19ae2bb
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AfriSenti: A Twitter sentiment dataset for 14 African languages"""
_HOMEPAGE = "https://github.com/afrisenti-semeval/afrisent-semeval-2023"
_DESCRIPTION = """\
AfriSenti is the largest sentiment analysis benchmark dataset for under-represented African languages---covering 110,000+ annotated tweets in 14 African languages (Amharic, Algerian Arabic, Hausa, Igbo, Kinyarwanda, Moroccan Arabic, Mozambican Portuguese, Nigerian Pidgin, Oromo, Swahili, Tigrinya, Twi, Xitsonga, and yoruba).
"""
_CITATION = """\
@inproceedings{muhammad-etal-2023-semeval,
title="{S}em{E}val-2023 Task 12: Sentiment Analysis for African Languages ({A}fri{S}enti-{S}em{E}val)",
author="Muhammad, Shamsuddeen Hassan and
Yimam, Seid and
Abdulmumin, Idris and
Ahmad, Ibrahim Sa'id and
Ousidhoum, Nedjma, and
Ayele, Abinew, and
Adelani, David and
Ruder, Sebastian and
Beloucif, Meriem and
Bello, Shehu Bello and
Mohammad, Saif M.",
booktitle="Proceedings of the 17th International Workshop on Semantic Evaluation (SemEval-2023)",
month=jul,
year="2023",
}
"""
import csv
import textwrap
import pandas as pd
import datasets
LANGUAGES = ['amh', 'hau', 'ibo', 'arq', 'ary', 'yor', 'por', 'twi', 'tso', 'tir', 'orm', 'pcm', 'kin', 'swa']
class AfriSentiConfig(datasets.BuilderConfig):
"""BuilderConfig for AfriSenti"""
def __init__(
self,
text_features,
label_column,
label_classes,
train_url,
valid_url,
test_url,
citation,
**kwargs,
):
"""BuilderConfig for AfriSenti.
Args:
text_features: `dict[string]`, map from the name of the feature
dict for each text field to the name of the column in the txt/csv/tsv file
label_column: `string`, name of the column in the txt/csv/tsv file corresponding
to the label
label_classes: `list[string]`, the list of classes if the label is categorical
train_url: `string`, url to train file from
valid_url: `string`, url to valid file from
test_url: `string`, url to test file from
citation: `string`, citation for the data set
**kwargs: keyword arguments forwarded to super.
"""
super(AfriSentiConfig, self).__init__(version=datasets.Version("1.0.0", ""), **kwargs)
self.text_features = text_features
self.label_column = label_column
self.label_classes = label_classes
self.train_url = train_url
self.valid_url = valid_url
self.test_url = test_url
self.citation = citation
class AfriSenti(datasets.GeneratorBasedBuilder):
"""AfriSenti benchmark"""
BUILDER_CONFIGS = []
for lang in LANGUAGES:
BUILDER_CONFIGS.append(
AfriSentiConfig(
name=lang,
description=textwrap.dedent(
f"""\
{lang} dataset."""
),
text_features={"tweet": "tweet"},
label_classes=["positive", "neutral", "negative"],
label_column="label",
train_url=f"https://raw.githubusercontent.com/afrisenti-semeval/afrisent-semeval-2023/main/data/{lang}/train.tsv",
valid_url=f"https://raw.githubusercontent.com/afrisenti-semeval/afrisent-semeval-2023/main/data/{lang}/dev.tsv",
test_url=f"https://raw.githubusercontent.com/afrisenti-semeval/afrisent-semeval-2023/main/data/{lang}/test.tsv",
citation=textwrap.dedent(
f"""\
{lang} citation"""
),
),
)
def _info(self):
features = {text_feature: datasets.Value("string") for text_feature in self.config.text_features}
features["label"] = datasets.features.ClassLabel(names=self.config.label_classes)
return datasets.DatasetInfo(
description=self.config.description,
features=datasets.Features(features),
citation=self.config.citation,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
train_path = dl_manager.download_and_extract(self.config.train_url)
valid_path = dl_manager.download_and_extract(self.config.valid_url)
test_path = dl_manager.download_and_extract(self.config.test_url)
return [
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": train_path}),
datasets.SplitGenerator(name=datasets.Split.VALIDATION, gen_kwargs={"filepath": valid_path}),
datasets.SplitGenerator(name=datasets.Split.TEST, gen_kwargs={"filepath": test_path}),
]
def _generate_examples(self, filepath):
df = pd.read_csv(filepath, sep='\t')
print('-'*100)
print(df.head())
print('-'*100)
for id_, row in df.iterrows():
tweet = row["tweet"]
label = row["label"]
yield id_, {"tweet": tweet, "label": label}