-
Notifications
You must be signed in to change notification settings - Fork 14
/
nytimes_faces_ner_matched.py
261 lines (218 loc) · 9.72 KB
/
nytimes_faces_ner_matched.py
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import logging
import os
import random
import re
from typing import Dict
import numpy as np
import pymongo
import torch
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import ArrayField, MetadataField, TextField
from allennlp.data.instance import Instance
from allennlp.data.token_indexers import TokenIndexer
from allennlp.data.tokenizers import Tokenizer
from overrides import overrides
from PIL import Image
from pymongo import MongoClient
from torchvision.transforms import Compose, Normalize, ToTensor
from tqdm import tqdm
from tell.data.fields import ImageField, ListTextField
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
SPACE_NORMALIZER = re.compile(r"\s+")
def tokenize_line(line):
line = SPACE_NORMALIZER.sub(" ", line)
line = line.strip()
return line.split()
@DatasetReader.register('nytimes_faces_ner_matched')
class NYTimesFacesNERMatchedReader(DatasetReader):
"""Read from the New York Times dataset.
See the repo README for more instruction on how to download the dataset.
Parameters
----------
tokenizer : ``Tokenizer``
We use this ``Tokenizer`` for both the premise and the hypothesis.
See :class:`Tokenizer`.
token_indexers : ``Dict[str, TokenIndexer]``
We similarly use this for both the premise and the hypothesis.
See :class:`TokenIndexer`.
"""
def __init__(self,
tokenizer: Tokenizer,
token_indexers: Dict[str, TokenIndexer],
image_dir: str,
mongo_host: str = 'localhost',
mongo_port: int = 27017,
use_caption_names: bool = True,
use_objects: bool = False,
n_faces: int = None,
lazy: bool = True) -> None:
super().__init__(lazy)
self._tokenizer = tokenizer
self._token_indexers = token_indexers
self.client = MongoClient(host=mongo_host, port=mongo_port)
self.db = self.client.nytimes
self.image_dir = image_dir
self.preprocess = Compose([
ToTensor(),
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
self.use_caption_names = use_caption_names
self.use_objects = use_objects
self.n_faces = n_faces
random.seed(1234)
self.rs = np.random.RandomState(1234)
roberta = torch.hub.load('pytorch/fairseq:2f7e3f3323', 'roberta.base')
self.bpe = roberta.bpe
self.indices = roberta.task.source_dictionary.indices
@overrides
def _read(self, split: str):
# split can be either train, valid, or test
# validation and test sets contain 10K examples each
if split not in ['train', 'valid', 'test']:
raise ValueError(f'Unknown split: {split}')
logger.info('Grabbing all article IDs')
sample_cursor = self.db.articles.find({
'split': split,
}, projection=['_id']).sort('_id', pymongo.ASCENDING)
ids = np.array([article['_id'] for article in tqdm(sample_cursor)])
sample_cursor.close()
self.rs.shuffle(ids)
projection = ['_id', 'parsed_section.type', 'parsed_section.text',
'parsed_section.hash', 'parsed_section.parts_of_speech',
'parsed_section.facenet_details', 'parsed_section.named_entities',
'image_positions', 'headline',
'web_url', 'n_images_with_faces']
for article_id in ids:
article = self.db.articles.find_one(
{'_id': {'$eq': article_id}}, projection=projection)
sections = article['parsed_section']
image_positions = article['image_positions']
for pos in image_positions:
title = ''
if 'main' in article['headline']:
title = article['headline']['main'].strip()
paragraphs = []
named_entities = set()
n_words = 0
if title:
paragraphs.append(title)
named_entities.union(
self._get_named_entities(article['headline']))
n_words += len(self.to_token_ids(title))
caption = sections[pos]['text'].strip()
if not caption:
continue
if self.n_faces is not None:
n_persons = self.n_faces
elif self.use_caption_names:
n_persons = len(self._get_person_names(sections[pos]))
else:
n_persons = 4
before = []
after = []
i = pos - 1
j = pos + 1
for k, section in enumerate(sections):
if section['type'] == 'paragraph':
paragraphs.append(section['text'])
named_entities |= self._get_named_entities(section)
break
while True:
if i > k and sections[i]['type'] == 'paragraph':
text = sections[i]['text']
before.insert(0, text)
named_entities |= self._get_named_entities(sections[i])
n_words += len(self.to_token_ids(text))
i -= 1
if k < j < len(sections) and sections[j]['type'] == 'paragraph':
text = sections[j]['text']
after.append(text)
named_entities |= self._get_named_entities(sections[j])
n_words += len(self.to_token_ids(text))
j += 1
if n_words >= 510 or (i <= k and j >= len(sections)):
break
image_path = os.path.join(
self.image_dir, f"{sections[pos]['hash']}.jpg")
try:
image = Image.open(image_path)
except (FileNotFoundError, OSError):
continue
if 'facenet_details' not in sections[pos] or n_persons == 0:
face_embeds = np.array([[]])
else:
face_embeds = sections[pos]['facenet_details']['embeddings']
# Keep only the top faces (sorted by size)
face_embeds = np.array(face_embeds[:n_persons])
paragraphs = paragraphs + before + after
named_entities = sorted(named_entities)
obj_feats = None
if self.use_objects:
obj = self.db.objects.find_one(
{'_id': sections[pos]['hash']})
if obj is not None:
obj_feats = obj['object_features']
if len(obj_feats) == 0:
obj_feats = np.array([[]])
else:
obj_feats = np.array(obj_feats)
else:
obj_feats = np.array([[]])
yield self.article_to_instance(
paragraphs, named_entities, image, caption, image_path,
article['web_url'], pos, face_embeds, obj_feats)
def article_to_instance(self, paragraphs, named_entities, image, caption,
image_path, web_url, pos, face_embeds, obj_feats) -> Instance:
context = '\n'.join(paragraphs).strip()
context_tokens = self._tokenizer.tokenize(context)
caption_tokens = self._tokenizer.tokenize(caption)
name_token_list = [self._tokenizer.tokenize(n) for n in named_entities]
if name_token_list:
name_field = [TextField(tokens, self._token_indexers)
for tokens in name_token_list]
else:
stub_field = ListTextField(
[TextField(caption_tokens, self._token_indexers)])
name_field = stub_field.empty_field()
fields = {
'context': TextField(context_tokens, self._token_indexers),
'names': ListTextField(name_field),
'image': ImageField(image, self.preprocess),
'caption': TextField(caption_tokens, self._token_indexers),
'face_embeds': ArrayField(face_embeds, padding_value=np.nan),
}
if obj_feats is not None:
fields['obj_embeds'] = ArrayField(obj_feats, padding_value=np.nan)
metadata = {'context': context,
'caption': caption,
'names': named_entities,
'web_url': web_url,
'image_path': image_path,
'image_pos': pos}
fields['metadata'] = MetadataField(metadata)
return Instance(fields)
def _get_named_entities(self, section):
# These name indices have the right end point excluded
names = set()
if 'named_entities' in section:
ners = section['named_entities']
for ner in ners:
if ner['label'] in ['PERSON', 'ORG', 'GPE']:
names.add(ner['text'])
return names
def _get_person_names(self, section):
# These name indices have the right end point excluded
names = set()
if 'named_entities' in section:
ners = section['named_entities']
for ner in ners:
if ner['label'] in ['PERSON']:
names.add(ner['text'])
return names
def to_token_ids(self, sentence):
bpe_tokens = self.bpe.encode(sentence)
words = tokenize_line(bpe_tokens)
token_ids = []
for word in words:
idx = self.indices[word]
token_ids.append(idx)
return token_ids