I have two problems actually. The first is that I am running a background task in my api that is taking an image and predicting on it. . For some reason I cannot store the background task in a variable and return it. I need to do this for the second part of my problem.
API Code:
from starlette.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, File, UploadFile, BackgroundTasks
from tensorflow.keras import preprocessing
from fastapi.staticfiles import StaticFiles
from keras.models import load_model
from PIL import Image
import numpy as np
import uvicorn
app = FastAPI()
app.mount("/Templates", StaticFiles(directory="Templates"), name="Templates")
templates = Jinja2Templates(directory="Templates")
model_dir = 'F:\\Saved-Models\\Dog-Cat-Models\\json_function_test_dog_cat_optuna.h5'
model = load_model(model_dir)
def predict_image(image):
pp_dogcat_image = Image.open(image.file).resize((150, 150), Image.NEAREST).convert("RGB")
pp_dogcat_image_arr = preprocessing.image.img_to_array(pp_dogcat_image)
input_arr = np.array([pp_dogcat_image_arr])
prediction = np.argmax(model.predict(input_arr), axis=-1)
if str(prediction) == '[1]':
answer = "It's a Dog"
else:
answer = "It's a Cat"
return answer
@app.get('/')
async def index():
return RedirectResponse(url="/Templates/index.html")
# Background tasks are so that we can return a response regardless how long it takes to process image data
@app.post('/prediction_page')
async def prediction_form(background_tasks: BackgroundTasks, dogcat_img: UploadFile = File(...)):
answer = background_tasks.add_task(predict_image, image=dogcat_img)
return answer
if __name__ == '__main__':
uvicorn.run(app, host='localhost', port=8000)
The second issue is that I am trying to pass this back into my html file in the form of a Jinja tag. If I can get to the point of storing my background task, I would like to return it to the actual html template. I have looked far and wide and FastAPI has useless information to do exactly this with a get.post.
HTML Code:
<div class="prediction_box"><p>Select an image of a dog or a cat and the AI will print out a prediction of what he
thinks
it is.....</p><br>
<!--enctype="multipart/form-data" enables UploadFile data to pass through-->
<form action="/prediction_page" enctype="multipart/form-data" method="post">
<label for="image-upload" class="custom-file-upload">Select Image:</label>
<input type="file" id="image-upload" name="dogcat_img"><br>
<input class="custom-submit-button" type="submit">
</form>
<p>{{answer}}</p>
</div>