File size: 7,640 Bytes
82221ca
 
 
 
 
 
fa7fec5
 
a189dd1
82221ca
 
 
 
 
 
cfad95e
 
82221ca
 
946f92f
 
 
 
 
 
 
 
 
 
 
a189dd1
946f92f
 
fa7fec5
a189dd1
946f92f
 
 
 
 
 
 
 
 
 
a189dd1
 
 
 
82221ca
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a189dd1
82221ca
 
 
 
a189dd1
82221ca
a189dd1
82221ca
 
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
 
 
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
 
 
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
 
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa7fec5
 
 
82221ca
 
fa7fec5
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
fa7fec5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
 
 
 
 
 
 
 
 
 
 
946f92f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82221ca
 
 
 
 
 
 
 
 
 
a283e47
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
"""
Script file used for performing inference with an existing model.
"""

import torch
import json
import nltk
from nltk.tokenize import sent_tokenize
import huggingface_hub

from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification
)

BIN_REPO = 'dlsmallw/NLPinitiative-Binary-Classification'
ML_REPO = 'dlsmallw/NLPinitiative-Multilabel-Regression'

class InferenceHandler:
    """A class that handles performing inference using the trained binary classification and multilabel regression models."""

    def __init__(self, api_token: str):
        """Constructor for instantiating an InferenceHandler object.

        Parameters
        ----------
        api_token : str
            A Hugging Face token with read/write access privileges to allow exporting the trained models (default is None).
        """

        self.api_token = api_token
        self.bin_tokenizer, self.bin_model = self._init_model_and_tokenizer(BIN_REPO)
        self.ml_regr_tokenizer, self.ml_regr_model = self._init_model_and_tokenizer(ML_REPO)
        nltk.download('punkt_tab')

    def _get_config(self, repo_id: str) -> str:
        """Retrieves the config.json file from the specified model repository.

        Parameters
        ----------
        repo_id : str
            The repository id (i.e., <owner username>/<repository name>).
        
        """

        config = None
        if repo_id and self.api_token:
            config = huggingface_hub.hf_hub_download(repo_id, filename='config.json', token=self.api_token)
        return config

    def _init_model_and_tokenizer(self, repo_id: str):
        """Initializes a model and tokenizer for use in inference using the models path.

        Parameters
        ----------
        model_path : Path
            Directory path to the models tensor file.

        Returns
        -------
        tuple[PreTrainedTokenizer | PreTrainedTokenizerFast, PreTrainedModel]
            A tuple containing the tokenizer and model objects.
        """

        config = self._get_config(repo_id)
        with open(config) as config_file:
            config_json = json.load(config_file)
        model_name = config_json['_name_or_path']

        tokenizer = AutoTokenizer.from_pretrained(model_name)
        model = AutoModelForSequenceClassification.from_pretrained(repo_id, token=self.api_token)

        model.eval()
        return tokenizer, model

    def _encode_binary(self, text: str):
        """Preprocesses and tokenizes the input text for binary classification.

        Parameters
        ----------
        text : str
            The input text to be preprocessed and tokenized.

        Returns
        -------
        BatchEncoding
            The preprocessed and tokenized input text.
        """

        bin_tokenized_input = self.bin_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
        return bin_tokenized_input

    def _encode_multilabel(self, text: str):
        """Preprocesses and tokenizes the input text for multilabel regression.

        Parameters
        ----------
        text : str
            The input text to be preprocessed and tokenized.

        Returns
        -------
        BatchEncoding
            The preprocessed and tokenized input text.
        """

        ml_tokenized_input = self.ml_regr_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
        return ml_tokenized_input

    def _encode_input(self, text: str):
        """Preprocesses and tokenizes the input text sentiment classification (both models).

        Parameters
        ----------
        text : str
            The input text to be preprocessed and tokenized.

        Returns
        -------
        tuple[BatchEncoding, BatchEncoding]
            A tuple containing preprocessed and tokenized input text for both the binary and multilabel regression models.
        """

        bin_inputs = self._encode_binary(text)
        ml_inputs = self._encode_multilabel(text)
        return bin_inputs, ml_inputs
    
    def classify_text(self, input: str):
        """Performs inference on the input text to determine the binary classification and the multilabel regression for the categories.

        Determines whether the text is discriminatory. If it is discriminatory, it will then perform regression on the input text to determine the
        assesed percentage that each category applies.

        Parameters
        ----------
        input : str
            The input text to be classified.

        Returns
        -------
        dict[str, Any]
            The resulting classification and regression values for each category.
        """

        result = {
            'text_input': input,
            'results': []
        }

        sent_res_arr = []
        sentences = sent_tokenize(input)
        for sent in sentences:
            text_prediction, pred_class = self.discriminatory_inference(sent)

            sent_result = {
                'sentence': sent,
                'binary_classification': {
                    'classification': text_prediction,
                    'prediction_class': pred_class
                },
                'multilabel_regression': None
            }

            if pred_class == 1:
                ml_results = {
                    "Gender": None,
                    "Race": None,
                    "Sexuality": None,
                    "Disability": None,
                    "Religion": None,
                    "Unspecified": None
                }

                ml_infer_results = self.category_inference(sent)
                for idx, key in enumerate(ml_results.keys()):
                    ml_results[key] = min(max(ml_infer_results[idx], 0.0), 1.0)

                sent_result['multilabel_regression'] = ml_results
            sent_res_arr.append(sent_result)

        result['results'] = sent_res_arr
        return result
    
    def discriminatory_inference(self, text: str):
        """Performs inference on the input text to determine the binary classification.

        Parameters
        ----------
        text : str
            The input text to be classified.

        Returns
        -------
        tuple[str, Number]
            A tuple consisting of the string classification (Discriminatory or Non-Discriminatory) and the numeric prediction class (1 or 0).
        """

        bin_inputs = self._encode_binary(text)

        with torch.no_grad():
            bin_logits = self.bin_model(**bin_inputs).logits

        probs = torch.nn.functional.softmax(bin_logits, dim=-1)
        pred_class = torch.argmax(probs).item()
        bin_label_map = {0: "Non-Discriminatory", 1: "Discriminatory"}
        bin_text_pred = bin_label_map[pred_class]

        return bin_text_pred, pred_class
    
    def category_inference(self, text: str):
        """Performs inference on the input text to determine the regression values for the categories of discrimination.

        Parameters
        ----------
        text : str
            The input text to be classified.

        Returns
        -------
        list[float]
            A tuple consisting of the string classification (Discriminatory or Non-Discriminatory) and the numeric prediction class (1 or 0).
        """

        ml_inputs = self._encode_multilabel(text)

        with torch.no_grad():
            ml_outputs = self.ml_regr_model(**ml_inputs).logits
        
        ml_op_list = ml_outputs.squeeze().tolist()

        results = []
        for item in ml_op_list:
            results.append(max(0.0, item))

        return results