-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.py
More file actions
166 lines (132 loc) · 4.42 KB
/
Copy pathutils.py
File metadata and controls
166 lines (132 loc) · 4.42 KB
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
from transformers import BertTokenizer, BertForSequenceClassification
import os
def load_tokenizer(path="../transformers-local/tmp/propaganda/"):
"""Load and return an instance of Bert Tokenizer from the given path
Parameters
----------
path : str, optional
Path to the tokenization directory, by default "../transformers-local/tmp/propaganda/"
Returns
-------
BertTokenizer
Returns a tokenizer
"""
print ("loading tokenizer...")
tokenizer = BertTokenizer.from_pretrained(path)
print ("done loading tokenizer.")
return tokenizer
def load_model(path="../transformers-local/tmp/propaganda/"):
"""Load and return an instance of BertForSequenceClassification model from the given path
Parameters
----------
path : str, optional
Path to the tokenization directory, by default "../transformers-local/tmp/propaganda/"
Returns
-------
BertForSequenceClassification
Returns a bert-based sequence classification model
"""
print ("loading the model ...")
model = BertForSequenceClassification.from_pretrained(path, output_attentions=False)
print ("Done loading the model...")
return model
def tokenize(tokenizer, line, words_only=True):
"""Tokenize a line into byte pairs or words.
Parameters
----------
tokenizer : BertTokenizer
An instance of the tokenizer
line : str
Input line
words_only : bool, optional
Whether we want words or byte pairs, by default True (i.e words)
Returns
-------
list
Returns a list of words or byte-pair tokens.
"""
bp_tokens = tokenizer.tokenize(line)
if words_only:
words = club_byte_pairs(bp_tokens)
return words
return bp_tokens
def club_byte_pairs_and_scores(bp_tokens, scores):
""" Helper function to collate the broken words into byte-pairs.
The function also combines importance scores corresponding to the clubbed byte-pair tokens.
The broken words can be identified with "##". For instance, `frustrating' might be broken
down to `frustrat` and `##ing`.
Parameters
----------
bp_tokens : list
List of byte pair tokens, each byte pair token is a string.
scores : list
List of 1-d tensor values containing importance scores
Returns
-------
list, list
Returns the clubbed words and scores, respectively.
"""
in_middle = False
updated_scores = []
updated_words = []
current_idx = 0
for i, bp_token in enumerate(bp_tokens):
if bp_token[:2] == "##":
updated_words[current_idx-1] += bp_token[2:]
updated_scores[current_idx-1] += scores[i].item()
else:
updated_scores.append(scores[i].item())
updated_words.append(bp_token)
current_idx += 1
return updated_words, updated_scores
def club_byte_pairs(bp_tokens):
""" Helper function to collate the broken words into byte-pairs.
The broken words can be identified with "##". For instance, `frustrating' might be broken
down to `frustrat` and `##ing`.
Parameters
----------
bp_tokens : list
List of byte pair tokens, each byte pair token is a string.
Returns
-------
list
Returns the clubbed words.
"""
in_middle = False
updated_words = []
current_idx = 0
for i, bp_token in enumerate(bp_tokens):
if bp_token[:2] == "##":
updated_words[current_idx-1] += bp_token[2:]
else:
updated_words.append(bp_token)
current_idx += 1
return updated_words
def ensure_dir(file_path):
"""Creates a directory if it does not exist
Parameters
----------
file_path : str
Path of the file
"""
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
return
def separate_tags_from_lines(lines):
""" Separates the tags and content from the input lines.
Parameters
----------
lines : list[str]
List of input lines.
Returns
-------
list[str], list[str]
Returns the respective lists of separated tags, and input content.
"""
tags, articles = [], []
for line in lines:
tag, content = line.split("\t")[0], line.split("\t")[1]
tags.append(tag)
articles.append(content)
return tags, articles