code
stringlengths
17
6.64M
class Bretschneider2017(dataset.Dataset): name = 'bretschneider2017' url = 'http://ub-web.de/research/resources/fb_hate_speech_csv.zip' hash = '5d31274178d342fb6516ee1015a6ec3c8fa7076e2d6313efb43040a6f8ba26af' files = [{'name': 'bretschneider2017en.csv', 'language': 'en', 'type': 'training', 'platform': 'facebook'}] comment = ' ' license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = os.path.join(tmp_file_path, 'fb_hate_speech_csv/comments.csv') file2 = os.path.join(tmp_file_path, 'fb_hate_speech_csv/annotated_comments.csv') tmp_file_path = helpers.join_csvs(file1, 'comment_id', file2, 'comment_id') tmp_file_path = helpers.drop_duplicates(tmp_file_path, ['comment_id']) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'bretschneider2017en.csv')) @classmethod def unify_row(cls, row): row['text'] = row['message'] labels = [] if (row['valence'] == 1): labels.append('moderate') elif (row['valence'] == 2): labels.append('substantially_offending') if (row['target_type'] == 1): labels.append('no_target') elif (row['target_type'] == 2): labels.append('targets_foreigner_refugee') elif (row['target_type'] == 3): labels.append('targets_politicians_government') elif (row['target_type'] == 5): labels.append('targets_other') elif (row['target_type'] == 6): labels.append('targets_unknown') elif (row['target_type'] == 7): labels.append('targets_page_community') elif (row['target_type'] == 8): labels.append('targets_press') row['labels'] = labels row = row.drop(['comment_id', 'post_id', 'anonymized_user', 'message', 'created_at', 'annotator_id', 'entry_number', 'valence', 'target_type']) return row
class Chung2019(dataset.Dataset): name = 'chung2019' url = 'https://raw.githubusercontent.com/marcoguerini/CONAN/master/CONAN/CONAN.json' hash = '511c062b5563affbc78bb2c9d9edafd88fe6419add73b5190865bb42863eacc4' files = [{'name': 'chung2019.csv', 'language': 'en/fr/it', 'type': 'training', 'platform': 'artifical'}] license = 'This resource can be used for research purposes. Please cite the publication above if you use it.' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): with open(tmp_file_path, 'r') as f: a = json.load(f) b = pd.DataFrame(a['conan']) tmp_file_path = (tmp_file_path + '.csv') b.to_csv(tmp_file_path, index=False) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'chung2019.csv')) @classmethod def unify_row(cls, row): row['text'] = row['hateSpeech'] labels = ['hate'] labels.append(row['hsType']) row['labels'] = labels row = row.drop(['cn_id', 'age', 'gender', 'educationLevel', 'cnType', 'hsType', 'hsSubType', 'hateSpeech', 'counterSpeech']) return row @classmethod def unify_format(cls, df): df = df.apply(cls.unify_row, axis=1) return df.drop_duplicates(subset=['text'])
class Coltekin2019(dataset.Dataset): name = 'coltekin2019' url = 'https://coltekin.github.io/offensive-turkish/offenseval2020-turkish.zip' hash = '7977e96255dbc9b8d14893f1b14cbe3dec53c70358503c062c5a59720ec9c2f2' files = [{'name': 'coltekin2019tr.csv', 'language': 'tr', 'type': 'training', 'platform': 'twitter'}] comment = ' ' license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): zip_file_path = helpers.unzip_file(tmp_file_path) file1 = os.path.join(zip_file_path, 'offenseval2020-turkish/offenseval-tr-testset-v1/offenseval-tr-labela-v1.tsv') file1 = helpers.clean_csv(file1, sep=',', names=['lid', 'class']) file2 = os.path.join(zip_file_path, 'offenseval2020-turkish/offenseval-tr-testset-v1/offenseval-tr-testset-v1.tsv') file2 = helpers.clean_csv(file2, sep='\t', names=['rid', 'text'], header=0) tmp_file_path = helpers.join_csvs(file1, 'lid', file2, 'rid') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'coltekin2019tr.csv')) @classmethod def unify_row(cls, row): row['labels'] = [row['class']] row = row.drop(['lid', 'rid', 'class']) return row
class Dataset(ABC): @staticmethod @property @abstractmethod def name(): ' Name of the dataset ' pass @staticmethod @property @abstractmethod def url(): ' URL of the downloadable file ' pass @staticmethod @property def license(): ' License information of the dataset ' return [] @staticmethod @property def hash(): ' SHA256 hash of the downloaded file ' return '' @staticmethod @property def files(): ' List of dicts for each file that will be created during processing.\n \n Each dict should contain the following information:\n name -- the file name\n language -- ISO 639-1 code of the language\n type -- training or test\n platform -- platfrom of the generated data (e.g. twitter, facebook,...)' return [] @classmethod def download(cls, file_name: str): ' Download a file from cls.url\n \n Keyword arguments:\n file_name -- file_path where the downloaded file will be stored (including file name)\n ' return helpers.download_from(cls.url, file_name) @classmethod @abstractmethod def process(cls, tmp_file_path: str, dataset_folder: str, api_config: Optional[Dict]=None): ' Process the downloaded file. The processed file should be copied to the corresponding dataset_folder in this method.\n \n Keyword arguments:\n tmp_file_path -- path of the file to process\n dataset_folder -- path where the resulting file should be stored\n ' pass @classmethod def valid_hash(cls, file: str): ' Calculate the SHA256 hash of the given file and print a warning if the hash differs.\n \n Keyword arguments:\n file -- path of the file to hash\n ' hash = sha256() with open(file, 'rb') as file: while True: chunk = file.read(hash.block_size) if (not chunk): break hash.update(chunk) hash_value = hash.hexdigest() if (cls.hash == hash_value): return True else: print(((((('WARNING: ' + cls.name) + ': Expected Dataset hash to be ') + cls.hash) + ' but was ') + hash_value)) return False @classmethod def unify_row(cls, row: pd.Series): ' This method is called for each row in the dataset. Use this method to filter attributes and rename columns.\n \n Keyword arguments:\n row -- pandas.Series that contains the row\n ' return row @classmethod def translate_row(cls, row: pd.Series, translation: dict): ' This method is called for each row in the dataset. Translate the labels according to config.json.\n \n Keyword arguments:\n row -- pandas.Series that contains the row\n translation -- dict that contains the translations\n ' translated_labels = [] if (type(row['labels']) == str): row['labels'] = ast.literal_eval(row['labels']) for i in row['labels']: translated_labels.extend(translation.get(i, [i])) row['labels'] = list(set(translated_labels)) return row @classmethod def unify(cls, config: Dict, dataset_name: str): ' Perform unification of the dataset files\n \n Keyword arguments:\n config -- supplied config\n dataset_name -- name of the dataset to be unified\n ' dataset_folder = os.path.join(config['file_directory'], dataset_name) for file in cls.files: df = pd.read_csv(os.path.join(dataset_folder, file['name'])) df = cls.unify_format(df) if (config and (file['name'] in config['datasets'])): df = cls.translate_labels(df, config['datasets'][file['name']]['translation']) df.to_csv(os.path.join(dataset_folder, file['name']), index_label='id', quoting=csv.QUOTE_NONNUMERIC, sep='\t') @classmethod def translate_labels(cls, df: pd.DataFrame, translation: dict): ' Perform label translation of the dataset file\n \n Keyword arguments:\n df -- pandas.DataFrame that contains the data\n translation -- dict that contains the translations\n ' return df.apply(cls.translate_row, axis=1, args=(translation,)) @classmethod def unify_format(cls, df: pd.DataFrame): ' Calls the unfiy method for each entry of the dataset\n \n Keyword arguments:\n df -- pandas.DataFrame that contains the dataset data\n ' return df.apply(cls.unify_row, axis=1)
class Davidson2017(dataset.Dataset): name = 'davidson2017' url = 'https://github.com/t-davidson/hate-speech-and-offensive-language/raw/master/data/labeled_data.csv' hash = 'fcb8bc7c68120ae4af04a5b9acd58585513ede11e1548ebf36a5c2040b6f6281' files = [{'name': 'davidson2017en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] license = 'MIT License\n\nCopyright (c) 2017 Tom Davidson\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'davidson2017en.csv')) @classmethod def unify_row(cls, row): row['text'] = row['tweet'] labels = [] if (row['class'] == 0): labels.append('hate') if (row['class'] == 1): labels.append('offensive') if (row['class'] == 2): labels.append('normal') row['labels'] = labels row = row.drop(['Unnamed: 0', 'count', 'hate_speech', 'offensive_language', 'neither', 'class', 'tweet']) return row
class Elsherief2018(dataset.Dataset): name = 'elSherief2018' url = 'https://github.com/mayelsherif/hate_speech_icwsm18/archive/master.zip' hash = '34365d3d398b0a345a4278df30d851761cb6dc34c7a38f4bdfb77f20fae164c2' files = [{'name': 'elSherief2018en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) base_path = os.path.join(tmp_file_path, 'hate_speech_icwsm18-master') files = {os.path.join(base_path, 'twitter_hashtag_based_datasets/ethn_blackpeoplesuck.csv'): ['racism', 'ethnicity', 'black'], os.path.join(base_path, 'twitter_hashtag_based_datasets/ethn_whitepower.csv'): ['racism', 'ethnicity', 'white'], os.path.join(base_path, 'twitter_hashtag_based_datasets/istandwithhatespeech.csv'): ['prohatespeech'], os.path.join(base_path, 'twitter_hashtag_based_datasets/rel_nomuslimrefugees.csv'): ['racism', 'religious', 'islamophobia'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_boojie.csv'): ['archaic_boojie'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_chinaman.csv'): ['archaic_chinaman'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_hillbilly.csv'): ['archaic_hillbilly'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_surrendermonkey.csv'): ['archaic_surrendermonkey'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_whigger.csv'): ['archaic_whigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_whitenigger.csv'): ['archaic_whitenigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_wigerette.csv'): ['archaic_wigerette'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/archaic_wigger.csv'): ['archaic_wigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/class_bitterclinger.csv'): ['class_bitterclinger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/class_conspiracytheorist.csv'): ['class_conspiracytheorist'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/class_redneck.csv'): ['class_redneck'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/class_rube.csv'): ['class_rube'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/class_trailerparktrash.csv'): ['class_trailerparktrash'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/class_whitetrash.csv'): ['class_whitetrash'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/disability_retard.csv'): ['disability_retard'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/disability_retarded.csv'): ['disability_retarded'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_camelfucker.csv'): ['ethn_camelfucker'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_coonass.csv'): ['ethn_coonass'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_housenigger.csv'): ['ethn_housenigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_mooncricket.csv'): ['ethn_mooncricket'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_nigger.csv'): ['ethn_nigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_raghead.csv'): ['ethn_raghead'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_spic.csv'): ['ethn_spic'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_trailerparktrash.csv'): ['ethn_trailerparktrash'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_trailertrash.csv'): ['ethn_trailertrash'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_wetback.csv'): ['ethn_wetback'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_whitenigger.csv'): ['ethn_whitenigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/ethn_whitetrash.csv'): ['ethn_whitetrash'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/gender_bint.csv'): ['gender_bint'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/gender_cunt.csv'): ['gender_cunt'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/gender_dyke.csv'): ['gender_dyke'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/gender_twat.csv'): ['gender_twat'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_bamboocoon.csv'): ['nation_bamboocoon'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_camelfucker.csv'): ['nation_camelfucker'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_chinaman.csv'): ['nation_chinaman'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_limey.csv'): ['nation_limey'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_plasticpaddy.csv'): ['nation_plasticpaddy'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_sidewayspussy.csv'): ['nation_sidewayspussy'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_surrendermonkey.csv'): ['nation_surrendermonkey'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_whigger.csv'): ['nation_whigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_whitenigger.csv'): ['nation_whitenigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_wigger.csv'): ['nation_wigger'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/nation_zionazi.csv'): ['nation_zionazi'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/rel_camelfucker.csv'): ['rel_camelfucker'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/rel_muzzie.csv'): ['rel_muzzie'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/rel_souptaker.csv'): ['rel_souptaker'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/rel_zionazi.csv'): ['rel_zionazi'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/sexorient_dyke.csv'): ['sexorient_dyke'], os.path.join(base_path, 'twitter_key_phrase_based_datasets/sexorient_faggot.csv'): ['sexorient_faggot']} tmp_file_path = helpers.merge_csvs(files) tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'tweet_id', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'elSherief2018en.csv')) @classmethod def unify_row(cls, row): return row
class Fortuna2019(dataset.Dataset): name = 'fortuna2019' url = 'https://b2share.eudat.eu/api/files/792b86e1-e676-4a0d-971f-b41a1ffb9b18/annotator_classes.csv' hash = 'f759888e9489a030187bbf6fbe005a7c5a6c0c3468882430924d9aaebd84759d' files = [{'name': 'fortuna2019pt.csv', 'language': 'pt', 'type': 'training', 'platform': 'twitter'}] comment = ' ' license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'tweet_id', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'fortuna2019pt.csv')) @classmethod def unify_row(cls, row): labels = row['class'].split('; ') row['labels'] = labels row = row.drop(['class']) return row
class Founta2018(dataset.Dataset): name = 'founta2018' url = 'https://zenodo.org/record/2657374/files/hatespeech_id_label.csv' hash = '35f19a5746eac9be27cd635a09b9ced11569080df10d84fb140ca76164836cef' files = [{'name': 'founta2018en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] comment = ' ' license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, names=['tweet', 'class']) tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'tweet', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'founta2018en.csv')) @classmethod def unify_row(cls, row): row['labels'] = [row['class']] row = row.drop(['class']) return row
class Gao2018(dataset.Dataset): name = 'gao2018' url = 'https://github.com/sjtuprog/fox-news-comments/raw/master/full-comments-u.json' hash = '059152e61f632f1e6671a68214d5618a21e6cf78f2512773e0421b9568aab8cf' files = [{'name': 'gao2018en.csv', 'language': 'en', 'type': 'training', 'platform': 'fox news'}] comment = 'Inflammatory language explicitly or implicitly threatens or demeans a person or agroup based upon a facet of their identity such as gender, ethnicity, or sexualorientation.\n- Excludes insults towards other anonymous users\n- Includes insults of belief systems' license = 'The MIT License\n\nCopyright (c) 2010-2019 Google, Inc. http://angularjs.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.convert_jsonl_to_csv(tmp_file_path) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'gao2018en.csv')) @classmethod def unify_row(cls, row): labels = [] if (row['label'] == 0): labels.append('normal') if (row['label'] == 1): labels.append('hate') row['labels'] = labels row = row.drop(['title', 'succ', 'meta', 'user', 'mentions', 'prev', 'label']) return row
class Gibert2018(dataset.Dataset): name = 'gibert2018' url = 'https://github.com/Vicomtech/hate-speech-dataset/archive/master.zip' hash = 'acc0d7ce40e22cf019daa752a5136049a45462b9ba4eab8bf40ea82dcd867eba' files = [{'name': 'gibert2018en.csv', 'language': 'en', 'type': 'training', 'platform': 'stormfront'}] license = 'The resources in this repository are licensed under the Creative Commons Attribution-ShareAlike 3.0 Spain\nLicense. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/es/ or send\na letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.' @classmethod def replace_csv_entry_with_filecontents(cls, row, directory): fid = row['file_id'] with open(os.path.join(directory, 'all_files', (fid + '.txt')), 'r', encoding='utf-8') as f: row['text'] = '\n'.join(f.readlines()) return row @classmethod def merge_txt_to_csv(cls, directory): df = pd.read_csv(os.path.join(directory, 'annotations_metadata.csv'), encoding='utf-8') df = df.apply(cls.replace_csv_entry_with_filecontents, axis=1, args=(directory,)) output_file = os.path.join(directory, (cls.name + '.csv')) df.to_csv(output_file) return output_file @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): extraction_dir = helpers.unzip_file(tmp_file_path) tmp_file_path = cls.merge_txt_to_csv(os.path.join(extraction_dir, 'hate-speech-dataset-master')) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'gibert2018en.csv')) @classmethod def unify_row(cls, row): row['labels'] = [row['label']] row = row.drop(['Unnamed: 0', 'subforum_id', 'file_id', 'user_id', 'num_contexts', 'label']) return row
def download_from(url: str, destination_file: str) -> str: ' Downloads a file to the specified destination.\n \n Keyword arguments:\n url -- url of the file to download\n destination_file -- path to the file to download to\n\n Returns path to the downloaded file.\n ' try: with urlopen(url) as response: os.makedirs(os.path.dirname(destination_file), exist_ok=True) with open(destination_file, 'wb') as f: shutil.copyfileobj(response, f) return destination_file except URLError as e: print('Additional certificate installation is needed for MacOS. See https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org and https://stackoverflow.com/questions/44649449/brew-installation-of-python-3-6-1-ssl-certificate-verify-failed-certificate/44649450#44649450 for help') raise e
def convert_excel_to_csv(file_name: str) -> str: ' Converts Excel file to CSV file.\n \n Keyword arguments:\n file_name -- path of the Excel file\n\n Returns path to the converted CSV file\n ' new_file = (file_name + '.csv') excel_data = pd.read_excel(file_name) excel_data.to_csv(new_file, index=False) return new_file
def copy_file(source_file: str, destination_file: str) -> str: " Copies a file to a given path. Creates the path if it doesn't exist.\n \n Keyword arguments:\n source_file -- path of the source file\n destination_file -- path of the destination file\n \n Returns path to the destination file\n " os.makedirs(os.path.dirname(destination_file), exist_ok=True) shutil.copyfile(source_file, destination_file) return destination_file
def convert_json_to_csv(file_name: str) -> str: ' Converts JSON file to CSV file\n \n Keyword arguments:\n file_name -- path of the JSON file\n\n Returns path to the converted CSV file\n ' new_file = (file_name + '.csv') json_data = pd.read_json(file_name) json_data.to_csv(new_file, index=False) return new_file
def convert_jsonl_to_csv(file_name: str) -> str: ' Converts JSONL file to CSV file\n \n Keyword arguments:\n file_name -- path of the JSONL file\n\n Returns path to the converted CSV file\n ' new_file = (file_name + '.json') data = [] with open(file_name, 'r') as jsonl_file: for line in jsonl_file: data.append(json.loads(line)) df = pd.DataFrame(data) df.to_csv(new_file, index=False) return new_file
def unzip_file(file_name: str) -> str: ' Unpacks a ZIP file\n \n Keyword arguments:\n file_name -- path of the ZIP file\n\n Returns path to the folder containing the unpacked files.\n ' extraction_dir = os.path.join(os.path.dirname(file_name), (os.path.basename(file_name) + '_extracted')) os.makedirs(extraction_dir, exist_ok=False) with zipfile.ZipFile(file_name) as zip_file: zip_file.extractall(extraction_dir) return extraction_dir
def untarbz_file(file_name: str): ' Unpacks a .tar.bz2 file\n \n Keyword arguments:\n file_name -- path of the .tar.bz2 file\n ' tar = tarfile.open(file_name, 'r:bz2') tar.extractall(path=os.path.dirname(file_name)) tar.close()
def add_column(file_name: str, column_name: str, column_value) -> str: ' Inserts a new column into a CSV file.\n \n Keyword arguments:\n file_name -- path of the CSV file\n column_name -- name of the new column\n column_value -- default value that is added in each line\n\n Returns path to the resulting file.\n ' new_file = (file_name + '_new_column') df = pd.read_csv(file_name) df.insert(loc=0, column=column_name, value=([column_value] * df.count().max())) df.to_csv(new_file, index=False) return new_file
def clean_csv(file_name: str, names: [str]=None, header: int='infer', sep: str=',', dtype: dict=None) -> str: ' Loads CSV into Dataframe and exports it as CSV again to archive a clean CSV with standard seperators. Can be used to add column names.\n \n Keyword arguments:\n file_name -- path to the file\n names -- list that contains the names for the columns\n header -- set to 0 if an existing header should be overwritten\n sep -- seperator of the CSV file\n dtype -- dict containing the data types of the columns\n\n Returns path to the resulting file.\n ' new_file = (file_name + '_clean') df = pd.read_csv(file_name, names=names, sep=sep, header=header, dtype=dtype) df.to_csv(new_file, index=False, quoting=csv.QUOTE_NONNUMERIC) return new_file
def join_csvs(file1: str, column1: str, file2: str, column2: str, how: str='inner') -> str: ' Joins two CSVs on a given column\n\n Keyword arguments:\n file1 -- path of the first CSV\n column1 -- name of the column to join on in file1\n file2 -- path of the second CSV\n column2 -- name of the column to join on in file2\n how -- joint type of the pandas DataFrame.merge function\n\n Returns path to the resulting file.\n ' new_file = (file1 + '_joined') df1 = pd.read_csv(file1) df2 = pd.read_csv(file2) df = df1.merge(df2, how=how, left_on=column1, right_on=column2) df.to_csv(new_file, index=False) return new_file
def drop_duplicates(file_name: str, columns: [str]) -> str: ' Drops all duplicates in a CSV file\n\n Keyword arguments:\n file_name -- path of the CSV file\n columns -- list of columns to perform duplicate checking on\n\n Returns path to the resulting file.\n ' new_file = (file_name + '_dropped') df = pd.read_csv(file_name) df = df.drop_duplicates(columns) df.to_csv(new_file, index=False) return new_file
def merge_csvs(files: dict) -> str: ' Merge multiple CSV files into one.\n\n Keyword arguments:\n files -- dictionary with the filename as a key and a list of attributes that will be added in a label column\n\n Returns path to the resulting file.\n ' new_file = (list(files.keys())[0] + '_merged') merged_df = pd.DataFrame() for file in files: df = pd.read_csv(file) if len(files[file]): df.insert(loc=0, column='labels', value=([files[file]] * df.count().max())) merged_df = merged_df.append(df) merged_df.to_csv(new_file, index=False) return new_file
def download_tweets_for_csv(file_name: str, column: str, api_data: Dict) -> str: ' Replaces the Tweet IDs of a CSV file with the actual tweets.\n\n Keyword arguments:\n file_name -- path of the CSV file\n column -- name of the column containing the tweet IDs\n\n Returns path to the resulting file.\n ' def hydrate(row, translation, columns): if (str(row[column]) in translation): row['text'] = translation[row[column]] row = row.drop(column) return row else: ser = pd.Series(index=columns) ser = ser.drop(column) return ser new_file = (file_name + '_with_tweets') df = pd.read_csv(file_name, dtype={column: str}) t = Twarc(api_data['twitter']['consumer_key'], api_data['twitter']['consumer_secret'], api_data['twitter']['access_token'], api_data['twitter']['access_token_secret']) translation = {} for tweet in t.hydrate(df[column]): translation[str(tweet['id'])] = tweet['full_text'] df = df.apply(hydrate, axis=1, args=(translation, df.columns)).dropna(how='all') df.to_csv(new_file, index=False, quoting=csv.QUOTE_NONNUMERIC) return new_file
def extract_sql_tables(file_name: str) -> str: ' Extracts tables from SQL file and saves them as CSV.\n\n Keyword arguments:\n file_name -- path of the SQL file\n\n Returns path of the directory that contains the resulting files.\n ' def find_tables(dump_filename): table_list = [] with open(dump_filename, 'r') as f: for line in f: line = line.strip() if line.lower().startswith('create table'): table_name = re.findall('create table `([\\w_]+)`', line.lower()) table_list.extend(table_name) return table_list def read_dump(dump_filename: str, output_dir: str, target_table: str) -> None: column_names = [] rows = [] read_mode = 0 with open(dump_filename, 'r') as f: for line in f: line = line.strip() if (line.lower().startswith('insert') and (target_table in line)): read_mode = 2 if (line.lower().startswith('create table') and (target_table in line)): read_mode = 1 continue if (read_mode == 0): continue elif (read_mode == 1): if line.lower().startswith('primary'): read_mode = 0 continue colheader = re.findall('`([\\w_]+)`', line) for col in colheader: column_names.append(col.strip()) elif (read_mode == 2): if line.endswith(';'): end_index = (- 1) else: end_index = 0 data = ast.literal_eval(line[(line.find('VALUES') + 7):end_index]) try: for item in data: row = {} for (key, value) in zip(column_names, item): row[key] = value rows.append(row) except IndexError: pass if line.endswith(';'): df = pd.DataFrame(rows, columns=column_names) break df.to_csv(os.path.join(output_dir, (target_table + '.csv')), index=False) output_dir = os.path.join(os.path.dirname(file_name), 'extracted') os.makedirs(output_dir, exist_ok=False) table_list = find_tables(file_name) if (len(table_list) > 0): for table in table_list: read_dump(file_name, output_dir, table) return output_dir
class Ibrohim2018(dataset.Dataset): name = 'ibrohim2018' url = 'https://github.com/okkyibrohim/id-abusive-language-detection/raw/master/re_dataset_three_labels.csv' hash = '8e88d5bf4d98f86d7c8fb9c010008246e206814e8dbe5695ec7de4a76812bc86' files = [{'name': 'ibrohim2018id.csv', 'language': 'id', 'type': 'training', 'platform': 'twitter'}] comment = '1 (not abusive language), 2 (abusive but not offensive), and 3 (offensive language)' license = 'This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'ibrohim2018id.csv')) @classmethod def unify_row(cls, row): row['text'] = row['Tweet'] labels = [] if (row['Label'] == 1): labels.append('none') if (row['Label'] == 2): labels.append('abusive') if (row['Label'] == 3): labels.append('offensive') row['labels'] = labels row = row.drop(['Tweet', 'Label']) return row
class Ibrohim2019(dataset.Dataset): name = 'ibrohim2019' url = 'https://github.com/okkyibrohim/id-multi-label-hate-speech-and-abusive-language-detection/raw/master/re_dataset.csv' hash = '44c04e31ad4b7ee4a95f1884e7af4da2c44b69762143eb2de0ede7f90502735e' files = [{'name': 'ibrohim2019id.csv', 'language': 'id', 'type': 'training', 'platform': 'twitter'}] comment = 'HS : hate speech label;\nAbusive : abusive language label;\nHS_Individual : hate speech targeted to an individual;\nHS_Group : hate speech targeted to a group;\nHS_Religion : hate speech related to religion/creed;\nHS_Race : hate speech related to race/ethnicity;\nHS_Physical : hate speech related to physical/disability;\nHS_Gender : hate speech related to gender/sexual orientation;\nHS_Gender : hate related to other invective/slander;\nHS_Weak : weak hate speech;\nHS_Moderate : moderate hate speech;\nHS_Strong : strong hate speech.\n' license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'ibrohim2019id.csv')) @classmethod def unify_row(cls, row): row['text'] = row['Tweet'] labels = [] for label in ['HS', 'Abusive', 'HS_Individual', 'HS_Group', 'HS_Religion', 'HS_Race', 'HS_Physical', 'HS_Gender', 'HS_Other', 'HS_Weak', 'HS_Moderate', 'HS_Strong']: if (row[label] == 1): labels.append(label) row['labels'] = labels row = row.drop(['Tweet', 'HS', 'Abusive', 'HS_Individual', 'HS_Group', 'HS_Religion', 'HS_Race', 'HS_Physical', 'HS_Gender', 'HS_Other', 'HS_Weak', 'HS_Moderate', 'HS_Strong']) return row
class Jha2017(dataset.Dataset): name = 'jha2017' url = 'https://github.com/AkshitaJha/NLP_CSS_2017/archive/master.zip' hash = 'da7392bfa1b5c7d6aa8540b1943abd5bf941f1a8e8e12dfa37335164c9752edb' files = [{'name': 'jha2017en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] comment = "The file benevolent_sexist.tsv contains Tweet ID's of tweets that exhibit benevolent sexism. The file hostile_sexist.tsv contains Tweet ID's of tweets that are hostile in nature. The hostile sexist tweets were part of the Hate Speech Dataset (Waseem and Hovy, 2016)." license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) benevolent_file = os.path.join(tmp_file_path, 'NLP_CSS_2017-master/benevolent_sexist.tsv') hostile_file = os.path.join(tmp_file_path, 'NLP_CSS_2017-master/hostile_sexist.tsv') benevolent_file = helpers.clean_csv(benevolent_file, ['tweet_id']) hostile_file = helpers.clean_csv(hostile_file, ['tweet_id']) tmp_file_path = helpers.merge_csvs({hostile_file: ['sexist', 'hostile'], benevolent_file: ['sexist', 'benevolent']}) tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'tweet_id', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'jha2017en.csv'))
class Kulkarni2021(dataset.Dataset): name = 'kulkarni2021' url = 'https://github.com/l3cube-pune/MarathiNLP/raw/main/L3CubeMahaSent%20Dataset/tweets-train.csv' hash = '1416e35f859f7473c536432954affe6460fad7a0a0d2c3889ce7a408347832d5' files = [{'name': 'kulkarni2021mr.csv', 'language': 'mr', 'type': 'training', 'platform': 'tweets'}] comment = 'Positive(1), Negative(-1) and Neutral(0)' license = '' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'kulkarni2021mr.csv')) @classmethod def unify_row(cls, row): row['text'] = row['tweet'] row['labels'] = [str(row['label'])] row = row.drop(['tweet', 'label']) return row
class Kumar2018(dataset.Dataset): name = 'kumar2018' url = 'https://github.com/SilentFlame/AggressionDetection/raw/master/DataPre-Processing/processedDataWithoutID.txt' hash = '06154c3f8b85254af949e3e83aca32c1b4e25af322f18221a58d02453132dd48' files = [{'name': 'kumar2018hing.csv', 'language': 'hing', 'type': 'training', 'platform': 'facebook'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, names=['text', 'class'], sep='\t') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'kumar2018hing.csv')) @classmethod def unify_row(cls, row): labels = [row['class']] row['labels'] = labels row = row.drop(['class']) return row
class Mandl2019en(dataset.Dataset): name = 'mandl2019en' url = 'https://hasocfire.github.io/hasoc/2019/files/english_dataset.zip' hash = '1b4bda7904193be59ed768675fc1d65f172f7bf92af3de6394e8deda8afb640e' files = [{'name': 'mandl2019en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter and facebook'}] license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(tmp_file_path, 'english_dataset/english_dataset.tsv'), sep='\t') file2 = helpers.clean_csv(os.path.join(tmp_file_path, 'english_dataset/hasoc2019_en_test-2919.tsv'), sep='\t') tmp_file_path = helpers.merge_csvs({file1: [], file2: []}) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mandl2019en.csv')) @classmethod def unify_row(cls, row): labels = [] if (row['task_1'] == 'NOT'): labels.append('normal') elif (row['task_2'] == 'HATE'): labels.append('hate') elif (row['task_2'] == 'OFFN'): labels.append('offensive') elif (row['task_2'] == 'PRFN'): labels.append('profane') if (row['task_3'] == 'TIN'): labels.append('targeted') elif (row['task_3'] == 'UNT'): labels.append('untargeted') row['labels'] = labels row = row.drop(['text_id', 'task_1', 'task_2', 'task_3']) return row
class Mandl2019ger(dataset.Dataset): name = 'mandl2019ger' url = 'https://hasocfire.github.io/hasoc/2019/files/german_dataset.zip' hash = 'cba78f437b9628c216a4ae0487fbb30e15d9c4b235aa55d9a0d4742fdc8d11c5' files = [{'name': 'mandl2019ger.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter and facebook'}] license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(tmp_file_path, 'german_dataset/german_dataset.tsv'), sep='\t') file2 = helpers.clean_csv(os.path.join(tmp_file_path, 'german_dataset/hasoc_de_test_gold.tsv'), sep='\t') tmp_file_path = helpers.merge_csvs({file1: [], file2: []}) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mandl2019ger.csv')) @classmethod def unify_row(cls, row): labels = [] if (row['task_1'] == 'NOT'): labels.append('normal') elif (row['task_2'] == 'HATE'): labels.append('hate') elif (row['task_2'] == 'OFFN'): labels.append('offensive') elif (row['task_2'] == 'PRFN'): labels.append('profane') row['labels'] = labels row = row.drop(['text_id', 'task_1', 'task_2']) return row
class Mandl2019hind(dataset.Dataset): name = 'mandl2019hind' url = 'https://hasocfire.github.io/hasoc/2019/files/hindi_dataset.zip' hash = 'd419780fe825f9946e3a03da4cf3fdf41699b188932d3662ca304693829994ad' files = [{'name': 'mandl2019hind.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter and facebook'}] license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(tmp_file_path, 'hindi_dataset/hindi_dataset.tsv'), sep='\t') file2 = helpers.clean_csv(os.path.join(tmp_file_path, 'hindi_dataset/hasoc2019_hi_test_gold_2919.tsv'), sep='\t') tmp_file_path = helpers.merge_csvs({file1: [], file2: []}) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mandl2019hind.csv')) @classmethod def unify_row(cls, row): labels = [] if (row['task_1'] == 'NOT'): labels.append('normal') elif (row['task_2'] == 'HATE'): labels.append('hate') elif (row['task_2'] == 'OFFN'): labels.append('offensive') elif (row['task_2'] == 'PRFN'): labels.append('profane') if (row['task_3'] == 'TIN'): labels.append('targeted') elif (row['task_3'] == 'UNT'): labels.append('untargeted') row['labels'] = labels row = row.drop(['text_id', 'task_1', 'task_2', 'task_3']) return row
class Mathur2018(dataset.Dataset): name = 'mathur2018' url = 'https://github.com/pmathur5k10/Hinglish-Offensive-Text-Classification/raw/master/Hinglish_Profanity_List.csv' hash = 'e09ccb2c46616a59faa5d80d205a6e49b01b4781c1eb31587e1098a86c751260' files = [{'name': 'mathur2018hing.csv', 'language': 'hing', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, names=['text', 'translation', 'class']) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mathur2018hing.csv')) @classmethod def unify_row(cls, row): labels = [('hate:' + str(row['class']))] row['labels'] = labels row = row.drop(['translation', 'class']) return row
class Mubarak2017aljazeera(dataset.Dataset): name = 'mubarak2017aljazeera' url = 'http://alt.qcri.org/~hmubarak/offensive/AJCommentsClassification-CF.xlsx' hash = 'afa00e36ff5492c1bbdd42a0e4979886f40d00f1aa5517807a957e22fb517670' files = [{'name': 'mubarak2017ar_aljazeera.csv', 'language': 'ar', 'type': 'training', 'platform': 'twitter'}] comment = 'Annotation\tMeaning\n0\tNORMAL_LANGUAGE\n-1\tOFFENSIVE_LANGUAGE\n-2\tOBSCENE_LANGUAGE' license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.convert_excel_to_csv(tmp_file_path) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mubarak2017ar_aljazeera.csv')) @classmethod def unify_row(cls, row): row['text'] = row['body'] labels = [] if (row['languagecomment'] == 0): labels.append('normal') if (row['languagecomment'] == (- 1)): labels.append('offensive') if (row['languagecomment'] == (- 2)): labels.append('obscene') row['labels'] = labels row = row.drop(['_unit_id', '_golden', '_unit_state', '_trusted_judgments', '_last_judgment_at', 'languagecomment', 'languagecomment:confidence', 'articletitle', 'body', 'bodylen', 'insdt', 'languagecomment_gold', 'link', 'serial', 'words']) return row
class Mubarak2017twitter(dataset.Dataset): name = 'mubarak2017twitter' url = 'http://alt.qcri.org/~hmubarak/offensive/TweetClassification-Summary.xlsx' hash = '606f73388adae60af740779f9b501f30cf9adac82afe15a46fe07155db3823cf' files = [{'name': 'mubarak2017ar_twitter.csv', 'language': 'ar', 'type': 'training', 'platform': 'twitter'}] comment = 'Annotation\tMeaning\n0\tNORMAL_LANGUAGE\n-1\tOFFENSIVE_LANGUAGE\n-2\tOBSCENE_LANGUAGE' license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.convert_excel_to_csv(tmp_file_path) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mubarak2017ar_twitter.csv')) @classmethod def unify_row(cls, row): labels = [] if (row['aggregatedAnnotation'] == 0): labels.append('normal') if (row['aggregatedAnnotation'] == (- 1)): labels.append('offensive') if (row['aggregatedAnnotation'] == (- 2)): labels.append('obscene') row['labels'] = labels row = row.drop(['#', 'type', 'aggregatedAnnotation', 'aggregatedAnnotationConfidence', 'annotator1', 'annotator2', 'annotator3']) return row
class Mulki2019(dataset.Dataset): name = 'mulki2019' url = 'https://github.com/Hala-Mulki/L-HSAB-First-Arabic-Levantine-HateSpeech-Dataset/raw/master/Dataset/L-HSAB' hash = '3fc5e06ab624b47e404a0530388631c4894c323ca038e726ce6dd3d0e6a371e3' files = [{'name': 'mulki2019ar.csv', 'language': 'ar', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): df = pd.read_csv(tmp_file_path, sep='\t') df.to_csv(tmp_file_path, index=False) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'mulki2019ar.csv')) @classmethod def unify_row(cls, row): row['text'] = row['Tweet'] labels = [row['Class']] row['labels'] = labels row = row.drop(['Class', 'Tweet']) return row
class Novak2021(dataset.Dataset): name = 'novak2021' url = 'https://www.clarin.si/repository/xmlui/bitstream/handle/11356/1398/IMSyPP_SI_anotacije_training-clarin.csv?sequence=6&isAllowed=y' hash = 'fd6b85fa783afee7b6a61c99eb2eb16d59edda75af8b7df9a1f9ab4f2f59e458' files = [{'name': 'novak2021sl.csv', 'language': 'gr', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'ID', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'novak2021sl.csv')) @classmethod def unify_row(cls, row): row['labels'] = [str(row['vrsta'])] row = row.drop(['vrsta', 'tarča', 'annotator']) return row
class Ousidhoum2019(dataset.Dataset): name = 'ousidhoum2019' url = 'https://github.com/HKUST-KnowComp/MLMA_hate_speech/raw/master/hate_speech_mlma.zip' hash = '56db7efb1b64a2570f63d0cdb48d119c5e32eccff13f3c22bf17a4331956dc43' files = [{'name': 'ousidhoum2019ar.csv', 'language': 'ar', 'type': 'training', 'platform': 'twitter'}, {'name': 'ousidhoum2019en_with_stopwords.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}, {'name': 'ousidhoum2019en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}, {'name': 'ousidhoum2019fr.csv', 'language': 'fr', 'type': 'training', 'platform': 'twitter'}] license = 'MIT License\n\nCopyright (c) 2019 HKUST-KnowComp\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_dir_path = helpers.unzip_file(tmp_file_path) helpers.copy_file(os.path.join(tmp_dir_path, 'hate_speech_mlma/ar_dataset.csv'), os.path.join(dataset_folder, 'ousidhoum2019ar.csv')) helpers.copy_file(os.path.join(tmp_dir_path, 'hate_speech_mlma/en_dataset.csv'), os.path.join(dataset_folder, 'ousidhoum2019en.csv')) helpers.copy_file(os.path.join(tmp_dir_path, 'hate_speech_mlma/fr_dataset.csv'), os.path.join(dataset_folder, 'ousidhoum2019fr.csv')) helpers.copy_file(os.path.join(tmp_dir_path, 'hate_speech_mlma/en_dataset_with_stop_words.csv'), os.path.join(dataset_folder, 'ousidhoum2019en_with_stopwords.csv')) @classmethod def unify_row(cls, row): row['text'] = row['tweet'] labels = row['sentiment'].split('_') labels.append(row['directness']) row['labels'] = labels row = row.drop(['annotator_sentiment', 'target', 'group', 'directness', 'HITId', 'sentiment', 'tweet']) return row
class Pitenis2020(dataset.Dataset): name = 'pitenis2020' url = 'https://zpitenis.com/downloads/offenseval2020-greek.zip' hash = '4b1cbbcf1795b078d57640144b6cd72686b6e326dcc65e801799680f3a47bbb1' files = [{'name': 'pitenis2020gr.csv', 'language': 'gr', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): extracted_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(extracted_file_path, 'offenseval-gr-testsetv1/offenseval-gr-labela-v1.csv'), names=['lid', 'category']) file2 = helpers.clean_csv(os.path.join(extracted_file_path, 'offenseval-gr-testsetv1/offenseval-gr-test-v1.tsv'), names=['rid', 'tweet'], sep='\t', header=0) tmp_file_path = helpers.join_csvs(file1, 'lid', file2, 'rid') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'pitenis2020gr.csv')) @classmethod def unify_row(cls, row): row['text'] = row['tweet'] row['labels'] = [row['category']] row = row.drop(['lid', 'rid', 'tweet', 'category']) return row
class Qian2019(dataset.Dataset): name = 'qian2019' url = 'https://github.com/jing-qian/A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-Speech/archive/master.zip' hash = 'e2774f61af64942373e76e3928269bf6b7d8b41d5f5dcbcac9e760d4e93ef6b4' files = [{'name': 'qian2019en_gab.csv', 'language': 'en', 'type': 'training', 'platform': 'gab'}, {'name': 'qian2019en_reddit.csv', 'language': 'en', 'type': 'training', 'platform': 'reddit'}] license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) helpers.copy_file(os.path.join(tmp_file_path, 'A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-Speech-master/data/gab.csv'), os.path.join(dataset_folder, 'qian2019en_gab.csv')) helpers.copy_file(os.path.join(tmp_file_path, 'A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-Speech-master/data/reddit.csv'), os.path.join(dataset_folder, 'qian2019en_reddit.csv')) @classmethod def unify_format(cls, df): df = df.fillna({'hate_speech_idx': '[]'}) clean_data = [] for (i, row) in df.iterrows(): for (idx, comment) in enumerate(row['text'].split('\n')): labels = [] if ((idx + 1) in json.loads(row['hate_speech_idx'])): labels.append('hate') if comment: clean_data.append({'text': comment, 'labels': labels}) return pd.DataFrame(clean_data)
class Ross2017(dataset.Dataset): name = 'ross2017' url = 'https://github.com/UCSM-DUE/IWG_hatespeech_public/raw/master/german%20hatespeech%20refugees.csv' hash = 'b0784b8c00f02d16cee8b1227b8e8968760885d3d87b68762ba51b4c3156714f' files = [{'name': 'ross2018de.csv', 'language': 'de', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'ross2018de.csv')) @classmethod def unify_row(cls, row): row['text'] = row['Tweet'] labels = [] if ((row['HatespeechOrNot (Expert 1)'] == 'YES') or (row['HatespeechOrNot (Expert 2)'] == 'YES')): labels.append('hate') else: labels.append('nohate') row['labels'] = labels row = row.drop(['Tweet', 'HatespeechOrNot (Expert 1)', 'HatespeechOrNot (Expert 2)', 'Hatespeech Rating (Expert 2)']) return row
class Sanguinetti2018(dataset.Dataset): name = 'sanguinetti2018' url = 'https://github.com/msang/hate-speech-corpus/raw/master/IHSC_ids.tsv' hash = '9c8fd7224362e5fa488ba70dbc1ae55cfc0a452d303c1508e3607e2cc2e20fa1' files = [{'name': 'sanguinetti2018it.csv', 'language': 'it', 'type': 'training', 'platform': 'twitter'}] comment = '' license = 'If you use the resource, please cite:\n\n@InProceedings{SanguinettiEtAlLREC2018,\n author = {Manuela Sanguinetti and Fabio Poletto and Cristina Bosco and Viviana Patti and Marco Stranisci},\n title = {An Italian Twitter Corpus of Hate Speech against Immigrants},\n booktitle = {Proceedings of the 11th Conference on Language Resources and Evaluation (LREC2018), May 2018, Miyazaki, Japan},\n month = {},\n year = {2018},\n address = {},\n publisher = {},\n pages = {2798--2895},\n url = {}\n}\n' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, sep='\t') tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'tweet_id', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'sanguinetti2018it.csv')) @classmethod def unify_row(cls, row): labels = [] if (row['hs'] == 'yes'): labels.append('hate') if (row['aggressiveness'] != 'no'): labels.append((row['aggressiveness'] + '_aggressiveness')) if (row['offensiveness'] != 'no'): labels.append((row['aggressiveness'] + '_offensiveness')) if (row['irony'] == 'yes'): labels.append('irony') if (row['stereotype'] == 'yes'): labels.append('stereotype') row['labels'] = labels row = row.drop(['aggressiveness', 'hs', 'irony', 'offensiveness', 'stereotype']) return row
class Sigurbergsson2019(dataset.Dataset): name = 'sigurbergsson2019' url = 'https://ndownloader.figshare.com/files/22476731' hash = 'fb5c41c385062af222f68c8eb298912644b2f7a86d91769451a26c081f6822f0' files = [{'name': 'sigurbergsson2019da.csv', 'language': 'da', 'type': 'training', 'platform': 'unknown'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): helpers.untarbz_file(tmp_file_path) tmp_file_path = os.path.join(os.path.dirname(tmp_file_path), 'dkhate/oe20da_data/offenseval-da-training-v1.tsv') tmp_file_path = helpers.clean_csv(tmp_file_path, sep='\t') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'sigurbergsson2019da.csv')) @classmethod def unify_row(cls, row): row['text'] = row['tweet'] if ((row['subtask_a'] != 'OFF') and (row['subtask_a'] != 'NOT')): row['labels'] = [] else: row['labels'] = [row['subtask_a']] row = row.drop(['id', 'tweet', 'subtask_a']) return row
class Waseem2016(dataset.Dataset): name = 'waseem2016' url = 'https://github.com/ZeerakW/hatespeech/raw/master/NAACL_SRW_2016.csv' hash = 'a23875e68792a9d66cafea3c1c42b0b563b35fbd6163a66c3c4451976ebcdcff' files = [{'name': 'waseem2016en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] license = ' ' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, ['twitter_ids', 'tag']) tmp_file_path = helpers.download_tweets_for_csv(tmp_file_path, 'twitter_ids', api_config) helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'waseem2016en.csv')) @classmethod def unify_row(cls, row): row['labels'] = [row['tag']] row = row.drop(['tag']) return row
class Wiegand2018(dataset.Dataset): name = 'wiegand2018' url = 'https://github.com/uds-lsv/GermEval-2018-Data/raw/master/germeval2018.test.txt' hash = '45f31510b305d080a933d4087b8d34f7a5e4087141718955b90357ca730074f2' files = [{'name': 'wiegand2018de.csv', 'language': 'de', 'type': 'training', 'platform': 'twitter'}] license = 'lf you publish any work using the GermEval-2018 data, please cite the following publication:\n\nMichael Wiegand, Melanie Siegel, and Josef Ruppenhofer: "Overview of the GermEval 2018 Shared Task on the Identification of Offensive Language", in Proceedings of the GermEval, 2018, Vienna, Austria.' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, names=['text', 'tag1', 'tag2'], sep='\t') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'wiegand2018de.csv')) @classmethod def unify_row(cls, row): labels = [row['tag1'], row['tag2']] row['labels'] = labels row = row.drop(['tag1', 'tag2']) return row
class Wulczyn2017aggressive(dataset.Dataset): name = 'wulczyn2017aggressive' url = 'https://ndownloader.figshare.com/articles/4267550/versions/5' hash = '9e48068af1fbbe893af4df1b629ceebf924dc723a290c7bc473d2a8a8aac3529' files = [{'name': 'wulczyn2017en_aggressive.csv', 'language': 'en', 'type': 'training', 'platform': 'wikipedia'}] license = ' ' @classmethod def valid_hash(cls, file): 'do not check hash since it differs for each download' return @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(tmp_file_path, 'aggression_annotated_comments.tsv'), sep='\t') file2 = helpers.clean_csv(os.path.join(tmp_file_path, 'aggression_annotations.tsv'), sep='\t') df1 = pd.read_csv(file1) df1['comment'] = df1['comment'].apply((lambda x: x.replace('NEWLINE_TOKEN', ' '))) df1['comment'] = df1['comment'].apply((lambda x: x.replace('TAB_TOKEN', ' '))) df1.to_csv((file1 + '_endings'), index=False) df2 = pd.read_csv(file2) labels = (df2.groupby(['rev_id']).mean() > 0.5) labels.to_csv((file2 + '_grouped')) tmp_file_path = helpers.join_csvs((file1 + '_endings'), 'rev_id', (file2 + '_grouped'), 'rev_id') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'wulczyn2017en_aggressive.csv')) @classmethod def unify_row(cls, row): row['text'] = row['comment'] labels = [] if row['aggression']: labels.append('aggressive') else: labels.append('none') row['labels'] = labels row = row.drop(['rev_id', 'comment', 'year', 'logged_in', 'ns', 'sample', 'split', 'worker_id', 'aggression', 'aggression_score']) return row
class Wulczyn2017attack(dataset.Dataset): name = 'wulczyn2017attack' url = 'https://ndownloader.figshare.com/articles/4054689/versions/6' hash = '9e48068af1fbbe893af4df1b629ceebf924dc723a290c7bc473d2a8a8aac3529' files = [{'name': 'wulczyn2017en_attack.csv', 'language': 'en', 'type': 'training', 'platform': 'wikipedia'}] license = ' ' @classmethod def valid_hash(cls, file): 'do not check hash since it differs for each download' return @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(tmp_file_path, 'attack_annotated_comments.tsv'), sep='\t') file2 = helpers.clean_csv(os.path.join(tmp_file_path, 'attack_annotations.tsv'), sep='\t') df1 = pd.read_csv(file1) df1['comment'] = df1['comment'].apply((lambda x: x.replace('NEWLINE_TOKEN', ' '))) df1['comment'] = df1['comment'].apply((lambda x: x.replace('TAB_TOKEN', ' '))) df1.to_csv((file1 + '_endings'), index=False) df2 = pd.read_csv(file2) labels = (df2.groupby(['rev_id']).mean() > 0.5) labels.to_csv((file2 + '_grouped')) tmp_file_path = helpers.join_csvs((file1 + '_endings'), 'rev_id', (file2 + '_grouped'), 'rev_id') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'wulczyn2017en_attack.csv')) @classmethod def unify_row(cls, row): row['text'] = row['comment'] labels = [] if row['attack']: labels.append('attack') else: labels.append('none') row['labels'] = labels row = row.drop(['rev_id', 'comment', 'year', 'logged_in', 'ns', 'sample', 'split', 'worker_id', 'quoting_attack', 'recipient_attack', 'third_party_attack', 'other_attack', 'attack']) return row
class Wulczyn2017toxic(dataset.Dataset): name = 'wulczyn2017toxic' url = 'https://ndownloader.figshare.com/articles/4563973/versions/2' hash = '9e48068af1fbbe893af4df1b629ceebf924dc723a290c7bc473d2a8a8aac3529' files = [{'name': 'wulczyn2017en_toxic.csv', 'language': 'en', 'type': 'training', 'platform': 'wikipedia'}] license = ' ' @classmethod def valid_hash(cls, file): 'do not check hash since it differs for each download' return @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.unzip_file(tmp_file_path) file1 = helpers.clean_csv(os.path.join(tmp_file_path, 'toxicity_annotated_comments.tsv'), sep='\t') file2 = helpers.clean_csv(os.path.join(tmp_file_path, 'toxicity_annotations.tsv'), sep='\t') df1 = pd.read_csv(file1) df1['comment'] = df1['comment'].apply((lambda x: x.replace('NEWLINE_TOKEN', ' '))) df1['comment'] = df1['comment'].apply((lambda x: x.replace('TAB_TOKEN', ' '))) df1.to_csv((file1 + '_endings'), index=False) df2 = pd.read_csv(file2) labels = (df2.groupby(['rev_id']).mean() > 0.5) labels.to_csv((file2 + '_grouped')) tmp_file_path = helpers.join_csvs((file1 + '_endings'), 'rev_id', (file2 + '_grouped'), 'rev_id') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'wulczyn2017en_toxic.csv')) @classmethod def unify_row(cls, row): row['text'] = row['comment'] labels = [] if row['toxicity']: labels.append('toxic') else: labels.append('none') row['labels'] = labels row = row.drop(['rev_id', 'comment', 'year', 'logged_in', 'ns', 'sample', 'split', 'worker_id', 'toxicity', 'toxicity_score']) return row
class Zampieri2019(dataset.Dataset): name = 'zampieri2019' url = 'https://github.com/idontflow/OLID/raw/master/olid-training-v1.0.tsv' hash = '907e186e75876f1a77aeff72c97c988bdcd533493926567f7206da6f82f45ae9' files = [{'name': 'zampieri2019en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] license = 'UNKNOWN' @classmethod def process(cls, tmp_file_path, dataset_folder, api_config): tmp_file_path = helpers.clean_csv(tmp_file_path, sep='\t') helpers.copy_file(tmp_file_path, os.path.join(dataset_folder, 'zampieri2019en.csv')) @classmethod def unify_row(cls, row): row['text'] = row['tweet'] row['labels'] = [row['subtask_a']] row = row.drop(['id', 'tweet', 'subtask_a', 'subtask_b', 'subtask_c']) return row
def generate_statistics(dataset_directory_path): generate_statistics_file(dataset_directory_path)
def get_all_datasets(*, config_path=None, reset=False, skip_combine=False, skip_download=False, api_config_path=None): config = __get_config(config_path) api_config = __get_api_config(api_config_path) if reset: clear_all(config) return if (not skip_download): max_suffix_length = download_datasets(config) max_suffix_length = process_datasets(config, api_config, max_suffix_length) else: max_suffix_length = 0 max_suffix_length = unify_datasets(config, max_suffix_length) if (not skip_combine): combine_datasets(config)
def get_dataset(name, *, config_path=None, skip_download=False, api_config_path=None): config = __get_config(config_path) api_config = __get_api_config(api_config_path) dataset = get_dataset_by_name(name) if (not dataset): raise RuntimeError(f'Dataset: {name} not found') if (not skip_download): file = dataset.download(os.path.join(config['raw_directory'], dataset.name)) dataset.valid_hash(file) __process_dataset(config, dataset, api_config) __unify_dataset(config, dataset)
def combine_datasets(config, output_file_name='combined.tsv'): filedir = config['file_directory'] output_file = os.path.join(filedir, output_file_name) combined_df = pd.DataFrame() for dataset in __filter_datasets_from_config(config): for ds_file in dataset.files: try: df = pd.read_csv(os.path.join(filedir, dataset.name, ds_file['name']), sep='\t') df.insert(loc=0, column='file_name', value=([ds_file['name']] * df.count().max())) df.insert(loc=0, column='file_language', value=([ds_file['language']] * df.count().max())) df.insert(loc=0, column='file_platform', value=([ds_file['platform']] * df.count().max())) df.drop(columns=['id'], inplace=True) combined_df = combined_df.append(df) except: print('Could not add {0} to the combined dataset. Continuing with next file.'.format(ds_file['name'])) combined_df.to_csv(output_file, index_label='id', quoting=csv.QUOTE_NONNUMERIC, sep='\t')
def unify_datasets(config, max_suffix_length=0): _clear_directory(config['file_directory']) possible_datasets = __filter_datasets_from_config(config) for (idx, dataset) in enumerate(possible_datasets): max_suffix_length = _print_progress_bar((idx + (len(possible_datasets) * 2)), (len(possible_datasets) * 3), ('Unify ' + dataset.name), max_suffix_length) __unify_dataset(config, dataset) _print_progress_bar((len(possible_datasets) * 3), (len(possible_datasets) * 3), 'Done', max_suffix_length) return max_suffix_length
def __unify_dataset(config, dataset): try: for ds_file in dataset.files: helpers.copy_file(os.path.join(config['raw_directory'], (dataset.name + '_dir'), ds_file['name']), os.path.join(config['file_directory'], dataset.name, ds_file['name'])) dataset.unify(config, dataset.name) except Exception: print('\nCould not unify {0}. Continuing with next dataset.'.format(dataset.name))
def process_datasets(config, api_config, max_suffix_length=0): possible_datasets = __filter_datasets_from_config(config) for (idx, dataset) in enumerate(possible_datasets): max_suffix_length = _print_progress_bar((idx + len(possible_datasets)), (len(possible_datasets) * 3), ('Process ' + dataset.name), max_suffix_length) __process_dataset(config, dataset, api_config) return max_suffix_length
def __process_dataset(config, dataset, api_config): _clear_directory(config['temp_directory']) tmp_file_name = os.path.join(config['temp_directory'], dataset.name) helpers.copy_file(os.path.join(config['raw_directory'], dataset.name), tmp_file_name) try: dataset.process(tmp_file_name, os.path.join(config['raw_directory'], (dataset.name + '_dir')), api_config) except Exception as e: print('\nError while processing {0}. Continuing with next one.'.format(dataset.name)) raise e
def download_datasets(config, max_suffix_length=0) -> int: _clear_directory(config['raw_directory']) possible_datasets = __filter_datasets_from_config(config) for (idx, dataset) in enumerate(possible_datasets): max_suffix_length = _print_progress_bar(idx, (len(possible_datasets) * 3), ('Download ' + dataset.name), max_suffix_length) if ((dataset.name in config['data_sources']) and config['data_sources'].get(dataset.name)['download']): file = dataset.download(os.path.join(config['raw_directory'], dataset.name)) dataset.valid_hash(file) return max_suffix_length
def generate_statistics_file(filedir): sg = Statistics_generator(filedir) sg.generate('statistics.txt')
def clear_all(config): _clear_directory(config['file_directory']) _clear_directory(config['temp_directory']) _clear_directory(config['raw_directory'])
def _clear_directory(directory): if os.path.exists(directory): shutil.rmtree(directory) os.mkdir(directory)
def _print_progress_bar(iteration, total, suffix='', max_suffix_length=0): percent = '{0:.1f}'.format((100 * (iteration / float(total)))) filledLength = int(((50 * iteration) // total)) bar = (('█' * filledLength) + ('-' * (50 - filledLength))) suffix_string = (suffix + (' ' * (max_suffix_length - len(suffix)))) print(f''' Progress: [{bar}] {percent}% {suffix_string}''', end='\r') if (iteration == total): print() return len(suffix_string)
def __get_api_config(config_path): if config_path: return __get_config_from_path(config_path) return None
def __get_config(config_path): if config_path: config = __get_config_from_path(config_path) else: config = json.loads(importlib.resources.read_text(__package__, 'config.json')) return config
def __get_config_from_path(config_path): try: with open(config_path, 'r') as config_file: return json.loads(config_file.read()) except Exception: print('Failure loading config.json. Run the following command to reset config.json:\n\n\tmain.py --genconfig')
def __filter_datasets_from_config(config): all_possible_datasets: List[dataset.Dataset] = datasets.get_datasets() return list(filter((lambda dataset: (dataset.name in config['data_sources'])), all_possible_datasets))
def find_tables(dump_filename): table_list = [] with open(dump_filename, 'r') as f: for line in f: line = line.strip() if line.lower().startswith('create table'): table_name = re.findall('create table `([\\w_]+)`', line.lower()) table_list.extend(table_name) return table_list
def read_dump(dump_filename, target_table): column_names = [] rows = [] read_mode = 0 with open(dump_filename, 'r') as f: for line in f: line = line.strip() if (line.lower().startswith('insert') and (target_table in line)): read_mode = 2 if (line.lower().startswith('create table') and (target_table in line)): read_mode = 1 continue if (read_mode == 0): continue elif (read_mode == 1): if line.lower().startswith('primary'): read_mode = 0 continue colheader = re.findall('`([\\w_]+)`', line) for col in colheader: column_names.append(col.strip()) elif (read_mode == 2): if line.endswith(';'): end_index = (- 1) else: end_index = 0 data = make_tuple(line[(line.find('VALUES') + 7):end_index]) try: for item in data: row = {} for (key, value) in zip(column_names, item): row[key] = value rows.append(row) except IndexError: pass if line.endswith(';'): df = pd.DataFrame(rows, columns=column_names) break df.to_csv((((dump_filename[:(- 4)] + '_') + target_table) + '_df.csv'), index=False) return
class Statistics_generator(): def __init__(self, filedir): self.filedir = filedir def generate(self, output_file=None): ds_data = self._collect_data() overall_data = self._calculate_overall_data(ds_data) if output_file: self._generate_output(output_file, ds_data, overall_data) return (ds_data, overall_data) def _generate_output(self, output_file, dataset_data, overall_data): str = self._generate_headline('Overall Statistics') str += self._generate_table(overall_data) str += self._generate_headline('Dataset Statistics') for i in dataset_data: str += (i + '\n') str += self._generate_table(dataset_data[i], 4) str += '\n' with open(output_file, 'w') as f: f.write(str) def _generate_headline(self, text): str = (('#' * (len(text) + 4)) + '\n') str += (('# ' + text) + ' #') str += (('\n' + ('#' * (len(text) + 4))) + '\n\n') return str def _generate_table(self, data, indentation=0): left_width = 0 string = '' for i in data: left_width = max(len(str(i)), left_width) for i in data: string += (' ' * indentation) string += ((str(i) + ':') + (' ' * ((left_width - len(i)) + 2))) if (type(data[i]) == dict): string += '\n' string += self._generate_table(data[i], (indentation + 4)) else: string += (str(data[i]) + '\n') return string def _collect_data(self): files = {} for (idx, dataset) in enumerate(datasets.get_datasets()): for file in dataset.files: file_path = os.path.join(self.filedir, dataset.name, file['name']) if (not os.path.isfile(file_path)): continue files[file['name']] = self._generate_file_statistics(file_path) return files def _generate_file_statistics(self, file): df = pd.read_csv(file, sep='\t') statistics = {} statistics['rows'] = len(df) statistics['file size'] = os.path.getsize(file) statistics['labels'] = self._get_label_count(df, 'labels') return statistics def _get_label_count(self, df, column): counts = {} raw_counts = dict(df[column].value_counts()) for i in raw_counts: for j in ast.literal_eval(i): if (j not in counts): counts[j] = 0 counts[j] += int(raw_counts[i]) return counts def _calculate_overall_data(self, dataset_data): rows = 0 file_size = 0 labels = {} for i in dataset_data: rows += dataset_data[i]['rows'] file_size += dataset_data[i]['file size'] for (label, count) in dataset_data[i]['labels'].items(): if (not (label in labels)): labels[label] = 0 labels[label] += count return {'rows': rows, 'file size': file_size, 'labels': labels}
def read_file(f): with open(f, 'r') as f: return json.load(f)
def get_results(results, dataset, name): if (dataset not in datasets_mt_few_shot): res = {k: round((v['acc'] * 100), 1) for (k, v) in results.items()} else: res = {k.replace(name, 'few-shot'): round((v['acc'] * 100), 1) for (k, v) in results.items()} res = dict(sorted(res.items())) task_names = list(res.keys()) results_dataset = defaultdict(dict) dataset_names = set([task[:(- 3)] for task in task_names]) for dataset_name in dataset_names: results_dataset[dataset_name] = defaultdict(dict) for task in task_names: dataset_name = task[:(- 3)] lang = task[(- 2):] results_dataset[dataset_name][lang] = res[task] for (dataset_name, resu) in results_dataset.items(): values = [v for (k, v) in resu.items() if (k != 'en')] results_dataset[dataset_name]['avg'] = round((sum(values) / len(values)), 1) for (resource, langs) in languages.items(): values = [v for (k, v) in resu.items() if (k in langs)] if (len(values) > 0): results_dataset[dataset_name][resource] = round((sum(values) / len(values)), 1) return results_dataset
def get_all_results(models, datasets): all_results = defaultdict(dict) for (model, names) in models.items(): for dataset in datasets: for name in names: shots = (8 if ('mgsm' in dataset) else 0) if (not os.path.exists(f'../results/{model}/{name}/{name}_{dataset}_{shots}-shot.json')): print(f'../results/{model}/{name}/{name}_{dataset}_{shots}-shot.json') continue output = read_file(f'../results/{model}/{name}/{name}_{dataset}_{shots}-shot.json') results = get_results(output['results'], dataset, name) for dataset_name in results: if (dataset_name not in all_results): all_results[dataset_name] = defaultdict(dict) all_results[dataset_name][name].update(results[dataset_name]) return all_results
def get_dataframes(all_results, datasets): results_avg = pd.DataFrame() for dataset in datasets: results = pd.DataFrame(all_results[dataset]).T results['dataset'] = dataset results['model'] = [models_reverse[model] for model in results.index] results['size'] = model_sizes_all[:len(results)] results_avg['model'] = results['model'] results_avg['size'] = results['size'] results_avg[dataset] = results['avg'] (yield results) size = results_avg['size'] results_avg = results_avg.drop(columns=['size']) results_avg['avg'] = results_avg.mean(axis=1).round(1) results_avg['dataset'] = 'avg' results_avg['size'] = size (yield results_avg)
def plot_size_df_models(df, langs=False): df.set_index('size', inplace=True) df.groupby('model')['avg'].plot(x='size', y='acc', title=list(df['dataset'])[0], legend=True, marker='o') plt.xscale('log') plt.xticks(model_sizes_all, model_sizes_all, rotation='vertical') plt.show() if langs: for lang in df.columns: if (lang in ['dataset', 'model', 'avg', 'size']): continue df.groupby('model')[lang].plot(x='size', title=f"{list(df['dataset'])[0]}_{lang}", legend=True, marker='o') plt.xscale('log') plt.xticks(model_sizes_all, model_sizes_all, rotation='vertical') plt.show()
def get_dataframes_model(all_results, datasets, model_name, divide=False): dataset_keys = list(all_results.keys()) if divide: df_avg_self = pd.DataFrame() df_avg_mt = pd.DataFrame() else: df_avg = {} for average in (['avg'] + list(languages.keys())): df_avg[average] = pd.DataFrame() for dataset in datasets: dfs = [] for dataset_key in dataset_keys: if dataset_key.startswith(dataset): if (model_name == 'open_llama_v2'): if (not any([(model.lower() in models['open_llama_v2']) for model in all_results[dataset_key]])): continue elif (not any([(model_name in model.lower()) for model in all_results[dataset_key]])): continue if (('600M' in dataset_key) or ('1.3B' in dataset_key)): continue results = pd.DataFrame(all_results[dataset_key]).T results['dataset'] = dataset_key results['model'] = [models_reverse[model] for model in results.index] results = results[(results['model'] == model_name)] results.drop(columns=['model'], inplace=True) results['model'] = model_name results['size'] = model_sizes[model_name][:len(results)] dfs.append(results) df_concat = pd.concat(dfs) df_concat = df_concat.sort_values(['size', 'dataset']) df_concat = df_concat.reindex(columns=(['model', 'size', 'dataset'] + [col for col in df_concat.columns if (col not in ['model', 'size', 'dataset'])])) df_concat['dataset'] = df_concat['dataset'].str.replace(dataset, 'Direct') df_concat['dataset'] = df_concat['dataset'].str.replace('Direct-mt_few-shot', 'Self-translate') df_concat['dataset'] = df_concat['dataset'].str.replace('Direct-mt_nllb-200-3.3B', 'MT (NLLB)') if divide: df_concat_self = df_concat[df_concat['dataset'].isin(['Direct', 'Self-MT'])] df_concat_mt = df_concat[df_concat['dataset'].isin(['Self-MT', 'MT'])] df_avg_self['model'] = df_concat_self['model'] df_avg_self['size'] = df_concat_self['size'] df_avg_self['dataset'] = df_concat_self['dataset'] df_avg_self[dataset] = df_concat_self['avg'] df_avg_mt['model'] = df_concat_mt['model'] df_avg_mt['size'] = df_concat_mt['size'] df_avg_mt['dataset'] = df_concat_mt['dataset'] df_avg_mt[dataset] = df_concat_mt['avg'] (yield df_concat_self) (yield df_concat_mt) else: for average in (['avg'] + list(languages.keys())): df_avg[average]['model'] = df_concat['model'] df_avg[average]['size'] = df_concat['size'] df_avg[average]['dataset'] = df_concat['dataset'] df_avg[average][dataset] = df_concat[average] (yield df_concat) if divide: size = df_avg_self['size'] df_avg_self = df_avg_self.drop(columns=['size']) size = df_avg_mt['size'] df_avg_mt = df_avg_mt.drop(columns=['size']) df_avg_self['avg'] = df_avg_self.mean(axis=1).round(1) df_avg_mt['avg'] = df_avg_mt.mean(axis=1).round(1) df_avg_self['size'] = size df_avg_mt['size'] = size (yield df_avg_self) (yield df_avg_mt) else: for average in (['avg'] + list(languages.keys())): size = df_avg[average]['size'] df_avg[average] = df_avg[average].drop(columns=['size']) df_avg[average][average] = df_avg[average].mean(axis=1).round(1) df_avg[average]['size'] = size (yield df_avg[average])
def plot_size_df_datasets(df, model_name, title, langs=False): titles = {'low': 'Low-resource languages', 'high': 'High-resource languages', 'avg': 'Average'} df.set_index('size', inplace=True) for average in (['avg'] + list(languages.keys())): if (average not in df.columns): continue df.groupby('dataset')[average].plot(x='size', y='acc', title=f'{title} {titles[average]}', ylabel='Average accuracy', xlabel='Model size (B)', legend=True, marker='o') plt.xscale('log') plt.xticks(model_sizes[model_name], model_sizes[model_name], rotation='vertical') if (title == ''): plt.ylim(46, 62) plt.savefig(f'plots/{model_name}_{average}.pdf', bbox_inches='tight') plt.show() if langs: for lang in df.columns: if (lang in ['dataset', 'avg', 'size']): continue df.groupby('dataset')[lang].plot(x='size', y='acc', title=f'{title}_{lang}', ylabel='Accuracy', xlabel='Model size (B)', legend=True, marker='o') plt.xscale('log') plt.xticks(model_sizes[model_name], model_sizes[model_name], rotation='vertical') plt.show()
def get_metrics(): metrics_dict = defaultdict(dict) for dataset_name in _DATASETS: for model_name in _MODELS: if ((model_name == 'bloom-560m') and (dataset_name == 'xnli')): with open(f'metrics/{dataset_name}/bloom-1b1.json') as f: metrics_dict[dataset_name][model_name] = json.load(f) else: with open(f'metrics/{dataset_name}/{model_name}.json') as f: metrics_dict[dataset_name][model_name] = json.load(f) for language in metrics_dict[dataset_name][model_name]: avg = defaultdict(float) for field in metrics_dict[dataset_name][model_name][language]: for (metric, value) in metrics_dict[dataset_name][model_name][language][field].items(): avg[metric] += value for metric in avg: avg[metric] /= len(metrics_dict[dataset_name][model_name][language]) avg[metric] = round(avg[metric], 2) metrics_dict[dataset_name][model_name][language]['avg'] = dict(avg) return dict(metrics_dict)
def add_avg(metrics_dict): metrics_dict_split = defaultdict(dict) for metric in ['sacrebleu', 'chrf++', 'comet']: metrics_dict_split[metric] = deepcopy(metrics_dict) for dataset_name in metrics_dict: for model_name in metrics_dict[dataset_name]: '\n if model_name == "bloom-560m" and dataset_name == "xnli":\n continue\n ' for (language, language_dict) in metrics_dict[dataset_name][model_name].items(): avg = metrics_dict[dataset_name][model_name][language]['avg'] metrics_dict_split[metric][dataset_name][model_name][language] = avg.get(metric, 0) metrics_dict_split[metric][dataset_name][model_name]['avg'] = round((sum(metrics_dict_split[metric][dataset_name][model_name].values()) / len(metrics_dict_split[metric][dataset_name][model_name])), 2) items = metrics_dict_split[metric][dataset_name][model_name] values = items.values() metrics_dict_split[metric][dataset_name][model_name]['avg'] = round((sum(values) / len(values)), 1) for (resource, langs) in languages.items(): values = [v for (k, v) in items.items() if (k in langs)] if (len(values) > 0): metrics_dict_split[metric][dataset_name][model_name][resource] = round((sum(values) / len(values)), 1) return dict(metrics_dict_split)
def plot_size_df_datasets(df, model_name, title, langs=False): df.set_index('size', inplace=True) df_model = df[(df['model'] == model_name)] for average in (['avg'] + list(languages.keys())): if (average not in df.columns): continue df_model[average].plot(x='size', y='acc', title=(f'{title} {average}' if title else ''), ylabel='Average COMET', xlabel='Model size (B)', legend=True, marker='o', label='Self-translate', color='C2') plt.axhline(y=df.loc[3.3][average], color='C1', linestyle='--', label='MT (NLLB)') plt.legend() plt.xscale('log') plt.ylim(55, 90) plt.xticks(model_sizes[model_name], model_sizes[model_name], rotation='vertical') if (title == ''): plt.savefig(f'plots/{average}.pdf', bbox_inches='tight') plt.show() if langs: for lang in df.columns: if (lang in ['dataset', 'avg', 'size']): continue df[lang].plot(x='size', y='acc', title=f'{title}_{lang}', ylabel='BLEU', xlabel='Model size (B)', legend=True, marker='o') plt.xscale('log') plt.xticks(model_sizes[model_name], model_sizes[model_name], rotation='vertical') plt.show()
def get_dataframes_model(metrics_dict_split, model_name): for metric in ['comet']: df_avg = {} for average in (['avg'] + list(languages.keys())): df_avg[average] = pd.DataFrame({'model': _MODELS}, index=_MODELS) for dataset_name in metrics_dict_split[metric]: df = pd.DataFrame(metrics_dict_split[metric][dataset_name]).T for average in (['avg'] + list(languages.keys())): df_avg[average][dataset_name] = df[average] df['model'] = model_names_all df['size'] = model_sizes_all df = df.reindex(columns=(['model', 'size'] + [col for col in df.columns if (col not in ['model', 'size'])])) display(df) print(df.to_latex(index=False)) plot_size_df_datasets(df, model_name, f'{dataset_name} {metric}') for average in (['avg'] + list(languages.keys())): df_avg[average][average] = df_avg[average].mean(axis=1).round(1) df_avg[average]['model'] = model_names_all df_avg[average]['size'] = model_sizes_all df_avg[average] = df_avg[average].reindex(columns=(['model', 'size'] + [col for col in df_avg[average].columns if (col not in ['model', 'size'])])) display(df_avg[average]) print(df_avg[average].to_latex(index=False)) plot_size_df_datasets(df_avg[average], model_name, title='')
def get_dataset(dataset_args: Dict[(str, str)]) -> DatasetDict: '\n Loads the dataset using the dataset_args.\n\n Args:\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n\n Returns:\n - dataset (DatasetDict): A dictionary containing the dataset.\n ' dataset = DatasetDict() if (dataset_args['dataset'] == 'xcopa'): dataset['en'] = load_dataset('super_glue', 'copa', split=dataset_args['dataset_split']) else: dataset['en'] = load_dataset(dataset_args['dataset'], 'en', split=dataset_args['dataset_split']) for config in dataset_args['dataset_configs']: dataset[config] = load_dataset(dataset_args['dataset'], config, split=dataset_args['dataset_split']) return dataset
def get_dataset_mt(dataset_args: Dict[(str, str)], model: str) -> DatasetDict: '\n Loads the machine translation dataset using the dataset_args and model.\n\n Args:\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n - model (str): The name of the model.\n\n Returns:\n - dataset (DatasetDict): A dictionary containing the machine translation dataset.\n ' dataset = DatasetDict() for config in dataset_args['dataset_configs']: dataset[config] = load_dataset(dataset_args['dataset_mt'], model, split=config) return dataset
def get_texts(dataset: DatasetDict, dataset_args: Dict[(str, str)]) -> DefaultDict[(str, Dict[(str, List[str])])]: '\n Extracts the texts from the dataset.\n\n Args:\n - dataset (DatasetDict): A dictionary containing the dataset.\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n\n Returns:\n - texts (defaultdict): A dictionary containing the texts for each configuration and field.\n ' texts = defaultdict(dict) for config in dataset: for field in dataset_args['dataset_fields']: texts[config][field] = dataset[config][field] return texts
def load_comet(model_name: str='Unbabel/wmt22-comet-da'): '\n Loads the COMET model from a checkpoint.\n\n Args:\n - model_name (str): The name of the COMET model.\n\n Returns:\n - model: The loaded COMET model.\n ' model_path = download_model(model_name) model = load_from_checkpoint(model_path) return model
@find_executable_batch_size(starting_batch_size=2048) def compute_comet(batch_size: int, model: load_from_checkpoint, predictions: List[str], references: List[str], sources: List[str], gpus: Optional[int]=None, progress_bar: bool=False) -> Dict[(str, float)]: '\n Computes the COMET score for a batch of translations.\n\n Args:\n - batch_size (int): The batch size for the COMET model.\n - model (load_from_checkpoint): The loaded COMET model.\n - predictions (List[str]): A list of translated sentences.\n - references (List[str]): A list of reference sentences.\n - sources (List[str]): A list of source sentences.\n - gpus (int): The number of GPUs to use for computation.\n - progress_bar (bool): Whether to display a progress bar during computation.\n\n Returns:\n - model_output (Dict[str, float]): A dictionary containing the COMET score for each sentence.\n ' if (gpus is None): gpus = (1 if torch.cuda.is_available() else 0) data = {'src': sources, 'mt': predictions, 'ref': references} data = [dict(zip(data, t)) for t in zip(*data.values())] model_output = model.predict(data, batch_size=batch_size, gpus=gpus, progress_bar=progress_bar) return model_output
def evaluate_translations(predictions: List[str], references: List[str], sources: List[str]) -> Dict[(str, float)]: '\n Evaluates the translations using sacrebleu, chrf and comet metrics.\n\n Args:\n - predictions (List[str]): A list of predicted translations.\n - references (List[str]): A list of reference translations.\n - sources (List[str]): A list of source sentences.\n\n Returns:\n - result_dictionary (Dict[str, float]): A dictionary containing the evaluation results for each metric.\n ' print('Loading sacrebleu...') sacrebleu = evaluate.load('sacrebleu') print('Loading chrf...') chrf = evaluate.load('chrf') print('Loading comet...') model = load_comet('Unbabel/wmt22-comet-da') result_dictionary = {} print(f'Computing sacrebleu') sacrebleu_results = sacrebleu.compute(predictions=predictions, references=references) result_dictionary['sacrebleu'] = round(sacrebleu_results['score'], 2) print(f'Computing chrf score') chrf_results = chrf.compute(predictions=predictions, references=references, word_order=2) result_dictionary['chrf++'] = round(chrf_results['score'], 2) print('Computing comet score') comet_results = compute_comet(model=model, predictions=predictions, references=references, sources=sources, progress_bar=True) comet_results['mean_score'] = (sum(comet_results['scores']) / len(comet_results['scores'])) result_dictionary['comet'] = round((comet_results['mean_score'] * 100), 2) print(result_dictionary) return result_dictionary
def evaluate_texts(predictions: DefaultDict[(str, Dict[(str, List[str])])], references: DefaultDict[(str, Dict[(str, List[str])])], dataset_args: Dict[(str, str)], model_name: str) -> None: '\n Evaluates the translations for each configuration and field.\n\n Args:\n - predictions (defaultdict): A dictionary containing the predicted translations for each configuration and field.\n - references (defaultdict): A dictionary containing the reference translations for each configuration and field.\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n - model_name (str): The name of the model.\n ' evaluations = {} for config in predictions: evaluations[config] = {} print(f'Evaluating config {config}') for field in dataset_args['dataset_fields']: print(f'Evaluating field {field}') evaluations[config][field] = evaluate_translations(predictions=predictions[config][field], references=references['en'][field], sources=references[config][field]) save_file(evaluations, dataset_args, model_name)
def save_file(evaluations: Dict[(str, Dict[(str, Dict[(str, float)])])], dataset_args: Dict[(str, str)], model_name: str) -> None: '\n Saves the evaluation results to a file.\n\n Args:\n - evaluations (dict): A dictionary containing the evaluation results for each configuration and field.\n - dataset_args (dict): A dictionary containing the dataset name, split, and configurations.\n - model_name (str): The name of the model.\n ' dirname = f"metrics/{dataset_args['dataset'].split('/')[(- 1)]}" if (not os.path.exists(dirname)): os.makedirs(dirname) filename = f'{dirname}/{model_name}.json' with open(filename, 'w', encoding='utf-8') as file: json.dump(evaluations, file, indent=2)
def main() -> None: '\n Main function that evaluates the translations for each dataset and model.\n ' for dataset_name in _DATASETS: dataset_args = dataset_configs[dataset_name] print('Evaluating dataset', dataset_name) dataset = get_dataset(dataset_args) references = get_texts(dataset, dataset_args) for model_name in _MODELS: if ((model_name == 'bloom-560m') and (dataset_name == 'xnli')): continue print('Evaluating model', model_name) dataset_mt = get_dataset_mt(dataset_args, model_name) predictions = get_texts(dataset_mt, dataset_args) evaluate_texts(predictions, references, dataset_args, model_name)
def count_lines(input_list: List[str]) -> int: '\n Counts the number of lines in a list of strings.\n\n Args:\n input_list (List[str]): List of strings.\n\n Returns:\n int: Number of lines in the list.\n ' return len(input_list)
class DatasetReader(IterableDataset): def __init__(self, sentences: List[str], tokenizer, max_length: int=128): '\n Initializes the DatasetReader class.\n\n Args:\n sentences (List[str]): List of sentences.\n tokenizer: Tokenizer object.\n max_length (int, optional): Maximum length of the tokenized sentence. Defaults to 128.\n ' self.sentences = sentences self.tokenizer = tokenizer self.max_length = max_length self.current_line = 0 self.total_lines = count_lines(sentences) print(f'{self.total_lines} lines in list') def preprocess(self, text: str) -> dict: '\n Preprocesses a sentence by tokenizing it.\n\n Args:\n text (str): Input sentence.\n\n Returns:\n dict: Tokenized sentence.\n ' self.current_line += 1 text = text.rstrip().strip() if (len(text) == 0): print(f'Warning: empty sentence at line {self.current_line}') return self.tokenizer(text, padding=False, truncation=True, max_length=self.max_length, return_tensors=None) def __iter__(self): mapped_itr = map(self.preprocess, self.sentences) return mapped_itr def __len__(self) -> int: return self.total_lines
class ParallelTextReader(IterableDataset): def __init__(self, predictions: List[str], references: List[str]): '\n Initializes the ParallelTextReader class.\n\n Args:\n predictions (List[str]): List of predicted sentences.\n references (List[str]): List of reference sentences.\n ' self.predictions = predictions self.references = references predictions_lines = count_lines(predictions) references_lines = count_lines(references) assert (predictions_lines == references_lines), f'Lines in predictions and references do not match {predictions_lines} vs {references_lines}' self.num_sentences = references_lines self.current_line = 0 def preprocess(self, pred: str, gold: str) -> Tuple[(str, List[str])]: '\n Preprocesses a predicted and a reference sentence by stripping them.\n\n Args:\n pred (str): Predicted sentence.\n gold (str): Reference sentence.\n\n Returns:\n Tuple[str, List[str]]: Tuple containing the predicted sentence and a list with the reference sentence.\n ' self.current_line += 1 pred = pred.rstrip().strip() gold = gold.rstrip().strip() if (len(pred) == 0): print(f'Warning: Pred empty sentence at line {self.current_line}') if (len(gold) == 0): print(f'Warning: Gold empty sentence at line {self.current_line}') return (pred, [gold]) def __iter__(self): mapped_itr = map(self.preprocess, self.predictions, self.references) return mapped_itr def __len__(self) -> int: return self.num_sentences
def encode_string(text): return text.replace('\r', '\\r').replace('\n', '\\n').replace('\t', '\\t')
def get_dataloader(accelerator: Accelerator, translate_data, tokenizer: PreTrainedTokenizerBase, batch_size: int, max_length: int) -> DataLoader: dataset = DatasetReader(translate_data, tokenizer, max_length) if (accelerator.distributed_type == DistributedType.TPU): data_collator = DataCollatorForSeq2Seq(tokenizer, padding='max_length', max_length=max_length, label_pad_token_id=tokenizer.pad_token_id, return_tensors='pt') else: data_collator = DataCollatorForSeq2Seq(tokenizer, padding=True, label_pad_token_id=tokenizer.pad_token_id, pad_to_multiple_of=8, return_tensors='pt') return DataLoader(dataset, batch_size=batch_size, collate_fn=data_collator, num_workers=0)
def main(source_lang: str, target_lang: str, starting_batch_size: int, model_name: str='facebook/m2m100_1.2B', cache_dir: str=None, precision: str='32', max_length: int=128, num_beams: int=4, num_return_sequences: int=1, do_sample: bool=False, temperature: float=1.0, top_k: int=50, top_p: float=1.0, keep_special_tokens: bool=False, sentences_path: str=None, output_path: str=None, sentences_list: str=None, return_output: bool=False): if (not return_output): os.makedirs(os.path.abspath(os.path.dirname(output_path)), exist_ok=True) accelerator = Accelerator(mixed_precision=(precision if (precision != '32') else 'no'), split_batches=False, dispatch_batches=False) print(f'Loading tokenizer {model_name}...') tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path=model_name, cache_dir=cache_dir) print(f'Loading model {model_name}...') model = AutoModelForSeq2SeqLM.from_pretrained(pretrained_model_name_or_path=model_name, cache_dir=cache_dir) model.eval() print(f'''Preparing data... ''') if (precision == '32'): model = model.float() elif (precision == 'fp16'): model = model.half() elif (precision == 'bf16'): model = model.bfloat16() else: raise ValueError('Precision not supported. Supported values: 32, fp16, bf16') try: _ = tokenizer.lang_code_to_id[source_lang] except KeyError: raise KeyError(f'Language {source_lang} not found in tokenizer. Available languages: {tokenizer.lang_code_to_id.keys()}') tokenizer.src_lang = source_lang try: lang_code_to_idx = tokenizer.lang_code_to_id[target_lang] except KeyError: raise KeyError(f'Language {target_lang} not found in tokenizer. Available languages: {tokenizer.lang_code_to_id.keys()}') gen_kwargs = {'max_length': max_length, 'num_beams': num_beams, 'num_return_sequences': num_return_sequences, 'do_sample': do_sample, 'temperature': temperature, 'top_k': top_k, 'top_p': top_p} total_lines: int = (count_lines(sentences_path) if (sentences_list == None) else len(sentences_list)) if accelerator.is_main_process: print(f'''** Translation ** Input file: {sentences_path} Output file: {output_path} Source language: {source_lang} Target language: {target_lang} Starting batch size: {starting_batch_size} Device: {str(accelerator.device).split(':')[0]} Num. Devices: {accelerator.num_processes} Distributed_type: {accelerator.distributed_type} Max length: {max_length} Precision: {model.dtype} Model: {model_name} ''') print('** Generation parameters **') print('\n'.join((f'{k}: {v}' for (k, v) in gen_kwargs.items()))) print('\n') def save_sentences(tgt_text: list): nonlocal return_output, output_path if return_output: save_sentences.sentences.extend(tgt_text) else: print('\n'.join(tgt_text), file=save_sentences.f) if (not return_output): save_sentences.f = open(output_path, 'w', encoding='utf-8') save_sentences.sentences = [] @find_executable_batch_size(starting_batch_size=starting_batch_size) def inference(batch_size): nonlocal model, tokenizer, sentences_path, max_length, output_path, lang_code_to_idx, gen_kwargs, precision, sentences_list, return_output print(f'Translating with batch size {batch_size}') translate_data = (sentences_path if (sentences_list == None) else sentences_list) data_loader = get_dataloader(accelerator=accelerator, translate_data=translate_data, tokenizer=tokenizer, batch_size=batch_size, max_length=max_length) (model, data_loader) = accelerator.prepare(model, data_loader) samples_seen: int = 0 with tqdm(total=total_lines, desc='Dataset translation', leave=True, ascii=True, disable=(not accelerator.is_main_process)) as pbar: with torch.no_grad(): for (step, batch) in enumerate(data_loader): batch['input_ids'] = batch['input_ids'] batch['attention_mask'] = batch['attention_mask'] generated_tokens = accelerator.unwrap_model(model).generate(**batch, forced_bos_token_id=lang_code_to_idx, **gen_kwargs) generated_tokens = accelerator.pad_across_processes(generated_tokens, dim=1, pad_index=tokenizer.pad_token_id) generated_tokens = accelerator.gather(generated_tokens).cpu().numpy() tgt_text = tokenizer.batch_decode(generated_tokens, skip_special_tokens=(not keep_special_tokens)) if accelerator.is_main_process: if (step == (math.ceil((math.ceil((total_lines / batch_size)) / accelerator.num_processes)) - 1)): tgt_text = tgt_text[:((total_lines * num_return_sequences) - samples_seen)] else: samples_seen += len(tgt_text) save_sentences([encode_string(sentence) for sentence in tgt_text]) pbar.update((len(tgt_text) // gen_kwargs['num_return_sequences'])) inference() print(f'''Translation done. ''') if return_output: return save_sentences.sentences
def get_dataset(dataset_args: Dict[(str, Any)]) -> DatasetDict: '\n Load the dataset specified in dataset_args and return a DatasetDict object.\n\n Args:\n - dataset_args: A dictionary containing the dataset name, dataset configurations, dataset split.\n\n Returns:\n - A DatasetDict object containing the loaded dataset.\n ' dataset = DatasetDict() for config in dataset_args['dataset_configs']: dataset[config] = load_dataset(dataset_args['dataset'], config, split=dataset_args['dataset_split']) return dataset
def get_texts(dataset: DatasetDict, dataset_args: Dict[(str, Any)]) -> Dict[(str, Dict[(str, Any)])]: '\n Extract the texts from the dataset and return a dictionary containing the texts.\n\n Args:\n - dataset: A DatasetDict object containing the loaded dataset.\n - dataset_args: A dictionary containing the dataset configurations.\n\n Returns:\n - A dictionary containing the texts extracted from the dataset.\n ' texts = defaultdict(dict) for config in dataset_args['dataset_configs']: for field in dataset_args['dataset_fields']: texts[config][field] = dataset[config][field] return texts
def get_few_shot_dataset(dataset_args: Dict[(str, Any)]) -> DatasetDict: '\n Load the few-shot dataset specified in dataset_args and return a DatasetDict object.\n\n Args:\n - dataset_args: A dictionary containing the few-shot dataset configurations.\n\n Returns:\n - A DatasetDict object containing the loaded few-shot dataset.\n ' dataset = DatasetDict() dataset['en'] = load_dataset('facebook/flores', 'eng_Latn', split='dev') for config in dataset_args['dataset_configs']: dataset[config] = load_dataset('facebook/flores', dataset_args['lang_codes'][config], split='dev') return dataset
def get_few_shot_prompts(dataset: DatasetDict, dataset_args: Dict[(str, Any)], translate_args: Dict[(str, Any)], shots: int) -> Dict[(str, str)]: '\n Generate few-shot prompts for each language in dataset_args and return a dictionary containing the prompts.\n\n Args:\n - dataset: A DatasetDict object containing the few-shot dataset.\n - dataset_args: A dictionary containing the dataset configurations.\n - translate_args: A dictionary containing the translation configurations.\n - shots: An integer representing the number of few-shot prompts to generate.\n\n Returns:\n - A dictionary containing the few-shot prompts for each language.\n ' prompts = {} for config in dataset_args['dataset_configs']: prompts[config] = '' (i, shot) = (0, 0) while (shot < shots): if (len(dataset[config][i]['sentence']) < 100): prompts[config] += f"{dataset_args['lang_names'][config]}: {dataset[config][i]['sentence']}{translate_args['eos_token']}" prompts[config] += f"English: {dataset['en'][i]['sentence']}{translate_args['eos_token']}" shot += 1 i += 1 prompts[config] += f"{dataset_args['lang_names'][config]}:" return prompts
def text_with_prompt(text: str, prompt: str, translate_args: Dict[(str, Any)]) -> str: '\n Concatenate the text with the prompt and the eos_token.\n\n Args:\n - text: A string representing the text to be concatenated.\n - prompt: A string representing the prompt to be concatenated.\n - translate_args: A dictionary containing the translation configurations.\n\n Returns:\n - A string representing the concatenated text with the prompt and the eos_token.\n ' return f"{prompt} {text}{translate_args['eos_token']}English:"