Hjgugugjhuhjggg commited on
Commit
7f7bd2a
1 Parent(s): dc7b924

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -0
app.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import random
3
+ import nltk
4
+ import numpy
5
+ from nltk.stem import LancasterStemmer
6
+ from tensorflow.python.keras.layers import Dense
7
+ from tensorflow.python.keras.models import Sequential
8
+ from flask import Flask, request, jsonify
9
+
10
+ app = Flask(__name__)
11
+
12
+ nltk.download('all')
13
+ stemmer = LancasterStemmer()
14
+
15
+ intents = []
16
+
17
+ def generar_pregunta():
18
+ temas = ["hola", "buenos días", "buenas tardes", "adiós", "hasta luego"]
19
+ plantillas = [
20
+ '¿Qué es {}?',
21
+ '¿Cuál es el significado de {}?',
22
+ '¿Puedes describir {}?',
23
+ '¿Qué relación hay entre {} y {}?',
24
+ '¿Cuál es la diferencia entre {} y {}?',
25
+ ]
26
+
27
+ tema = random.choice(temas)
28
+ plantilla = random.choice(plantillas)
29
+
30
+ if '{}' in plantilla:
31
+ palabra1 = random.choice(temas)
32
+ palabra2 = random.choice(temas)
33
+ pregunta = plantilla.format(tema, palabra1, palabra2)
34
+ else:
35
+ pregunta = plantilla.format(tema)
36
+
37
+ return pregunta
38
+
39
+ def entrenar_modelo():
40
+ global intents
41
+ words = []
42
+ labels = []
43
+ docs_x = []
44
+ docs_y = []
45
+
46
+ for intent in intents:
47
+ for pattern in intent["patterns"]:
48
+ wrds = nltk.word_tokenize(pattern)
49
+ words.extend(wrds)
50
+ docs_x.append(wrds)
51
+ docs_y.append(intent["tag"])
52
+ if intent["tag"] not in labels:
53
+ labels.append(intent["tag"])
54
+
55
+ words = [stemmer.stem(w.lower()) for w in words if w != "?"]
56
+ words = sorted(list(set(words)))
57
+ labels = sorted(labels)
58
+
59
+ training = []
60
+ output = []
61
+ output_empty = [0 for _ in range(len(labels))]
62
+
63
+ for x, doc in enumerate(docs_x):
64
+ bag = []
65
+ wrds = [stemmer.stem(w.lower()) for w in doc]
66
+ for w in words:
67
+ if w in wrds:
68
+ bag.append(1)
69
+ else:
70
+ bag.append(0)
71
+ output_row = output_empty[:]
72
+ output_row[labels.index(docs_y[x])] = 1
73
+ training.append(bag)
74
+ output.append(output_row)
75
+
76
+ training = numpy.array(training)
77
+ output = numpy.array(output)
78
+
79
+ modelo = Sequential()
80
+ modelo.add(Dense(8, input_shape=[len(words)], activation='relu'))
81
+ modelo.add(Dense(len(labels), activation='softmax'))
82
+ modelo.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
83
+ modelo.fit(training, output, epochs=1000, batch_size=8)
84
+
85
+ return modelo
86
+
87
+ def responder_pregunta(modelo, pregunta):
88
+ global intents
89
+ words = []
90
+ labels = []
91
+
92
+ for intent in intents:
93
+ for pattern in intent["patterns"]:
94
+ wrds = nltk.word_tokenize(pattern)
95
+ words.extend(wrds)
96
+ if intent["tag"] not in labels:
97
+ labels.append(intent["tag"])
98
+
99
+ words = [stemmer.stem(w.lower()) for w in words if w != "?"]
100
+ words = sorted(list(set(words)))
101
+ labels = sorted(labels)
102
+
103
+ bag = [0 for _ in range(len(words))]
104
+ s_words = nltk.word_tokenize(pregunta)
105
+ s_words = [stemmer.stem(word.lower()) for word in s_words]
106
+
107
+ for se in s_words:
108
+ for i, w in enumerate(words):
109
+ if w == se:
110
+ bag[i] = 1
111
+
112
+ result = modelo.predict(numpy.array([bag]))
113
+ result_index = numpy.argmax(result)
114
+ tag = labels[result_index]
115
+
116
+ if result[0][result_index] > 0.7:
117
+ for tg in intents:
118
+ if tg['tag'] == tag:
119
+ responses = tg['responses']
120
+ return random.choice(responses)
121
+ else:
122
+ return "I didn't get that, try again"
123
+
124
+ @app.route('/chat', methods=['GET', 'POST'])
125
+ def chatBot():
126
+ chatInput = request.form.get('chatInput', '')
127
+ if not chatInput:
128
+ return jsonify(chatBotReply="No se proporcionó entrada.")
129
+ try:
130
+ intents.append({
131
+ "tag": chatInput,
132
+ "patterns": [chatInput],
133
+ "responses": ["Respuesta a " + chatInput]
134
+ })
135
+
136
+ modelo = entrenar_modelo()
137
+ reply = responder_pregunta(modelo, chatInput)
138
+ return jsonify(chatBotReply=reply)
139
+ except Exception as e:
140
+ return jsonify(chatBotReply=f"Error en chatBot: {e}")
141
+
142
+ if __name__ == '__main__':
143
+ app.run(host='0.0.0.0', port=7860, debug=True)