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... |
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':... |
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':... |
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():
' ... |
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... |
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'... |
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': 'tra... |
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'}]
... |
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 new... |
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': 'stormfro... |
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:... |
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_da... |
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 t... |
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_c... |
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_f... |
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) + '_ex... |
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 ... |
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... |
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 ... |
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_... |
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] +... |
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 res... |
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 ... |
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'... |
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... |
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 ... |
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': 't... |
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', ... |
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 an... |
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 ... |
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': 'twitte... |
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': 'hin... |
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... |
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': 'tr... |
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':... |
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', ... |
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... |
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'}]
li... |
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': '... |
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',... |
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', 'platf... |
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... |
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'... |
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', 'platfo... |
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': 'train... |
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', 'platf... |
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... |
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': 'tw... |
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 ... |
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_downl... |
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:
... |
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_data... |
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)
exc... |
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)... |
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.... |
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 '... |
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... |
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... |
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 (... |
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, ... |
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()))
tas... |
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}_{data... |
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[:... |
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:
... |
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[aver... |
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
... |
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_n... |
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 i... |
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', tit... |
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 = p... |
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 '
... |
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... |
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... |
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(mod... |
@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 transla... |
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 ref... |
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 diction... |
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_... |
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... |
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, o... |
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 sen... |
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 = DataCollatorForSeq2... |
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_toke... |
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 containi... |
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 containin... |
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... |
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 con... |
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_ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.