mnli-norwegian / create_multilingual_simCSE.py
pere's picture
first push
3cdf7bc
raw
history blame
3.19 kB
import json
import jsonlines
import argparse
import pandas as pd
import pprint
from random import *
def main(args):
mainDict = {}
with jsonlines.open(args.norwegian_input_file) as reader:
for obj in reader:
#Check if the value already exists
neutral = ""
entailment = ""
contradiction = ""
prompt = ""
if mainDict.get(obj['promptID'], None):
prompt = obj['sentence1']
entailment = mainDict[obj['promptID']].get('entailment','')
contradiction = mainDict[obj['promptID']].get('contradiction','')
neutral = mainDict[obj['promptID']].get('neutral','')
if obj['gold_label'] == "neutral":
neutral = obj['sentence2']
elif obj['gold_label'] == "contradiction":
contradiction = obj['sentence2']
elif obj['gold_label'] == "entailment":
entailment = obj['sentence2']
mainDict[obj['promptID']] = {'prompt': prompt, 'entailment' : entailment, 'neutral' : neutral, 'contradiction' : contradiction}
myList = []
for promptID in mainDict:
myList.append({'sent0':mainDict[promptID]['prompt'], 'sent1':mainDict[promptID]['entailment'], 'hard_neg':mainDict[promptID]['contradiction']})
df = pd.DataFrame.from_records(myList)
#Drop empty
df.replace("", float("NaN"), inplace=True)
df.dropna(subset = ["sent0","sent1","hard_neg"], inplace=True)
#Get the english file
english = pd.read_csv(args.english_input_file)
#Get the multilingual lookup file
multi = pd.read_csv(args.multilingual_input_file, sep='\t')
multi.columns=['id','english','norwegian']
multi['english'] = multi['english'].str.strip()
multi['norwegian'] = multi['norwegian'].str.strip()
#Create dictionary
mydict = {}
for index,row in multi.iterrows():
mydict[row['norwegian']] = row['english']
merged = df.copy()
for index, row in merged.iterrows():
flip = randint(1,6)
if flip == 3 or flip == 4 or flip == 5:
merged.at[index, 'sent0'] = mydict.get(row['sent0'],row['sent0'])
if flip == 2 or flip == 4 or flip == 6:
merged.at[index, 'sent1'] = mydict.get(row['sent1'],row['sent1'])
if flip == 1 or flip == 5 or flip == 6:
merged.at[index,'hard_neg'] = mydict.get(row['hard_neg'],row['hard_neg'])
combined = pd.concat([df, english, merged])
combined = combined.sample(frac=1).reset_index(drop=True)
#Save csv
combined.to_csv(args.output_file, index=False)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--norwegian_input_file', help="Norwegian json file.", required=True)
parser.add_argument('--english_input_file', help="English csv file.", required=True)
parser.add_argument('--multilingual_input_file', help="Multilingual tsv file.", required=True)
parser.add_argument('--output_file', help="Output file.", required=True)
args = parser.parse_args()
main(args)