Spaces:
Runtime error
Runtime error
File size: 1,675 Bytes
3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 bcb9fa1 3680e02 28721ba 3680e02 |
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 |
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from keras.models import load_model
import pickle
import numpy as np
from keras.preprocessing.sequence import pad_sequences
app = FastAPI()
max_sequence_length = 180
# Load the trained model
try:
model = load_model('word_prediction_model.h5')
except Exception as e:
print(f"Error loading the model: {str(e)}")
model = None
# Load the tokenizer
try:
with open('tokenizer.pickle', 'rb') as handle:
tokenizer = pickle.load(handle)
except Exception as e:
print(f"Error loading the tokenizer: {str(e)}")
tokenizer = None
class PredictionRequest(BaseModel):
input_phrase: str
top_n: int = 5
class PredictionResponse(BaseModel):
top_words: list
top_probabilities: list
@app.post("/predict", response_model=PredictionResponse)
def predict(request: PredictionRequest):
if tokenizer is None or model is None:
raise HTTPException(status_code=500, detail="Model or tokenizer not loaded")
input_phrase = request.input_phrase
top_n = request.top_n
input_sequence = tokenizer.texts_to_sequences([input_phrase])[0]
padded_sequence = pad_sequences([input_sequence], maxlen=max_sequence_length-1, padding='pre')
predicted_probs = model.predict(padded_sequence)[0]
top_indices = predicted_probs.argsort()[-top_n:][::-1]
top_words = [tokenizer.index_word[index] for index in top_indices]
top_probabilities = predicted_probs[top_indices]
return {"top_words": top_words, "top_probabilities": top_probabilities.tolist()}
@app.get("/")
def read_root():
return {"message": "Hello from MDS Darija Prediction Team!"}
|