Spaces:
Paused
Paused
Download sentiments.py from pgc3105/emodet: direct link, hf CLI and curl.
- Browser
- Download file 4.9 kB
-
https://huggingface.co/spaces/pgc3105/emodet/resolve/main/sentiments.py
- Command line
-
hf download hf://spaces/pgc3105/emodet/sentiments.py
-
curl -L -o sentiments.py https://huggingface.co/spaces/pgc3105/emodet/resolve/main/sentiments.py
4.9 kB
| 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() | |