Skip to content

Commit

Permalink
deploy to flask
Browse files Browse the repository at this point in the history
  • Loading branch information
daaffalbari committed Jan 11, 2024
0 parents commit d393813
Show file tree
Hide file tree
Showing 26 changed files with 324 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .deployment
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[config]
SCM_DO_BUILD_DURING_DEPLOYMENT=true
11 changes: 11 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Dockerfile
README.md
*.pyc
*.pyo
*.pyd
__pycache__
.pytest_cache
test
.gcloudignore
.gitignore
.idea
19 changes: 19 additions & 0 deletions .gcloudignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# This file specifies files that are *not* uploaded to Google Cloud
# using gcloud. It follows the same syntax as .gitignore, with the addition of
# "#!include" directives (which insert the entries of the given .gitignore-style
# file at that point).
#
# For more information, run:
# $ gcloud topic gcloudignore
#
.gcloudignore
# If you would like to upload your .git directory, .gitignore file or files
# from your .gitignore file, remove the corresponding line
# below:
.git
.gitignore

# Python pycache:
__pycache__/
# Ignored by the build system
/setup.cfg
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
best_model.h5
./best_model.h5
*.h5
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/deploy.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"appService.zipIgnorePattern": [
"__pycache__{,/**}",
"*.py[cod]",
"*$py.class",
".Python{,/**}",
"build{,/**}",
"develop-eggs{,/**}",
"dist{,/**}",
"downloads{,/**}",
"eggs{,/**}",
".eggs{,/**}",
"lib{,/**}",
"lib64{,/**}",
"parts{,/**}",
"sdist{,/**}",
"var{,/**}",
"wheels{,/**}",
"share/python-wheels{,/**}",
"*.egg-info{,/**}",
".installed.cfg",
"*.egg",
"MANIFEST",
".env{,/**}",
".venv{,/**}",
"env{,/**}",
"venv{,/**}",
"ENV{,/**}",
"env.bak{,/**}",
"venv.bak{,/**}",
".vscode{,/**}"
],
"appService.defaultWebAppToDeploy": "/subscriptions/6b27ef89-f6a5-4163-a07d-295734711582/resourceGroups/peaky-blinder/providers/Microsoft.Web/sites/peaky-blinder-ai",
"appService.deploySubpath": "."
}
22 changes: 22 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

# Use the official lightweight Python image.
# https://hub.docker.com/_/python
FROM python:3.9-slim

# Allow statements and log messages to immediately appear in the logs
ENV PYTHONUNBUFFERED True

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

# Install production dependencies.
RUN pip install --no-cache-dir -r requirements.txt

# Run the web service on container startup. Here we use the gunicorn
# webserver, with one worker process and 8 threads.
# For environments with multiple CPU cores, increase the number of workers
# to be equal to the cores available.
# Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling.
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app
44 changes: 44 additions & 0 deletions Untitled-1.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
SUBSCRIPTION="Microsoft Azure Sponsorship"
RESOURCEGROUP="peaky-blinder"
LOCATION="southeastasia"
PLANNAME="ASP-moonchickdiseasegroup-8645"
PLANSKU="B2"
SITENAME="peaky-blinder-ai"
RUNTIME="PYTHON|3.9"

# login supports device login, username/password, and service principals
# see https://docs.microsoft.com/en-us/cli/azure/?view=azure-cli-latest#az_login
az login
# list all of the available subscriptions
az account list -o table
# set the default subscription for subsequent operations
az account set --subscription $SUBSCRIPTION
# create a resource group for your application
az group create --name $RESOURCEGROUP --location $LOCATION
# create an appservice plan (a machine) where your site will run
az appservice plan create --name $PLANNAME --location $LOCATION --is-linux --sku $PLANSKU --resource-group $RESOURCEGROUP
# create the web application on the plan
# specify the node version your app requires
az webapp create --name $SITENAME --plan $PLANNAME --runtime $RUNTIME --resource-group $RESOURCEGROUP

#upgrade pip
az webapp config appsettings set --name $SITENAME --resource-group $RESOURCEGROUP --settings PRE_BUILD_COMMAND="python -m pip install --upgrade pip && pip install -r requirements.txt"

# To set up deployment from a local git repository, uncomment the following commands.
# first, set the username and password (use environment variables!)
# USERNAME=""
# PASSWORD=""
# az webapp deployment user set --user-name $USERNAME --password $PASSWORD

# now, configure the site for deployment. in this case, we will deploy from the local git repository
# you can also configure your site to be deployed from a remote git repository or set up a CI/CD workflow
# az webapp deployment source config-local-git --name $SITENAME --resource-group $RESOURCEGROUP

# the previous command returned the git remote to deploy to
# use this to set up a new remote named "azure"
# git remote add azure "https://$USERNAME@$SITENAME.scm.azurewebsites.net/$SITENAME.git"
# push master to deploy the site
# git push azure master

