-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
64 lines (50 loc) · 2.37 KB
/
main.py
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
from fastapi import FastAPI
from tensorflow.keras.models import load_model
from transformers import BertTokenizer
from gensim.models import FastText
from tensorflow.keras.preprocessing.sequence import pad_sequences
import pickle
import numpy as np
app = FastAPI()
# Load models
model_sentiments_data_original = load_model("modelos/nlp_pqrs_original.h5")
model_sentiments_data_mezclada = load_model("modelos/nlp_sintetica.h5")
with open("modelos/tokenizer.pkl", "rb") as file:
tokenizer = pickle.load(file)
fasttext_model_lda = FastText.load("modelos/FastText-Model-For-ABSA.bin")
# Define aspects for similarity
aspects = [
"citas medicas", "enfermeria", "urgencias", "gestion documental",
"procedimientos de salud", "aseo y limpieza", "facturacion"
]
@app.post("/sentimientos_datos_original")
def predict_sentimiento(text: str):
tokens = tokenizer.texts_to_sequences([text])
x_new = pad_sequences(tokens, maxlen=50)
predictions = model_sentiments_data_original.predict([x_new, x_new])
emotions = {0: 'Negativo', 1: 'Neutral', 2: 'Positivo'}
response = {emotions[i]: round(float(pred) * 100, 2) for i, pred in enumerate(predictions[0])}
return {"texto": text, "predicciones": response}
@app.post("/sentimientos__datos_mezclados")
def predict_sentimiento(text: str):
tokens = tokenizer.texts_to_sequences([text])
x_new = pad_sequences(tokens, maxlen=50)
predictions = model_sentiments_data_mezclada.predict([x_new, x_new])
emotions = {0: 'Negativo', 1: 'Neutral', 2: 'Positivo'}
response = {emotions[i]: round(float(pred) * 100, 2) for i, pred in enumerate(predictions[0])}
return {"texto": text, "predicciones": response}
@app.post("/tendencias_lda")
def predict_tendencias(text: str):
def get_similarity(text, aspect):
if fasttext_model_lda is None:
return 0
try:
text_tokens = text.split()
aspect_tokens = aspect.split()
return fasttext_model_lda.wv.n_similarity(text_tokens, aspect_tokens)
except Exception:
return 0
similarities = {aspect: get_similarity(text, aspect) for aspect in aspects}
top_aspects = sorted(similarities.items(), key=lambda item: item[1], reverse=True)[:5]
response = [{"aspecto": aspect, "similitud": round(similarity * 100, 2)} for aspect, similarity in top_aspects]
return {"texto": text, "top_tendencias": response}