Datasets:

Modalities:
Text
Languages:
English
Libraries:
Datasets
License:
t_rex / unify_predicate.py
asahi417's picture
Update unify_predicate.py
8e24b9b
raw
history blame
2.73 kB
import json
import pandas as pd
# load manual check sheet
df_predicate = pd.read_csv('predicate_manual_check.csv')
df_predicate = df_predicate[df_predicate['remove (noisy)'] != 'x']
df_predicate = df_predicate[df_predicate['remove (too vague)'] != 'x']
predicate_main = df_predicate[df_predicate['ok'] == 'x']['unique predicates'].tolist()
df_sub = df_predicate[df_predicate['ok'] != 'x']
df_sub_same = df_sub[['unique predicates', 'same as']].dropna()
df_sub_same = df_sub_same[[i in predicate_main for i in df_sub_same['same as']]]
df_sub_same.index = df_sub_same.pop('unique predicates')
sub_same = df_sub_same['same as'].to_dict()
df_sub_rev = df_sub[['unique predicates', 'reverse of']].dropna()
df_sub_rev = df_sub_rev[[i in predicate_main for i in df_sub_rev['reverse of']]]
df_sub_rev.index = df_sub_rev.pop('unique predicates')
sub_rev = df_sub_rev['reverse of'].to_dict()
# load data and filter based on manual predicate check sheet
with open(f"data/t_rex.filter.jsonl") as f:
data = pd.DataFrame([json.loads(i) for i in f.read().split('\n') if len(i) > 0])
data['predicate'] = [sub_same[i] if i in sub_same else i for i in data['predicate']]
data['reverse'] = [i in sub_rev for i in data['predicate']]
data['predicate'] = [sub_rev[i] if i in sub_rev else i for i in data['predicate']]
data_filter = data[[i in predicate_main for i in data['predicate']]]
data_filter_rev = data_filter[data_filter['reverse']].copy()
o = data_filter_rev.pop("object")
s = data_filter_rev.pop("subject")
data_filter_rev["subject"] = o
data_filter_rev["object"] = s
data_filter[data_filter['reverse']] = data_filter_rev[data_filter.columns]
data_filter.pop("reverse")
df_main = df_predicate[df_predicate['ok'] == 'x'][['unique predicates', 'pretty relation name', 'pretty relation name is reverse']]
df_main['reverse'] = [i == 'x' for i in df_main.pop('pretty relation name is reverse')]
df_main['predicate'] = df_main.pop('unique predicates')
data_filter_join = data_filter.merge(df_main, how='inner', on='predicate')
data_filter_join_rev = data_filter_join[data_filter_join['reverse']].copy()
o = data_filter_join_rev.pop("object")
s = data_filter_join_rev.pop("subject")
data_filter_join_rev["subject"] = o
data_filter_join_rev["object"] = s
data_filter_join[data_filter_join['reverse']] = data_filter_join_rev[data_filter_join.columns]
data_filter_join.pop("reverse")
data_filter_join.pop("predicate")
data_filter_join['predicate'] = data_filter_join.pop("pretty relation name")
print(f"{len(data_filter_join)} triples, {len(data_filter_join['predicate'].unique())} predicates")
with open(f"data/t_rex.filter_unified.jsonl", 'w') as f:
for _, i in data_filter_join.iterrows():
f.write(json.dumps(i.to_dict()) + '\n')