# browse to the site
# az webapp browse --name $SITENAME --resource-group $RESOURCEGROUP
3 changes: 3 additions & 0 deletions app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
runtime: python39
entrypoint: gunicorn -b :$PORT main:app
instance_class: F4_1G
Binary file added data/0 label.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/03b373718013.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/paangga3.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/pangga.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/test.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/test3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/three.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
135 changes: 135 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
from flask import Flask, request, jsonify
import tensorflow as tf
from tensorflow import keras
import numpy as np
import io
import os
from PIL import Image, ImageOps
import cv2

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


model = keras.models.load_model('best_model.h5')


def transform_image(pillow_image):
target_size = (331, 331)
resize_image = ImageOps.fit(pillow_image, target_size, Image.LANCZOS)

grayscale_image = ImageOps.grayscale(resize_image)

img_array = np.array(grayscale_image)

img_array_eq = cv2.equalizeHist(img_array)
img_array_eq_rgb = cv2.cvtColor(img_array_eq, cv2.COLOR_GRAY2RGB)

normalized_image = img_array_eq_rgb / 255.0

normalized_image = cv2.resize(normalized_image, (331, 331))

normalized_image = np.expand_dims(normalized_image, axis=0)

return normalized_image


def predict(x):
predictions = model(x)
predictions = tf.nn.softmax(predictions)
pred0 = predictions[0]
label0 = np.argmax(pred0)
return label0


app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == "POST":
file = request.files.get('file')
if file is None or file.filename == "":
return jsonify({"error": "no file"})

try:
image_bytes = file.read()
pillow_img = Image.open(io.BytesIO(image_bytes)).convert('L')
tensor = transform_image(pillow_img)
prediction = predict(tensor)

label_names = {0: 'Tidak ada DR (Tidak ada Retinopati Diabetes)',
1: 'DR Ringan (Mild)',
2: 'DR Sedang (Moderate)',
3: 'DR Parah (Severe)',
4: 'DR Proliferatif (Proliferative)'}

label_name = label_names.get(prediction, 'Unknown')

# Konversi nilai 'prediction' menjadi int
prediction = int(prediction)

recommendation = {}

