Spaces:
Runtime error
Runtime error
File size: 5,443 Bytes
c80917c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
from tqdm import tqdm
from pprint import pprint
import pandas as pd
import argparse
import re
import json
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
p_stemmer = PorterStemmer()
# nltk.download('punkt')
# nltk.download('wordnet')
# nltk.download('stopwords')
import language_evaluation
evaluator = language_evaluation.CocoEvaluator()
def nltk_process(text):
# Tokenization
nltk_tokenList = word_tokenize(text)
# Stemming
nltk_stemedList = []
for word in nltk_tokenList:
nltk_stemedList.append(p_stemmer.stem(word))
filtered_sentence = nltk_stemedList
# Removing Punctuation
tokens = [re.sub(r'[^a-zA-Z0-9]', '', tok) for tok in filtered_sentence]
text = " ".join(tokens)
return text
def calculate_finegrained_scores(pred_id2sent, id2caption, use_coco_eval=False):
if use_coco_eval:
n_total = 0
refs = []
hyps = []
for id, gt_captions in id2caption.items():
pred_sent = pred_id2sent[id]
refs.append(gt_captions)
hyps.append(pred_sent)
n_total += 1
print('caption')
results = evaluator.run_evaluation(hyps, refs)
pprint(results)
n_total = 0
total_score = 0
for id, gt_phrases in id2background.items():
pred_sent = pred_id2sent[id]
score = 0
n_phrases = len(gt_phrases)
for gt_phrase in gt_phrases:
word_score = 0
for gt_word in gt_phrase.split():
if gt_word in pred_sent:
word_score += 1
if len(gt_phrase.split()) > 0:
score += word_score / len(gt_phrase.split())
if n_phrases > 0:
score /= n_phrases
total_score += score
n_total += 1
print('background')
# print('# retrieved words:', n_retrieved)
print(f'Acc: {total_score / n_total * 100:.2f}')
n_total = 0
total_score = 0
for id, gt_phrases in id2object.items():
pred_sent = pred_id2sent[id]
score = 0
n_phrases = len(gt_phrases)
for gt_phrase in gt_phrases:
word_score = 0
for gt_word in gt_phrase.split():
if gt_word in pred_sent:
word_score += 1
if len(gt_phrase.split()) > 0:
score += word_score / len(gt_phrase.split())
if n_phrases > 0:
score /= n_phrases
total_score += score
n_total += 1
print('object')
# print('# retrieved words:', n_retrieved)
print(f'Acc: {total_score / n_total * 100:.2f}')
n_total = 0
total_score = 0
for id, gt_phrases in id2relation.items():
pred_sent = pred_id2sent[id]
score = 0
n_phrases = len(gt_phrases)
for gt_phrase in gt_phrases:
word_score = 0
for gt_word in gt_phrase.split():
if gt_word in pred_sent:
word_score += 1
if len(gt_phrase.split()) > 0:
score += word_score / len(gt_phrase.split())
if n_phrases > 0:
score /= n_phrases
total_score += score
n_total += 1
print('relation')
# print('# retrieved words:', n_retrieved)
print(f'Acc: {total_score / n_total * 100:.2f}')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--finecapeval_path', type=str, default="data/FineCapEval.csv")
parser.add_argument('--generated_id2caption', type=str, default="FineCapEval_results/mle.json")
args = parser.parse_args()
df = pd.read_csv(args.finecapeval_path)
assert df.shape == (5000, 5)
generated_id2caption = json.load(open(args.generated_id2caption, 'r'))
print("Preprocessing GT FineCapEval data...")
id2caption = {}
id2background = {}
id2object = {}
id2relation = {}
for row in tqdm(df.itertuples(), total=len(df)):
id = row.image.split('.')[0]
caption = row.caption
background = row.background
object = row.object
relation = row.relation
if not isinstance(caption, str):
continue
if not isinstance(background, str):
continue
if not isinstance(object, str):
continue
if not isinstance(relation, str):
continue
if id not in id2caption:
id2caption[id] = []
id2background[id] = []
id2object[id] = []
id2relation[id] = []
id2caption[id].append(caption)
phrases = []
for phrase in background.lower().split('\;'):
if len(phrase) > 1:
phrase = nltk_process(phrase)
phrases.append(phrase)
id2background[id].extend(phrases)
phrases = []
for phrase in object.lower().split('\;'):
if len(phrase) > 1:
phrase = nltk_process(phrase)
phrases.append(phrase)
id2object[id].extend(phrases)
phrases = []
for phrase in relation.lower().split('\;'):
if len(phrase) > 1:
phrase = nltk_process(phrase)
phrases.append(phrase)
id2relation[id].extend(phrases)
print("Calculating scores...")
calculate_finegrained_scores(
generated_id2caption,
id2caption,
use_coco_eval=True)
|