Adieva-15 commited on
Commit
62ecefe
·
1 Parent(s): f6fc4ec

setup ai-model sentiment

Browse files
__pycache__/config.cpython-313.pyc CHANGED
Binary files a/__pycache__/config.cpython-313.pyc and b/__pycache__/config.cpython-313.pyc differ
 
config.py CHANGED
@@ -1,5 +1,8 @@
1
- import os
2
  from dotenv import load_dotenv
 
 
 
3
 
4
  load_dotenv()
5
 
@@ -9,6 +12,7 @@ HF_TOKEN = os.getenv("HF_TOKEN")
9
 
10
 
11
  SENTIMENT_API = "https://huggingface.co/tabularisai/multilingual-sentiment-analysis"
 
12
  # OBJECT_DETECTION_API = "https://api-inference.huggingface.co/models/facebook/detr-resnet-50"
13
  # TEXT_GEN_API = "https://api-inference.huggingface.co/models/gpt2"
14
  # SUMMARIZATION_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
 
1
+
2
  from dotenv import load_dotenv
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import torch
5
+ import os
6
 
7
  load_dotenv()
8
 
 
12
 
13
 
14
  SENTIMENT_API = "https://huggingface.co/tabularisai/multilingual-sentiment-analysis"
15
+ model_name = "tabularisai/multilingual-sentiment-analysis"
16
  # OBJECT_DETECTION_API = "https://api-inference.huggingface.co/models/facebook/detr-resnet-50"
17
  # TEXT_GEN_API = "https://api-inference.huggingface.co/models/gpt2"
18
  # SUMMARIZATION_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
functions/__pycache__/sentiment.cpython-313.pyc CHANGED
Binary files a/functions/__pycache__/sentiment.cpython-313.pyc and b/functions/__pycache__/sentiment.cpython-313.pyc differ
 
functions/sentiment.py CHANGED
@@ -1,16 +1,59 @@
1
- import requests
2
- from config import SENTIMENT_API, headers
3
 
4
- async def sentiment_analysis(text:str)->str:
5
- payload = {"inputs":text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  try:
7
- response = requests.post(SENTIMENT_API, headers=headers, json=payload)
8
- result = response.json()
9
- if isinstance(result, list) and len(result)>0:
10
- labels = result[0]
11
- best = max(labels, key=lambda x: x['score'])
12
- label_map = {"LABEL_0":"негативный", "LABEL_1": "нейтральный", "LABEL_2": "позитивный"}
13
- return label_map.get(best['label'], best['label'])
14
- return "не удалось определить"
 
 
 
 
 
 
15
  except Exception as e:
16
- return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
1
 
2
+ from config import model_name
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ import torch
5
+
6
+
7
+ # import os
8
+ # # Отключаем все прокси-переменные
9
+ # os.environ.pop('HTTP_PROXY', None)
10
+ # os.environ.pop('HTTPS_PROXY', None)
11
+ # os.environ.pop('http_proxy', None)
12
+ # os.environ.pop('https_proxy', None)
13
+ # os.environ.pop('ALL_PROXY', None)
14
+
15
+ # async def sentiment_analysis(text:str)->str:
16
+ # payload = {"inputs":text}
17
+ # try:
18
+ # response = requests.post(SENTIMENT_API, headers=headers, json=payload)
19
+ # result = response.json()
20
+ # if isinstance(result, list) and len(result)>0:
21
+ # labels = result[0]
22
+ # best = max(labels, key=lambda x: x['score'])
23
+ # label_map = {"LABEL_0":"негативный", "LABEL_1": "нейтральный", "LABEL_2": "позитивный"}
24
+ # return label_map.get(best['label'], best['label'])
25
+ # return "не удалось определить"
26
+ # except Exception as e:
27
+ # return f"Error: {str(e)}"
28
+
29
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
30
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
31
+
32
+ async def sentiment_analysis(text)->str:
33
+ '''принимает строку, возвращает тональность'''
34
  try:
35
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
36
+ with torch.no_grad():
37
+ outputs = model(**inputs)
38
+ #вероятности классов
39
+ probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
40
+ pred_class = torch.argmax(probabilities, dim=-1).tolist()
41
+
42
+ if pred_class <=1:
43
+ return "Негативный"
44
+ elif pred_class ==2:
45
+ return "Нейтральный"
46
+ else:
47
+ return "Позитивный"
48
+
49
  except Exception as e:
50
+ return f"Error: {str(e)}"
51
+ #
52
+ #
53
+ # texts = [
54
+ # "I absolutely love the new design of this app!", "The customer service was disappointing.", "The weather is fine, nothing special.",
55
+ # "Я в восторге от этого нового гаджета!", "Этот сервис оставил у меня только разочарование.", "Встреча была обычной, ничего особенного.",
56
+ # ]
57
+ #
58
+ # for text, sentiment in zip(texts, sentiment_analysis(texts)):
59
+ # print(f"Text: {text}\nSentiment: {sentiment}\n")