if label_name == 'Tidak ada DR (Tidak ada Retinopati Diabetes)':
message = ["Lakukan Kontrol Kadar Gula Darah Secara Berkala"]
general_recommendation = ["Cara mengontrol kadar gula darah\n",
"1. Konsumsi makanan yang tepat: Menurut studi dalam jurnal Education and Health Promotion, melewatkan jadwal makan terlalu lama malah akan menyebabkan gula darah turun dan kemudian melonjak cepat.\n",
"2. Mengontrol porsi makan: Diabetesi dengan berat badan normal juga sebaiknya menjaga porsi makannya sehingga tidak berujung obesitas.\n",
"3. Aktif bergerak dan olahraga teratur: Olahraga dapat membantu sel-sel di otot Anda mengambil lebih banyak glukosa dan mengubahnya menjadi energi, sehingga mampu menurunkan gula darah. Hindari gaya hidup sedentari (bermalas-malasan) dan minim gerakan fisik atau membuang energi, seperti menonton TV, bermain game pada gawai, atau duduk terlalu lama di depan komputer.\n",
"4. Kelola stess dengan baik: Stres berlebihan juga dapat menyebabkan kadar gula darah meningkat akibat pelepasan kortisol alias hormon stres. Nah, agar stres tidak sampai membuat kadar gula darah melonjak, penting untuk Anda memahami cara mengendalikan stres dan mencoba berbagai hal yang dapat memperbaiki suasana hati, merilekskan tubuh, dan menenangkan pikiran.\n",
"5. Istirahat Cukup: Tidur yang cukup dapat menyeimbangkan hormon, menghindari stres, dan membuat Anda mendapatkan cukup energi untuk beraktivitas dan berolahraga pada esok harinya.Dengan demikian, kadar gula darah pun dapat terkendali dengan baik.\n",
"6. Rutin mengecek gula darah: Dengan terus memantau perubahan kadar gula darah, Anda akan lebih mudah untuk menentukan apakah harus melakukan penyesuaian pola makan atau konsumsi obat."
]
recommendation = {
"message": message,
"general_recommendation": general_recommendation
}
elif label_name == 'DR Ringan (Mild)':
message = ["Lakukan Kontrol Kadar Gula Darah Secara Berkala"]
general_recommendation = ["Cara mengontrol kadar gula darah\n",
"1. Konsumsi makanan yang tepat: Menurut studi dalam jurnal Education and Health Promotion, melewatkan jadwal makan terlalu lama malah akan menyebabkan gula darah turun dan kemudian melonjak cepat.\n",
"2. Mengontrol porsi makan: Diabetesi dengan berat badan normal juga sebaiknya menjaga porsi makannya sehingga tidak berujung obesitas.\n",
"3. Aktif bergerak dan olahraga teratur: Olahraga dapat membantu sel-sel di otot Anda mengambil lebih banyak glukosa dan mengubahnya menjadi energi, sehingga mampu menurunkan gula darah. Hindari gaya hidup sedentari (bermalas-malasan) dan minim gerakan fisik atau membuang energi, seperti menonton TV, bermain game pada gawai, atau duduk terlalu lama di depan komputer.\n",
"4. Kelola stess dengan baik: Stres berlebihan juga dapat menyebabkan kadar gula darah meningkat akibat pelepasan kortisol alias hormon stres. Nah, agar stres tidak sampai membuat kadar gula darah melonjak, penting untuk Anda memahami cara mengendalikan stres dan mencoba berbagai hal yang dapat memperbaiki suasana hati, merilekskan tubuh, dan menenangkan pikiran.\n",
"5. Istirahat Cukup: Tidur yang cukup dapat menyeimbangkan hormon, menghindari stres, dan membuat Anda mendapatkan cukup energi untuk beraktivitas dan berolahraga pada esok harinya.Dengan demikian, kadar gula darah pun dapat terkendali dengan baik.\n",
"6. Rutin mengecek gula darah: Dengan terus memantau perubahan kadar gula darah, Anda akan lebih mudah untuk menentukan apakah harus melakukan penyesuaian pola makan atau konsumsi obat."
]
recommendation = {
"message": message,
"general_recommendation": general_recommendation
}
elif label_name == 'DR Sedang (Moderate)':
message = ["Lakukan konsultasi ke Dokter"]
general_recommendation = ["Hal-hal yang mungkin dilakukan setelah melakukan konsultasi bersama Dokter\n",
"1. Injeksi mata: Dokter akan menyuntikan steroid pada mata untuk menghentikan peradangan dan mencegah pembentukan pembuluh darah baru. Suntikan anti-VEGF juga mungkin disarankan, yang dapat mengurangi pembengkakan di makula dan meningkatkan penglihatan.\n",
"2. Operasi Leser: Operasi laser yang disebut fotokoagulasi mengurangi pembengkakan di retina dan menghilangkan pembuluh darah abnormal.\n",
"3. Vitrektomi: Jika Anda menderita retinopati diabetik stadium lanjut, Anda mungkin memerlukan vitrektomi. Operasi mata ini mengatasi masalah pada retina dan vitreous, zat seperti jeli di tengah mata. Operasi tersebut dapat menghilangkan darah atau cairan, jaringan parut, dan sebagian gel vitreous sehingga sinar cahaya dapat terfokus dengan baik pada retina.\n"]
recommendation = {"message": message,
"general_recommendation": general_recommendation}
elif label_name == 'DR Parah (Severe)':
message = ["Lakukan konsultasi ke Dokter"]
general_recommendation = ["Hal-hal yang mungkin dilakukan setelah melakukan konsultasi bersama Dokter\n",
"1. Injeksi mata: Dokter akan menyuntikan steroid pada mata untuk menghentikan peradangan dan mencegah pembentukan pembuluh darah baru. Suntikan anti-VEGF juga mungkin disarankan, yang dapat mengurangi pembengkakan di makula dan meningkatkan penglihatan.\n",
"2. Operasi Leser: Operasi laser yang disebut fotokoagulasi mengurangi pembengkakan di retina dan menghilangkan pembuluh darah abnormal.\n",
"3. Vitrektomi: Jika Anda menderita retinopati diabetik stadium lanjut, Anda mungkin memerlukan vitrektomi. Operasi mata ini mengatasi masalah pada retina dan vitreous, zat seperti jeli di tengah mata. Operasi tersebut dapat menghilangkan darah atau cairan, jaringan parut, dan sebagian gel vitreous sehingga sinar cahaya dapat terfokus dengan baik pada retina.\n"]
recommendation = {"message": message,
"general_recommendation": general_recommendation}
elif label_name == 'DR Proliferatif (Proliferative)':
message = ["Lakukan konsultasi ke Dokter"]
general_recommendation = ["Hal-hal yang mungkin dilakukan setelah melakukan konsultasi bersama Dokter\n",
"1. Injeksi mata: Dokter akan menyuntikan steroid pada mata untuk menghentikan peradangan dan mencegah pembentukan pembuluh darah baru. Suntikan anti-VEGF juga mungkin disarankan, yang dapat mengurangi pembengkakan di makula dan meningkatkan penglihatan.\n",
"2. Operasi Leser: Operasi laser yang disebut fotokoagulasi mengurangi pembengkakan di retina dan menghilangkan pembuluh darah abnormal.\n",
"3. Vitrektomi: Jika Anda menderita retinopati diabetik stadium lanjut, Anda mungkin memerlukan vitrektomi. Operasi mata ini mengatasi masalah pada retina dan vitreous, zat seperti jeli di tengah mata. Operasi tersebut dapat menghilangkan darah atau cairan, jaringan parut, dan sebagian gel vitreous sehingga sinar cahaya dapat terfokus dengan baik pada retina.\n"]
recommendation = {"message": message,
"general_recommendation": general_recommendation}

data = {"prediction": prediction, "label": label_name,
"kumilcintabh": recommendation}
return jsonify(data)
except Exception as e:
return jsonify({"error": str(e)})
return "OK"


if __name__ == "__main__":
app.run(debug=True)
Binary file added requirements.txt
Binary file not shown.

0 comments on commit d393813

Please sign in to comment.