Spaces:
Sleeping
Sleeping
Download src/predict.py from duvr/sentiment_analysis: direct link, hf CLI and curl.
- Browser
- Download file 1.48 kB
-
https://huggingface.co/spaces/duvr/sentiment_analysis/resolve/main/src/predict.py
- Command line
-
hf download hf://spaces/duvr/sentiment_analysis/src/predict.py
-
curl -L -o predict.py https://huggingface.co/spaces/duvr/sentiment_analysis/resolve/main/src/predict.py
1.48 kB
| import torch | |
| import numpy as np | |
| from src.loader import get_model | |
| from src.config import AVG_POOLING, INDEX_TO_LABEL | |
| from src.nlp import preprocess | |
| from src.clean import clean_text | |
| from src.embedding_loader import EmbeddingLoader | |
| from src.utils import apply_pooling | |
| models_with_embeddings = ["SWEM", "MLP", "RNN", "LSTM"] | |
| models_with_pooling = ["SWEM", "MLP"] | |
| def predict(lang: str, model_name: str, text: str): | |
| input = clean_text(text, lang) | |
| input = preprocess([input], True, lang) # list[str] | |
| embedding_model = None | |
| if model_name in models_with_embeddings: | |
| input = [input[0].split()] # list[str] | |
| embedding_model = EmbeddingLoader(lang) | |
| input = embedding_model.get_embeddings(input) # list[list[float32]] | |
| if model_name in models_with_pooling: | |
| input = apply_pooling( | |
| input, embedding_model.vector_size(), AVG_POOLING | |
| ) # list[list[float64]] | |
| if model_name in ["MLP", "RNN", "LSTM"]: | |
| input = torch.tensor(np.array(input), dtype=torch.float32) | |
| if model_name in ["RNN", "LSTM"]: | |
| length = torch.tensor([len(input)]) | |
| input = torch.nn.utils.rnn.pad_sequence( | |
| input, batch_first=True, padding_value=0 | |
| ) | |
| clf = get_model(lang, model_name, embedding_model) | |
| if model_name in ["RNN", "LSTM"]: | |
| return INDEX_TO_LABEL[clf.predict(input, length)[0]] | |
| return INDEX_TO_LABEL[clf.predict(input)[0]] | |