Soufianesejjari's picture
Add application file
bcb9fa1
raw
history blame
2.54 kB
from flask import Flask, request, jsonify
from keras.models import load_model
import pickle
import numpy as np
from keras.preprocessing.sequence import pad_sequences
app = Flask(__name__)
max_sequence_length = 180
# Charger le modèle entraîné
try:
model = load_model('word_prediction_model.h5')
except Exception as e:
print(f"Erreur lors du chargement du modèle : {str(e)}")
model = None
# Charger le tokenizer
try:
with open('tokenizer.pickle', 'rb') as handle:
tokenizer = pickle.load(handle)
except Exception as e:
print(f"Erreur lors du chargement du tokenizer : {str(e)}")
tokenizer = None
# Fonction de prédiction des mots suivants avec probabilités
def predict_next_words_with_proba(input_phrase, top_n=5):
if tokenizer is None or model is None:
return [], []
# Tokeniser la phrase d'entrée
input_sequence = tokenizer.texts_to_sequences([input_phrase])[0]
# Remplir la séquence à la longueur maximale de séquence
padded_sequence = pad_sequences([input_sequence], maxlen=max_sequence_length-1, padding='pre')
# Prédire les probabilités des mots suivants
predicted_probs = model.predict(padded_sequence)[0]
# Obtenir les indices des mots avec les probabilités les plus élevées
top_indices = predicted_probs.argsort()[-top_n:][::-1]
# Obtenir les mots correspondants aux indices
top_words = [tokenizer.index_word[index] for index in top_indices]
# Obtenir les probabilités correspondantes
top_probabilities = predicted_probs[top_indices]
return top_words, top_probabilities
@app.route('/test', methods=['GET'])
def test():
data = request.get_json()
input_phrase = data['input_phrase']
response = {
"top_words": "test",
"top_probabilities": input_phrase
}
return jsonify(response)
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.get_json()
input_phrase = data['input_phrase']
top_n = data.get('top_n', 5) # Par défaut, retourne les 5 meilleurs mots
top_words, top_probabilities = predict_next_words_with_proba(input_phrase, top_n)
response = {
"top_words": top_words,
"top_probabilities": top_probabilities.tolist()
}
return jsonify(response)
except Exception as e:
return jsonify(error=str(e)), 500
if __name__ == '__main__':
app.run(debug=True)