ML Android App Development with Retrofit & Flask REST API.
Hello Readers,
As of this 2020, Machine learning is a benchmark for providing your application automated learning and experience learning with being programmed. This kind of technique is optimized well on unstructured data such as images, audio files, etc. or the problems with a large number of parameters such as predicting the winning sports team.
Machine Learning the subset of Artificial Intelligence that empowers software to learn, explore, and envisage outcomes automatically without human interference. Machine learning has been used in numerous fields, and it is now aggressively serving to mobile application development.
Motivation
Tools and framework like Tensorflow lite evolving continuously it has been easy for mobile developers to new and exciting features to their mobile apps. Powerful Machine leaning Mobile application can leverage great business models and accomplish complex tasks like Face detection or automatically creating captions for pictures, all in real-time and without Internet connectivity.
We have performed detailed research on how to develop an android application without using any frameworks like tf-lite. After a lot of exploration, we came across this wonderful REST API called Retrofit. The Java API i.e. Retrofit will able to send and get a response from Python API
Idea is to use Retrofit Java API with Flask-restplus. The Flask Restplus API is basically a Machine learning API that is deployed on Heruko Platform. The Integration between Java and Python API is the key point here which we are going to Implement in a further section of this post.
Contents
- Introduction to Retrofit & Flask -Restplus
- Building Machine Learning Models API with Flask Restplus
- Deploying Model API on Heroku.
- Android App Integration with REST API using Retrofit.
- Conclusion
Introduction to Retrofit API and Flask Restplus
The Retrofit API is basically a type-safe REST API client for Andriod and Java which aims to consume JSON or XML data which is parsed into Plain Old Java Objects. It becomes easy for Android developers to consume web services RESTFUL API. Created by Developer @ Square it also enables us to receive data types like XML, Jackson other than JSON.
Now let’s talk about REST terminologies in a brief
- REST API is the set of functions which can be used by programming practitioner in order to request and receive responses via HTTP protocols. In our scenario, Retrofit API will be REST API to send and receive a request from the Client.
- REST Client that is used on the client-side (Android) to make an HTTP request to REST API.
There are basically three classes for Retrofit API that we will use for on-device intelligence
- Interface with HTTP operations- Retrofit works by converting your HTTP requests into Java interfaces. Methods inside the interface represent one API call that has HTTP annotations to specify what type of request has been made along with the relative URL. Return of interface encapsulates call object with expected result type.
- Retrofit Class — It has the implementation of an interface that we have created above. The code will be inside this class We have to create an instance of Retrofit class and define various methods in that particular interface.
- At last, we need a class with POJO that will match each field of JSON response which got from querying an API. It will be class which includes setter and getter methods for fields declared in the JSON response object.
- Below are some of the converters which are supported by Retrofit type API.
- Gson
- SimpleXML
- Jackson
- Moshi
Flask Restplus plays a vital role in our Architecture. According to Documentation of Flask Restplus.
“Flask-RESTPlus is an extension for Flask that adds support for quickly building REST APIs. Flask-RESTPlus encourages best practices with minimal setup. If you are familiar with Flask, Flask-RESTPlus should be easy to pick up. It provides a coherent collection of decorators and tools to describe your API and expose its documentation properly (using Swagger).”
Building Machine learning Model API with Flask Restplus
Machine learning Model Development requires a pipeline that starts with Data collection, EDA and goes up to Model Deployment to the real world. In order to explain the logic behind the Retrofit and Flask, we have developed a Machine learning model that predicts the presence of Heart disease in patients.
Here are the Data Source and Notebook link for the Machine learning Model Pipeline.
After many iterations, Random forest classifier is used to predict Heart disease in patients. Model is persisted using pickle and deployed in Heruko using Flask Restplus services
For More Insights on Flask Restplus and its Application, Click on this awesome tutorial.
Deploying Model API on Heroku.
According to Wikipedia
“ Heroku is a cloud platform as a service (PaaS) supporting several programming languages. One of the first cloud platforms, Heroku has been in development since June 2007, when it supported only the Ruby programming language, but now supports Java, Node.js, Scala, Clojure, Python, PHP, and Go. For this reason, Heroku is said to be a polyglot platform as it has features for a developer to build, run and scale applications in a similar manner across most languages”.
Complete Walkthrough for Model Deployment for Heruko will be out of scope for this post, however, some points to be noted down while deploying Flask App on Heruko cloud platform
- At the initial stage, we need heruko CLI in order to deploy and manage our application. After Installation login into CLI using heruko login command. In case you need heruko credentials for successful login.
- The second approach will be deploying your app by linking your GitHub repository with your Heroku account.
- We need to create some files which are required by heruko for deploying our flask application.
- Requirements.txt Now you want to output all your dependent packages for that application needs in a file called requirements.txt.Run the following command in your command line
pip freeze > requirements.txt
2. The next step would be creating a Procfile. Procfile is a mechanism for declaring what commands are run by your application’s dynos on the Heroku platform. In the Procfile following command -
web gunicorn app:app
Here web is used by Heroku to start a web server for the application app:app denotes that module and application name.
- After the above said files are created we are ready to push our app to heruko servers Just do some git commands like commit, push Create a repository on GitHub add and commit your files in the local repository And push that on the GitHub master branch
- Before creating an app make sure your GitHub account is connected with Heroku Account then Create an app on Heroku. Open your Heroku app go to deploy option select the Deployment method as Github, Search your repository with a name and click connect
- Click the deploy branch option Now your app ready to deploy on Heroku wait for some time.
Android App Integration with Flask REST API using Retrofit.
Here we go this now the fun part Integration of Python API with java type-safe HTTP client API. We have already deployed Flask REST API on heruko for which Endpoint are
After Deployment of Flask API. Some Steps need to be followed in order to make our Flask API to interact with Java Client.
- Create an object for Retrofit Class- the First Step will be defining a Generic Method say getApiClient that will return a Retrofit object. Moreover, in this method, we mention BASE URL Endpoints that will be pointing to our Flask URL.
2. Create Interface with HTTP Operation- This Interface will act as a bridge in order to connect with REST Endpoints. It will return a response from the Flask Endpoint to POJO Class.
3. Defining POJO Class to handle the response- This Class basically captures the return variables from Flask Endpoint. In a flask, we have defined a key-value pair, those keys are declared in POJO class.
4. Encapsulating the above Steps in MainActivity.java-
- In MainAcitivity.java we create the object for interface i.e. ApiInterface
- Using this object we call the method declared in the Interface.
- Define the Callback Interface. It consists of two methods namely onResponse & onFailure.
- If the request from JAVA API is successful then onResponse Method will be called otherwise onFailure method will be called.
- onResponse method will assign the Response body to the POJO class. From POJO we can extract the Response using the getter method.
Conclusion
After a lot of research and exploration of Retrofit and Flask Python API, We concluded that we can send and receive a response from Python API which is hosted on a server to any JAVA or Android HTTP Client.
The POJO Response can be displayed as a Dialog box in the Android App. Indeed, Retrofit is a great HTTP client API for Android.
Please find the Source code as well as Restplus API implementation on my GitHub Repo below-
At Last My Sincere thanks to Sathick S for his valuable contribution to this Project. His Approach & Guidance really help us to crack within a short span of time.
References
- Retrofit Docs
- Flask Restplus Docs
- Flask APP Deploy on Heroku
- Awesome Explanation of Retrofit Library
- Another Great Explanation of Retrofit Library
- GitHub for Retrofit
- Machine learning on Android
If you like this post, please follow me. If you have noticed any mistakes in the way of thinking, formulas, animations or code, please let me know.
Cheers!