Developing Web Apps for data models has always been a hectic task for non-web developers. For developing Web API we need to make the front end as well as back end platform. That is not an easy task. But then python comes to the rescue with its very fascinating frameworks like Streamlit, Flassger, FastAPI. These frameworks help us to build web APIs very elegantly, without worrying about the Front end as these frameworks already provide default UIs.
Streamlit is one of the frameworks in Python which is used for building Web APIs very easily. With streamlit, we need not worry about front end tasks as it handles those itself without writing a line of code. We can Rapidly build all the apps we need with Streamlit. For more on Streamlit just visit here.
After creating a new environment just type the following command and you are good to go
pip install streamlit
You may need to download other libraries for different data modeling tasks. Hence I am leaving that up to you. Now let us start our project.
After installing just run the below command to check the installation:
streamlit hello
If you see the below screen after browsing the server then you are good to go.
The original problem was given by Kaggle to classify the tweets as disastrous or not based on the tweet’s sentiment. Then I build an end to end project out of it. In this blog, we only gonna create Web API using Streamlit. for the whole project you can refer here.
After installing streamlit let’s start developing our Web API. At first, we need to install and import the required libraries.
import streamlit as st ## streamlit import pandas as pd ## for data manipulation import pickle ## For model loading import spacy ## For NLP tasks import time from PIL import Image ## For image from io import StringIO ## for text input and output from the web app
After importing libraries we first need to load the trained model which we have saved as a pickle file.
def load_model(): #declare global variables global nlp global textcat nlp = spacy.load(model_path) ## will load the model from the model_path textcat = nlp.get_pipe(model_file) ## will load the model file
Now after loading the model from our system we will use it to make a prediction on the tweet for classification. The model will first vectorize the text and then will make the prediction.
def predict(tweet): print("news = ", tweet) ## tweet news = [tweet] txt_docs = list(nlp.pipe(tweet)) scores, _ = textcat.predict(txt_docs) print(scores) predicted_classes = scores.argmax(axis=1) print(predicted_classes) result = ['real' if lbl == 1 else 'fake' for lbl in predicted_classes] print(result) return(result)
The predict function will take the tweet as input and then first will vectorize the tweet and then will classify it using our model. We have two categories here real or fake. If the prediction is 1 it is a real tweet means it is affirmative about disaster otherwise it’s a fake.
def run(): st.sidebar.info('You can either enter the news item online in the textbox or upload a txt file') st.set_option('deprecation.showfileUploaderEncoding', False) add_selectbox = st.sidebar.selectbox("How would you like to predict?", ("Online", "Txt file")) st.title("Predicting fake tweet") st.header('This app is created to predict if a tweet is real or fake') if add_selectbox == "Online": text1 = st.text_area('Enter text') output = "" if st.button("Predict"): output = predict(text1) output = str(output[0]) # since its a list, get the 1st item st.success(f"The news item is {output}") st.balloons() elif add_selectbox == "Txt file": output = "" file_buffer = st.file_uploader("Upload text file for new item", type=["txt"]) if st.button("Predict"): text_news = file_buffer.read() # in the latest stream-lit version ie. 68, we need to explicitly convert bytes to text st_version = st.__version__ # eg 0.67.0 versions = st_version.split('.') if int(versions[1]) > 67: text_news = text_news.decode('utf-8') print(text_news) output = predict(text_news) output = str(output[0]) st.success(f"The news item is {output}") st.balloons()
The above run function will take the input from the user via our app as a text or text file and after pressing the predict button it will give the output.
if __name__ == "__main__": load_model() run()
if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported. it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.
Now we can run our app in our system as localhost using:
streamlit run app.py
After running this app we would see the further web page where you can give text input and get the prediction after clicking on the predict button.
That is it for this small blog. You can deploy this app on any cloud service as well. For that Heroku would be the easiest and cheapest choice. If you have any queries, feedback, or suggestions feel free to comment below or reach me here.
https://www.streamlit.io/
Image Sources: localhost
Gif:https://www.google.com/imgres?imgurl=https%3A%2F%2Fmedia1.tenor.com%2Fimages%2F2d438ca55094b4b591a5b8432457aaa9
I am a freelance Data Science professional with immense passion to solve Data driven problem. I have almost one year of industry experience. I love to write, explore new use cases of data science, and travel. I am open to a collaboration to learn, teach and grow more.
Build a Travel Assistant Chatbot with HuggingFa...
Machine Learning Model Deployment using Streamlit
Developing Data Web App Using Streamlit
Build Web App instantly for Machine Learning us...
Streamlit Tutorial: Building Web Apps with Code...
Deploying machine learning models using Streaml...
Building a Real-time Short News App using Huggi...
Streamlit for ML Web Applications: CustomerR...
Streamlit • A faster way to build and share d...
Building a Live Twitter Sentiment Analyzer with...
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
It is needed for personalizing the website.
Expiry: Session
Type: HTTP
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Expiry: Session
Type: HTTPS
Preserves the login/logout state of users across the whole site.
Expiry: Session
Type: HTTPS
Preserves users' states across page requests.
Expiry: Session
Type: HTTPS
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
Expiry: 365 days
Type: HTTP
Used by Microsoft Clarity, to store and track visits across websites.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
Expiry: 1 Year
Type: HTTP
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
Expiry: 1 Day
Type: HTTP
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Years
Type: HTTP
Use to measure the use of the website for internal analytics
Expiry: 1 Years
Type: HTTP
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
Expiry: 1 Year
Type: HTTP
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
Expiry: 2 Months
Type: HTTP
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics, to store and count pageviews.
Expiry: 399 Days
Type: HTTP
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
Expiry: 1 Day
Type: HTTP
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
Expiry: Session
Type: PIXEL
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
Expiry: 6 Months
Type: HTTP
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
Expiry: 2 Years
Type: HTTP
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
Expiry: 1 Year
Type: HTTP
this is used to send push notification using webengage.
Expiry: 1 Year
Type: HTTP
used by webenage to track auth of webenagage.
Expiry: Session
Type: HTTP
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
Expiry: 1 Day
Type: HTTP
Use to maintain an anonymous user session by the server.
Expiry: 1 Year
Type: HTTP
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
Expiry: 1 Year
Type: HTTP
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
Expiry: 6 Months
Type: HTTP
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
Expiry: 6 Months
Type: HTTP
allow for the Linkedin follow feature.
Expiry: 1 Year
Type: HTTP
often used to identify you, including your name, interests, and previous activity.
Expiry: 2 Months
Type: HTTP
Tracks the time that the previous page took to load
Expiry: Session
Type: HTTP
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
Expiry: Session
Type: HTTP
Tracks percent of page viewed
Expiry: Session
Type: HTTP
Indicates the start of a session for Adobe Experience Cloud
Expiry: Session
Type: HTTP
Provides page name value (URL) for use by Adobe Analytics
Expiry: Session
Type: HTTP
Used to retain and fetch time since last visit in Adobe Analytics
Expiry: 6 Months
Type: HTTP
Remembers a user's display preference/theme setting
Expiry: 6 Months
Type: HTTP
Remembers which users have updated their display / theme preferences
Expiry: 6 Months
Type: HTTP
Used by Google Adsense, to store and track conversions.
Expiry: 3 Months
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
Expiry: 2 Years
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 6 Hours
Type: HTTP
These cookies are used for the purpose of targeted advertising.
Expiry: 1 Month
Type: HTTP
These cookies are used to gather website statistics, and track conversion rates.
Expiry: 1 Month
Type: HTTP
Aggregate analysis of website visitors
Expiry: 6 Months
Type: HTTP
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
Expiry: 4 Months
Type: HTTP
Contains a unique browser and user ID, used for targeted advertising.
Expiry: 2 Months
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 1 Year
Type: HTTP
Used by LinkedIn for tracking the use of embedded services.
Expiry: 1 Day
Type: HTTP
Used by LinkedIn to track the use of embedded services.
Expiry: 6 Months
Type: HTTP
Use these cookies to assign a unique ID when users visit a website.
Expiry: 6 Months
Type: HTTP
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
Expiry: 6 Months
Type: HTTP
Used to make a probabilistic match of a user's identity outside the Designated Countries
Expiry: 90 Days
Type: HTTP
Used to collect information for analytics purposes.
Expiry: 1 year
Type: HTTP
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
Expiry: 1 Day
Type: HTTP
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.
Edit
Resend OTP
Resend OTP in 45s
Thank's, It's a great thing that this article suggested the importance of Streamlit Web API for NLP.
Really like these new tips, which I haven't heard of before, like the Streamlit Web API for NLP. Can’t wait to implement some of these as soon as possible.
This is amazing, I will try this for my project, Thanx