-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
311 lines (236 loc) · 9.86 KB
/
app.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# app.py
from flask import Flask, render_template, request, jsonify
from keras.preprocessing.sequence import pad_sequences
import Vectorizers_Models
import numpy as np
app = Flask(__name__)
# Load the model (after choosing 'model_number' in Vectorizers_Models.py)
model = Vectorizers_Models.model
# Calling the vectorizers
english_vectorizer = Vectorizers_Models.eng_vectorization
french_vectorizer = Vectorizers_Models.fre_vectorization
def translate_sentence(
model, eng_text, eng_vectorization, fre_vectorization, sequence_length=14
):
# Tokenize and pad the English input sentence
eng_sequence = eng_vectorization(np.array([eng_text]))
eng_sequence = pad_sequences(eng_sequence, maxlen=sequence_length, padding="post")
# Initialize the decoder input with the start token
fre_sequence = np.zeros((1, sequence_length), dtype=np.int32)
fre_sequence[0, 0] = fre_vectorization.get_vocabulary().index("[start]")
# Inference loop
for i in range(1, sequence_length):
predictions = model.predict([eng_sequence, fre_sequence])
predicted_token_index = np.argmax(predictions[0, i - 1, :])
fre_sequence[0, i] = predicted_token_index
# Check for the end token
if fre_vectorization.get_vocabulary()[predicted_token_index] == "[end]":
break
# Convert the predicted indices to French text
translated_text = " ".join(
[fre_vectorization.get_vocabulary()[idx] for idx in fre_sequence[0] if idx > 0]
)
if not ("[end]" in translated_text):
translated_text += " [end]"
return translated_text.capitalize()
def translate_text(input_text):
translated_text = translate_sentence(
model,
input_text,
english_vectorizer,
french_vectorizer,
Vectorizers_Models.sequence_length,
)
return translated_text
@app.route("/")
def index():
return render_template("index.html")
@app.route("/translate", methods=["POST"])
def translate():
input_text = request.form["input_text"]
translated_text = translate_text(input_text)
cleaned_text = translated_text.replace("[start]", "").replace("[end]", "").strip()
return jsonify({"translated_text": cleaned_text})
if __name__ == "__main__":
app.run(debug=False)
#
#
#
#
# ##-----------VERSION utilisant les Vectorizers téléchargés (mais posant problème car ne récupère pas exactement le même Vectorizer)---------------------------
# # app.py
# from flask import Flask, render_template, request, jsonify
# # import tensorflow as tf
# # from keras.models import load_model
# from keras.preprocessing.sequence import pad_sequences
# # from keras.layers import TextVectorization
# import Vectorizers_Models
# # import joblib
# import numpy as np
# # import re, string
# app = Flask(__name__)
# # # Load the models
# # model_number = 1
# # model_path_v6 = "my_translation_model_gpu_v6.h5"
# # model_path_v80 = "my_translation_model_gpu_v80.h5"
# # model_v6 = load_model(model_path_v6) # model number 0
# # model_v80 = load_model(model_path_v80) # model number 1
# # seq_len = [14, 20][model_number]
# # model = [model_v6, model_v80][model_number]
# model = Vectorizers_Models.model
# # # Load the TextVectorization trained instances (config & weights) #MUST BE IN THE SAME PATH AS THE PROJECT
# # eng_vectorization_data_v6 = joblib.load("text_vectorizer_eng_data.joblib")
# # fre_vectorization_data_v6 = joblib.load("text_vectorizer_fr_data.joblib")
# # eng_vectorization_data_v80 = joblib.load("text_vectorizer_eng_20k-vocab20(v80).joblib")
# # fre_vectorization_data_v80 = joblib.load("text_vectorizer_fr_20k-vocab20(v80).joblib")
# # # Remove custom standardization from configurations (why : because otherwise weights loading may raise errors)
# # eng_vectorization_data_v6["config"]["standardize"] = None
# # fre_vectorization_data_v6["config"]["standardize"] = None
# # eng_vectorization_data_v80["config"]["standardize"] = None
# # fre_vectorization_data_v80["config"]["standardize"] = None
# # # redefine custom_standardization of the french vectorizer:
# # strip_chars = list(string.punctuation)
# # strip_chars.remove("[")
# # strip_chars.remove("]")
# # strip_chars = "".join(strip_chars)
# # def custom_standardization(input_string):
# # lowercase = tf.strings.lower(input_string)
# # return tf.strings.regex_replace(lowercase, "[%s]" % re.escape(strip_chars), "")
# # # Create the TextVectorization layers by taking the configs of the loaded instances
# # english_vectorizer = [
# # TextVectorization.from_config(eng_vectorization_data_v6["config"]),
# # TextVectorization.from_config(eng_vectorization_data_v80["config"]),
# # ][model_number]
# # french_vectorizer = [
# # TextVectorization.from_config(fre_vectorization_data_v6["config"]),
# # TextVectorization.from_config(fre_vectorization_data_v80["config"]),
# # ][model_number]
# # # Reassign the custom standardization function to the french vectorizer
# # french_vectorizer._custom_standardization = custom_standardization
# # # Set the weights for the layers
# # english_vectorizer.set_weights(
# # [eng_vectorization_data_v6["weights"], eng_vectorization_data_v80["weights"]][
# # model_number
# # ]
# # )
# # french_vectorizer.set_weights(
# # [fre_vectorization_data_v6["weights"], fre_vectorization_data_v80["weights"]][
# # model_number
# # ]
# # )
# ## RUN the file Vectorizers_Models before (once) !
# english_vectorizer = Vectorizers_Models.eng_vectorization
# french_vectorizer = Vectorizers_Models.fre_vectorization
# def translate_sentence(
# model, eng_text, eng_vectorization, fre_vectorization, sequence_length=14
# ):
# # Tokenize and pad the English input sentence
# eng_sequence = eng_vectorization(np.array([eng_text]))
# eng_sequence = pad_sequences(eng_sequence, maxlen=sequence_length, padding="post")
# # Initialize the decoder input with the start token
# fre_sequence = np.zeros((1, sequence_length), dtype=np.int32)
# fre_sequence[0, 0] = fre_vectorization.get_vocabulary().index("[start]")
# # Inference loop
# for i in range(1, sequence_length):
# predictions = model.predict([eng_sequence, fre_sequence])
# predicted_token_index = np.argmax(predictions[0, i - 1, :])
# fre_sequence[0, i] = predicted_token_index
# # Check for the end token
# if fre_vectorization.get_vocabulary()[predicted_token_index] == "[end]":
# break
# # Convert the predicted indices to French text
# translated_text = " ".join(
# [fre_vectorization.get_vocabulary()[idx] for idx in fre_sequence[0] if idx > 0]
# )
# if not ("[end]" in translated_text):
# translated_text += " [end]"
# return translated_text
# def translate_text(input_text):
# translated_text = translate_sentence(
# model,
# input_text,
# english_vectorizer,
# french_vectorizer,
# Vectorizers_Models.sequence_length,
# )
# return translated_text
# @app.route("/")
# def index():
# return render_template("index.html")
# @app.route("/translate", methods=["POST"])
# def translate():
# input_text = request.form["input_text"]
# translated_text = translate_text(input_text)
# cleaned_text = translated_text.replace("[start]", "").replace("[end]", "").strip()
# return jsonify({"translated_text": cleaned_text})
# if __name__ == "__main__":
# app.run(debug=False)
#
#
#
#
# ##-----------------CODE POUR UN CHATBOT UTILISANT LES APIs DE GPT3 (FAIT LES IMPORTS NECESSAIRES)
# from flask_sqlalchemy import SQLAlchemy
# # Autres import
# # (Faut adapter les fichier js et css)-----------------##
# app = Flask(__name__)
# # create the extension
# db = SQLAlchemy()
# # create the app
# # configure the SQLite database, relative to the app instance folder
# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///ma_database.db"
# # initialize the app with the extension
# db.init_app(app)
# class ChatExchange(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# user_message = db.Column(db.String(255))
# assistant_response = db.Column(db.String(255))
# with app.app_context():
# db.create_all()
# # from app.models import ChatExchange
# # Dans votre vue Flask pour afficher les échanges
# @app.route("/chat-history") # Route pour afficher l'historique des échanges
# def show_chat_history():
# chat_history = ChatExchange.query.all()
# return render_template("index.html", chat_history=chat_history)
# q_list = []
# r_list = []
# @app.route("/hello/")
# def hello_world():
# return "<p>Hello, World!</p>"
# @app.route("/")
# def hello():
# return render_template("index.html") # , messages=messages)
# @app.route("/prompt", methods=["POST"])
# def prompt():
# message = {}
# data = request.form["prompt"]
# message["answer"] = ask_question_to_pdf.gpt3_completion(data)
# # Enregistrez l'échange dans la base de données dès que la réponse d'OpenAI est générée
# exchange = ChatExchange(user_message=data, assistant_response=message["answer"])
# db.session.add(exchange)
# db.session.commit()
# return message
# @app.route("/question", methods=["GET"])
# def question():
# q = ask_question_to_pdf.ask_question_to_pdf(
# "Pose moi une question au hasard sur le texte", ask_question_to_pdf.filename
# )
# q_list.append(q)
# return {"answer": q}
# @app.route("/answer", methods=["POST"])
# def reponse():
# r = request.form["prompt"]
# answer = ask_question_to_pdf.verif(q_list[-1], r, ask_question_to_pdf.filename)
# exchange = ChatExchange(
# user_message=q_list[-1],
# assistant_response="Ma réponse : " + r + "; Correction : " + answer,
# )
# db.session.add(exchange)
# db.session.commit()
# return {"answer": answer}
# @app.route("/upload", methods=["POST"])
# def upload():
# f = request.files["background"]
# f.save("filename.pdf")
# return "file uploaded"