Cara Mudah Deploy Tensorflow Simple Project ke Heroku App
Halo teman-teman, pada kesempatan kali ini kita akan mencoba membuat aplikasi prediction sederhana menggunakan Tensorflow dan juga Flask.
Prerequirement :
- Install Git
- Install Python (versi 3.5 keatas)
- Install vscode
- Install PIP
- Install Heroku CLI
Langkah pertama, silahkan jalankan CMD sebagai Administrator

kemudian silahkan change directory sesuai keinginan teman-teman mau membuat projectnya dimana, misalnya saja seperti dibawah ini :
cd c:/
mkdir coba-flask-tensorflow
cd coba-flask-tensorflow
Selanjutnya, kita install virtual environment
python -m venv venv
pip install virtualenv
Setelah itu kita setting dan aktifkan virtual environmentnya
virtualenv venv
./venv.\venv\Scripts\activate
Virtual environment sudah selesai, langkah berikutnya kita install library yang dibutuhkan untuk menjalankan aplikasinya nanti
pip install flask
pip install numpy
pip install pillow
pip install tensorflow-cpu
Library sudah siap, kemudian buatlah file baru dengan nama app.py di root folder

Isi file app.py dengan kode dibawah ini
import base64
import numpy as np
import io
from PIL import Image
# for our model
import tensorflow as tf
from tensorflow.keras.applications.resnet50 import ResNet50, decode_predictions
# to retrieve and send back data
from flask import request
from flask import jsonify
from flask import Flask# create a variable named app
app = Flask(__name__)# create our model
IMG_SHAPE = (224, 224, 3)
def get_model():
model = ResNet50(include_top=True, weights=”imagenet”, input_shape=IMG_SHAPE)
print(“[+] model loaded”)
return model# decode the imaeg coming from the request
def decode_request(req):
encoded = req[“image”]
decoded = base64.b64decode(encoded)
return decoded# preprocess image before sending it to the model
def preprocess(decoded):
#resize and convert in RGB in case image is in RGBA
pil_image = Image.open(io.BytesIO(decoded)).resize((224,224), Image.LANCZOS).convert(“RGB”)
image = np.asarray(pil_image)
batch = np.expand_dims(image, axis=0)
return batch# load model so it’s in memory and not loaded each time there is a request
model = get_model()
# function predict is called at each request
@app.route(“/predict”, methods=[“POST”])
def predict():print(“[+] request received”)
# get the data from the request and put ir under the right format
req = request.get_json(force=True)
image = decode_request(req)
batch = preprocess(image)
# actual prediction of the model
prediction = model.predict(batch)
# get the label of the predicted class
print(decode_predictions(prediction))
a=decode_predictions(prediction)
b=a[0][0]
top_label =[(b[1],str(b[2]))]
#top_label = [(i[1],str(i[2])) for i in decode_predictions(prediction)[0][0]]
print(top_label)
# create the response as a dict
response = {“prediction”: top_label}
print(“[+] results {}”.format(response))
return jsonify(response)
# return it as json
Jika sudah, buat folder baru dengan nama static dan buat file baru didalamnya berikan nama app.html. Isikan kode berikut ke dalamnya
<!DOCTYPE html>
<html>
<head>
<!-- title displayed on the browser tab -->
<title>image classification app</title>
</head>
<!-- contains our front-end elements -->
<body>
<!--input to upload the image-->
<input id="upload" type="file">
<!--button to activate the script which call our Flask app-->
<button id="predict-button">Predict</button>
<h1>Predictions</h1>
<!--parapgraph where we will display the result-->
<p><span id="prediction"></span></p>
<!--display the uploaded image-->
<img id="selected-image" src=""/>
</body><!--jquery lib-->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!--The script which call our Flask app-->
<script>
let base64Image;
// when we upload an image
$("#upload").change(function() {
let reader = new FileReader();
reader.onload = function(e) {
let dataURL = reader.result;
$('#selected-image').attr("src", dataURL);
base64Image = dataURL.replace("data:image/png;base64,","");
}
reader.readAsDataURL($("#upload")[0].files[0]);
//reset pred text as empty
$("#prediction").text("");
});$("#predict-button").click(function(){
let message = {image: base64Image}
// you could also use 127.0.0.1 instead of 0.0.0.0
$.post("http://127.0.0.1:5000/predict", JSON.stringify(message), function(response){
$("#prediction").text("results: "+response.prediction[0][0]+" ( confidence : "+response.prediction[0][1]+")");
console.log(response);
});
});
</script>
</html>
http://127.0.0.1:5000/predict (ganti kode 127.0.0.1:5000 nanti dengan nama subdomain yang diberikan oleh heroku waktu mau dihosting).
Programnya sudah siap, saatnya kita testing
set FLASK_ENV=development
flask run
buka browser lalu ketik 127.0.0.1:5000/static/app.html
Jika tidak ada kendala, akan menampilkan sebuah inputan image sederhana dan tombol predict dimana jika ditekan akan menghasilkan sebuah label sesuai perkiraan data model hasil yang dikeluarkan
Untuk deploy ke heroku keluarkan dulu running server flasknya dengan command CTRL + C. Kemudian ketikkan perintah berikut
echo web: gunicorn app:app > Procfile
pip install gunicorn
pip freeze > requirements.txt
Setelah itu, silahkan teman-teman login ke heroku dan buat project baru dengan cara
Create>New App
Masukkan nama app (misalnya coba-flask-tensorflow)
Jika sudah, kembali ke terminal ketik command berikut
heroku login
git init
heroku git:remote -a coba-flask-tensorflow
git add .
git commit -am “first commit”
git push heroku main
Demo Aplikasi hasil jadinya