Spaces:
Paused
Paused
File size: 4,895 Bytes
ae207dc 39109cc ae207dc 006a091 ae207dc 1102fa2 ae207dc | 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 | import torch
from transformers import (AutoModelForSequenceClassification,
TFAutoModelForSequenceClassification,
AutoTokenizer,
AutoConfig, pipeline)
from accelerate import Accelerator
import torch.nn.functional as F
accelerator = Accelerator()
device = accelerator.device
torch.set_default_device(device)
print(device)
class Sentiments:
"""The class calculates sentiments for each string in input list or for single text."""
def __init__(self, model_path: str, input_data: str | list, as_dict: bool = True):
"""
Parameters
----------
model_path: model path from huggingface.co/models
input_data: single text or list of texts
as_dict: if True input_data is a list of dictionaries with keys "Content", "Date" and other fields. If False,
the list contains strings only.
"""
self.input_data = input_data
self.as_dict = as_dict
self.model_path: str = model_path
self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
self.model = AutoModelForSequenceClassification.from_pretrained(self.model_path).to(device)
self.model = accelerator.prepare(self.model)
# self.model.to(device)
self.max_length = self.model.config.max_position_embeddings
self.pipe = pipeline(task="text-classification",
model=self.model,
tokenizer=self.tokenizer,
device=device,
truncation=self.max_length,
padding=True,
function_to_apply="softmax")
self.list_of_sentiments = []
self.df_sentiments = None
def get_sentiments_for_text(self, text: str) -> dict:
"""The function calculates sentiments for single text. It truncates and pads the text.
"""
result = {}
encoded_input = self.tokenizer(text=text,
padding=True,
truncation=True,
max_length=self.max_length,
return_tensors='pt').to(device)
output = self.model(**encoded_input)
probabilities = F.softmax(output.logits, dim=-1).cuda()
for index, name in self.model.config.id2label.items():
result[name] = probabilities[0][index].item()
return result
def get_sentiments_for_batch(self):
"""
Calculates sentiments for all texts in batch. Easy to fill all CUDA device memory.
:return:
"""
self.list_of_sentiments = []
if not self.as_dict:
text_dicts = [{"Content": text} for text in self.input_data]
texts_list = self.input_data
else:
text_dicts = self.input_data
texts_list = [text.get("Content") for text in self.input_data]
encoded_inputs = self.tokenizer(texts_list,
padding=True,
truncation=True,
max_length=self.max_length,
return_tensors="pt").to(device)
outputs = self.model(**encoded_inputs)
probabilities = F.softmax(outputs.logits, dim=-1).cuda()
for text_item, probs in zip(text_dicts, probabilities):
single_sent = {self.model.config.id2label[i]: prob.item() for i, prob in enumerate(probs)}
for key, value in text_item.items():
single_sent[key] = value
self.list_of_sentiments.append(single_sent)
def get_sentiments_separately(self):
"""
Calulates sentiments for each string in input list
Parameters
----------
batch: bool - whether to take input data as batch or as single text (to save memory).
Returns
-------
list of texts (and dates) with sentiments for each string
"""
self.list_of_sentiments = []
for text_data in self.input_data:
if not self.as_dict:
text_dict = {"Content": text_data}
else:
text_dict = text_data.copy()
if "Content" in text_dict:
sentiments = self.get_sentiments_for_text(text_dict.get("Content"))
text_dict.update(sentiments)
self.list_of_sentiments.append(text_dict)
def get_sentiments(self, batch = False):
sent_calc_func = self.get_sentiments_for_batch if batch else self.get_sentiments_separately
sent_calc_func()
def main():
pass
if __name__ =='__main__':
main()
|