<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jonathan Readshaw on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Readshaw on Medium]]></description>
        <link>https://medium.com/@readshawjonathan?source=rss-ccfd35fa18d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tD0-6S_qOpgE23MnONC7Iw.jpeg</url>
            <title>Stories by Jonathan Readshaw on Medium</title>
            <link>https://medium.com/@readshawjonathan?source=rss-ccfd35fa18d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:45:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@readshawjonathan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Serverless Model Hosting with Docker, AWS Lambda and API Gateway]]></title>
            <link>https://medium.com/data-science/serverless-model-hosting-with-docker-aws-lambda-and-api-gateway-2d79382ecb45?source=rss-ccfd35fa18d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d79382ecb45</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Jonathan Readshaw]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 18:05:54 GMT</pubDate>
            <atom:updated>2021-06-20T22:31:47.093Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make the most of Docker support in Lambda to host your models without the need for dedicated servers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lovxQO12mwBmO3mhK2QeIg.jpeg" /><figcaption>Image by Markus Spiske on Unsplash</figcaption></figure><p>Previously AWS Lambda deployment packages were limited to a maximum unzipped size of 250MB including requirements. This proved to be an obstacle when attempting to host Machine Learning models using the service, as common ML libraries and complex models led to deployment packages far larger than the 250MB limit.</p><p>However in December 2020 AWS <a href="https://aws.amazon.com/blogs/aws/new-for-aws-lambda-container-image-support/">announced </a>support for packaging and deployment of Lambda functions as Docker Images. Critically in the context of Machine Learning, these images can be up to 10GB in size. This means that large dependencies (e.g. Tensorflow) and medium-sized models can be included in the image and hence model predictions can be served using Lambda.</p><p>In this article we’ll work through an example build and deployment for model hosting on Lambda. All of the relevant code used can be found <a href="https://github.com/jonathanreadshaw/ml-deploy-sam">here</a>.</p><p><strong>Architecture Overview</strong></p><p>The solution can be broken down into three components:</p><ol><li><strong>Docker Image</strong>: The docker image contains our dependencies, trained model pipeline and function code. AWS provides189097 a base image for various runtimes that can be built upon to ensure compatibility with the service.</li><li><strong>Lambda Function</strong>: Serverless resource that runs the function code in the Docker image based on incoming events/requests.</li><li><strong>API Gateway Endpoint</strong>: Used as a trigger for the Lambda function and the entry point for client requests. When prediction requests are received at the endpoint, the Lambda function is triggered with the request body included in the event sent to the function. The value(s) returned by the function are then returned to the client as a response.</li></ol><p><strong>Model</strong></p><p>In this example our model will be a simple KNN implementation trained on the Iris classification dataset. Training won’t be covered in this post however the outcome is a scikit-learn Pipeline object consisting of the following objects:</p><p>1. StandardScaler: Standardises inputs based on the mean and standard deviation of the training samples.</p><p>2. KNeighborsClassifier: The actual pretrained model. Trained with K = 5.</p><p>The pipeline is saved using scikit-learn’s Joblib implementation to ‘<em>model_pipeline.joblib</em>’.</p><p><strong>Function Code</strong></p><p>Let’s start by considering the function code that will be used by Lambda to handle prediction request events (predict\app.py).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/098b4c4be474779973f1369341b6425d/href">https://medium.com/media/098b4c4be474779973f1369341b6425d/href</a></iframe><p><em>Lambda_handler</em> has the required arguments for functions used by lambda. The pipeline object is loaded outside of the handler in order to avoid loading this on every invocation. Lambda will keep containers alive for a period until there are no events, so loading the model once on creation means it can be reused whilst the container is kept alive by Lambda.</p><p>The handler function itself is pretty simple; the required inputs are extracted from the event body and used to generate a prediction. The prediction is the returned as part of the JSON response. The response from the function will be returned to the client by API Gateway. A few checks are made to ensure the inputs are as expected, and any prediction errors are caught and logged.</p><p><strong>Docker Image</strong></p><p>The Dockerfile is structured as follows:</p><p>1. Pull AWS’ base Python 3.6 image</p><p>2. Copy required files from local directory to the root of the image</p><p>3. Install requirements</p><p>4. Run handler function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/661bac5e329f5d45dd77de3c06350e18/href">https://medium.com/media/661bac5e329f5d45dd77de3c06350e18/href</a></iframe><p><strong>Deployment</strong></p><p>To manage deployment and AWS resources we will use AWS Serverless Application Manager (SAM) CLI<em>. </em>Instructions to install SAM and its dependencies can be found <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">here</a>.</p><p>To use SAM for build and deployment a template file must be configured. This is used to specify the required AWS resources and associated configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8ba9ad443e51cb72a7ce6c20f18101/href">https://medium.com/media/4f8ba9ad443e51cb72a7ce6c20f18101/href</a></iframe><p>For this project the SAM template contains the following:</p><ul><li>Miscellaneous info such as stack name, and global configuration for Lambda timeout.</li><li><em>MLPredictionFunction</em> Resource: This is the Lambda function we want to deploy. This section contains the bulk of the required config:</li><li>Properties: here we specific that the function will be defined using a Docker Image (<em>PackageType: Image</em>) and that the function will be triggered via API Gateway (<em>Type: API</em>). The API path route name and type are also defined here.</li><li>Metadata contains the tag that will be used for built images and the location/name of the Dockerfile used for building the image.</li><li>Outputs lists all of the required resources that will be created by SAM. In this case it is the API Gateway endpoint, Lambda function and associated IAM role that SAM needs.</li></ul><p>Running the command below builds the application image locally using the defined SAM template:</p><pre>!sam build</pre><p>If successful the function can be invoked locally with a sample event using the following command (see repo for example event):</p><pre>!sam local invoke -e events/event.json</pre><p>Once the function has been tested locally the image needs to be pushed to AWS ECR. First create a new repository:</p><pre>!aws ecr create-repository --repository-name ml-deploy-sam</pre><p>You will need to log in to ECR’s managed Docker service before the image can be pushed:</p><pre>!aws ecr get-login-password --region &lt;region&gt; | docker login --username AWS \ --password-stdin &lt;account id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com</pre><p>Now you can deploy your application using:</p><pre>!sam deploy -g</pre><p>This will run the deployment in “guided” mode, where you will need to confirm the name of the application, AWS region and the image repository created earlier. Accepting the default options for the remaining settings should be fine in most instances.</p><p>The deployment process will then begin and AWS resources will be provisioned. Once complete, each resource will be displayed in the console.</p><h4>Considerations</h4><ul><li><strong>Image updates</strong>: to deploy an updated model or function code, you can simply rebuild the image locally and re-run the deploy command. SAM will detect which aspects of the application have changed and update the relevant resources accordingly.</li><li><strong>Cold Start: </strong>Each time Lambda spins up a container using our function code the model will be loaded before processing can start. This leads to a cold start scenario where the first request will be significantly slower than those that follow. One method to combat this is to periodically trigger the function using CloudWatch such that a container is always ready with the model loaded.</li><li><strong>Multiple Functions: </strong>It is possible to deploy multiple Lambda functions to be served by a single API. This could be useful if you have multiple models to serve, or if you want to have a separate pre-processing/validation endpoint. To configure this you can simply include the additional functions in the SAM template resources.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d79382ecb45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/serverless-model-hosting-with-docker-aws-lambda-and-api-gateway-2d79382ecb45">Serverless Model Hosting with Docker, AWS Lambda and API Gateway</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying ML Models in Production with FastAPI and Celery]]></title>
            <link>https://medium.com/data-science/deploying-ml-models-in-production-with-fastapi-and-celery-7063e539a5db?source=rss-ccfd35fa18d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7063e539a5db</guid>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sklearn]]></category>
            <dc:creator><![CDATA[Jonathan Readshaw]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 18:41:27 GMT</pubDate>
            <atom:updated>2021-02-11T15:33:35.569Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serving ML Models in Production with FastAPI and Celery</h3><h4>Full working example to serve your model using asynchronous Celery tasks and FastAPI.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SlnPD3csrD3ANeu-EskF9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa">Arnold Francisca</a> on <a href="https://unsplash.com/">UnSplash</a></figcaption></figure><h4>Overview</h4><p>There is an abundance of material online related to building and training all kinds of machine learning models. However once a high performance model has been trained there is significantly less material for how to put it into production.</p><p>This post walks through a working example for serving a ML model using Celery and FastAPI. All code can be found in the repository <a href="https://github.com/jonathanreadshaw/ServingMLFastCelery">here</a>.</p><p><strong><em>We won’t specifically discuss the ML model used for this example however it was trained using example Bank customer churn data (</em></strong><a href="https://www.kaggle.com/sakshigoyal7/credit-card-customers">https://www.kaggle.com/sakshigoyal7/credit-card-customers</a><strong><em>). There is a notebook in the repository outlining the training for a LightGBM model including hyperparameter optimization and performance evaluation.</em></strong></p><h4>Potential Options</h4><p>Below is a summary of potential approaches for deploying your trained models to production:</p><ol><li>Load model directly in application: this option involves having the pretrained model directly in the main application code. For small models this might be feasible however large models may introduce memory issues. This option also introduces a direct dependency on the model within the main application (coupled).</li><li>Offline batch prediction: Use cases that do not require near real-time predictions can make use of this option. The model can be used the make predictions for a batch of data in a process that runs at defined intervals (e.g. overnight). The predictions can then be utilized by the application once the batch job is complete. Resource for prediction is only required when the batch process runs which can be beneficial.</li><li>API: The third option is to deploy the model as its own microservice and communicate with it via an API. This decouples the application from the model and allows it to be utilized from multiple other services. The ML service can serve requests in one of the two ways described below.</li></ol><p>Synchronous: the client requests a prediction and must wait for the model service to return a prediction. This is suitable for small models that require a small number of computations, or where the client cannot continue other processing steps without a prediction.</p><p>Asynchronous: instead of directly returning a prediction the model service will return a unique identifier for a task. Whilst the prediction task is being completed by the model service the client is free to continue other processing. The result can then be fetched via a results endpoint using the unique task id.</p><h4>Process Flow</h4><p>The steps below describe the actions taken to handle a prediction request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnCyO6vI6WqpvoGyRleT5g.png" /><figcaption>Example Architecture (Image by Author using logos from <a href="https://commons.wikimedia.org/wiki/Main_Page">Wikimedia Commons</a>)</figcaption></figure><ol><li>Client sends a POST request to the FastAPI prediction endpoint, with the relevant feature information contained in the request body (JSON).</li><li>The request body is validated by FastAPI against a defined model (i.e. checks if the expected features have been provided). If the validation is successful then a Celery prediction task is created and passed to the configured broker (e.g. RabbitMQ).</li><li>The unique id is returned to the client if a task is created successfully.</li><li>The prediction task is delivered to an available worker by the broker. Once delivered the worker generates a prediction using the pretrained ML model.</li><li>Once a prediction has been generated the result is stored using the Celery backend (e.g. Redis).</li><li>At any point after step 3 the client can begin to poll the FastAPI results endpoint using the unique task id. Once the prediction is ready it will be returned to the client.</li></ol><p>Now let’s look at some example code that implements this architecture.</p><h4>Project Structure</h4><p>The project structure is as follows:</p><pre>serving_ml<br>│   app.py<br>│   models.py<br>│   README.md<br>│   requirements.txt<br>│   test_client.py<br>│<br>├───celery_task_app<br>│   │   tasks.py<br>│   │   worker.py<br>│   │   __init__.py<br>│   │<br>│   ├───ml<br>│   │   │   model.py<br>│   │   │   __init__.py</pre><ul><li><em>app.py</em>: FastAPI application including route definitions.</li><li><em>models.py: </em>Pydantic model definitions that are used for the API validation and response structure.</li><li><em>test_client.py</em>: Script used for testing the set-up. We’ll cover this in more detail later.</li><li><em>celery_task_app\tasks.py: </em>Contains Celery task definition, specifically the prediction task in our case<em>.</em></li><li><em>celery_task_app\worker.py: </em>Defines the celery app instance and associated config.</li><li><em>celery_task_app\ml\model.py: </em>Machine learning model wrapper class used to load pretrained model and serve predictions.</li></ul><h4>ML Model</h4><p>First let’s look at how we are going to load the pretrained model and calculate predictions. The code below defines a wrapper class for a pretrained model that loads from file on creation and calculates class probability or membership in its predict method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6815d42a9d88533f1ba8002d3897a26f/href">https://medium.com/media/6815d42a9d88533f1ba8002d3897a26f/href</a></iframe><p>This implementation can be re-used for a variety of ML models as long as the model has predict and predict_proba methods (i.e. Scikit-Learn or Keras implementations).</p><p>In our example the saved model is in fact a Scikit-Learn pipeline object the contains a preprocessing step, so we don’t need to worry about having additonal preprocessing code before prediction. We can simply create a DataFrame with the feature data and call the pipeline predict method.</p><h4>Celery</h4><p>Celery is a simple task queue implementation that can used to distribute tasks across threads and/or machines. The implementation requires a broker and optionally a backend:</p><ul><li>Broker: This is used to deliver messages between clients and workers. To initiate a task the client adds a message to the queue, the broker then delivers that message to a worker. RabbitMQ is often used as the broker and is the default used by Celery.</li><li>Backend: This is optional and its only function is to store task results to be retrieved at a later date. Redis is commonly used as the backend.</li></ul><p>First let’s look at how we define our Celery app instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49671a9c1d9640f03c55b29caaec19e6/href">https://medium.com/media/49671a9c1d9640f03c55b29caaec19e6/href</a></iframe><p>This app definition is very simple however there are a wide range of additional config options that can be defined (e.g. timezone, serialization).</p><p>The <em>include </em>argument is used to specify modules where tasks are defined for the Celery app. In this case we define a single task in <em>tasks.py:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b27906765db31d9bc276e360e2e4d644/href">https://medium.com/media/b27906765db31d9bc276e360e2e4d644/href</a></iframe><p>Our task implementation is slightly more complex than usual. Most simple tasks can be defined using the task decorator which overrides the run method of Celery’s base task class. However if we were to use this approach it would lead to a model class being defined and hence loaded from disk for each task processed.</p><p>By extending the Celery Task object we can override the default behavior such that the ML model is loaded only once when the task is first called. Subsequent calls can then use the same loaded model.</p><p>Although this is better than loading the model each time a task is run, there are still some considerations:</p><ol><li>There will be a PredictTask object for each worker process. Therefore if a worker has four threads then the model will be loaded four times (each is then stored in memory as well…).</li><li>This introduces a cold start scenario for each worker process, where the first task will be slow as the model needs to be loaded. There are different approaches that can be used to tackle this, and the fact that task are asynchronous makes this less of an issue.</li></ol><p>We can then use the usual decorator approach and specify <em>base=PredictTask </em>so Celery knows to use our custom Task class instead of the default. The <em>bind</em> parameter allows us to access the model attribute using <em>self </em>(as if we were defining the run method directly in the class).</p><h4>FastAPI</h4><p>Finally we can create an API that will be used to generate tasks and fetch results from the backend based on client requests.</p><p>Two endpoints are required:</p><ul><li>…/churn/predict (POST): Client sends JSON containing required features. Unique task id returned.</li><li>…/churn/result/&lt;task_id&gt;: (GET): Checks is task result is available in the backend, and returns the prediction if it is.</li></ul><p>We implement these endpoints as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7454bfdee61274db030e09d358fd536f/href">https://medium.com/media/7454bfdee61274db030e09d358fd536f/href</a></iframe><p>A specific response is implemented within the results route to handle cases where the task result is not ready. This can be used by the client to poll the result endpoint until the result is ready (we’ll use this for testing…).</p><h4>Testing</h4><p>To check everything is working as expected we can create a separate Python script that imitates a prediction request. To do so we make use of Python’s <em>requests</em> package.</p><p>Once both the broker and backend servers are running, we can start the API using uvicorn:</p><pre>uvicorn app:app</pre><p>Next start a worker process:</p><pre>celery -A celery_task_app.worker worker -l info</pre><p>Running <em>test_client.py</em> will do the following (see repo for code):</p><ol><li>An example feature JSON is sent to the predict endpoint. The features are hardcoded in a dictionary within the script.</li><li>If successful, the task id returned will be used to poll the results endpoint. The dummy client will wait 5 seconds between each request and will make a maximum of 5 attempts.</li><li>If the task is successful, the result (in this case the probability of membership to class 1) will be printed.</li></ol><pre>(venv) python.exe test_client.py<br>0.011178750583075114</pre><h4>Next Steps</h4><p>The solution discussed above is simply a working example and should be adapted with more advanced Celery and FastAPI configuration for full production use.</p><p>Another possibility would be to dockerize the entire solution such that it can be deployed easily on cloud infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7063e539a5db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploying-ml-models-in-production-with-fastapi-and-celery-7063e539a5db">Deploying ML Models in Production with FastAPI and Celery</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Live Tweet Dashboard using Tweepy, MySQL and Streamlit]]></title>
            <link>https://medium.com/data-science/tracking-the-race-for-10-downing-street-live-tweet-dashboard-using-tweepy-mysql-and-streamlit-6084e88b4dd8?source=rss-ccfd35fa18d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6084e88b4dd8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tweepy]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Jonathan Readshaw]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 18:42:12 GMT</pubDate>
            <atom:updated>2021-02-12T20:52:58.825Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keep up-to-date with public sentiment using live tweets and an easy-to-build Streamlit web app.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQlq74tfe5z3uS5-DIc-FA.png" /><figcaption>Streamlit makes it easy to turn Data Science projects into web apps and dashboards (Image by Author)</figcaption></figure><p>Twitter can be used as a data source for various data science projects, including Geo-spatial analysis (where are users tweeting about certain subjects?) and sentiment analysis (how do users feel about certain subjects?).</p><p>I decided to build a dashboard that combines the two questions using the example of UK political leaders; Boris Johnson and Keir Starmer. However it’s possible to use any combination of keywords to analyse political figures, companies etc.</p><p>We can break down what needs to be done into three distinct areas:</p><ol><li>Database set-up: This can be done directly in the RDBMS of your choice, however we choose to use SQLAlchemy in this example.</li><li>Tweepy: Credentials are required to interact with the Tweepy API. Once these have been obtained we can set up a stream with keyword filters.</li><li>Streamlit: Once we have our data stream working we’ll need to set up our web app using Streamlit. This is surprisingly simple and can be done within a single python file!</li></ol><p>This article will work through each point above and show how they interact.</p><p>All code is available on GitHub: <a href="https://github.com/jonathanreadshaw/streamlit-twitter-stream">https://github.com/jonathanreadshaw/streamlit-twitter-stream</a></p><h4>Database Set-up</h4><p>We need a MySQL server up and a running before we can create our database and tables. This can either be done locally or on a hosted server, however I would recommend setting this up locally first. Your app can then be moved to hosted infrastructure at a later date.</p><p>First let’s create our database through the following SQL statement:</p><pre>CREATE DATABASE twitter_sqlalc;</pre><p>Creation of the table and database transactions will be handled using SQLAlchemy. This is a Python library most commonly used as an Object Relational Mapper (ORM), handling the communication between our Python code and the database. SQLAlchemy allows database tables to be represented as Python classes and the use of functions to automatically execute SQL statements.</p><p>The class below represents the table we will use to store tweets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1b2aea9a2b1e2052d9d9249982aa12e/href">https://medium.com/media/b1b2aea9a2b1e2052d9d9249982aa12e/href</a></iframe><p>In a separate file database.py we define various variables that are required to perform our database operations using SQLAlchemy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c730bb0d557a269c0a819fa1a63678f1/href">https://medium.com/media/c730bb0d557a269c0a819fa1a63678f1/href</a></iframe><p>Details on engines, base and sessions can be found in the SQLAlchemy documentation. There are two key functions within this file:</p><ul><li><em>session_scope()</em>: this function uses the context managed decorator to provide a SQLAlchemy session object to perform transactions. The decorator allows for use within the with…as… syntax, and will commit or rollback depending on success, before closing the session.</li><li><em>init_db()</em>: this function will create the tables defined by our SQLAlchemy models if they don’t exist.</li></ul><h4>Tweepy Stream</h4><p>Tweepy is a Python library to access the Twitter API. You’ll need to set up a twitter application at <a href="http://dev.twitter.com/">dev.twitter.com</a> to attain a set of authentication keys to use with the API. Streaming with Tweepy comprises of three objects; <em>Stream, StreamListener, OAuthHandler. </em>The latter simply handles API authentication and requires the unique keys from the creation of your Twitter app.</p><p>The StreamListener class is used to define how each incoming tweet should be handled. There are two methods of the StreamListener class that we will overwrite in our child class TweetListener:</p><ul><li><em>on_status():</em> Called when a new tweet is present in the stream. Tweets are defined as Status objects in Tweepy and passed as an argument to this method.</li><li><em>on_error():</em> Called when there is an error in the streaming process. The associated HTML error code is passed as an argument.</li></ul><p>Our <em>on_error()</em> implementation can be kept simple. The code below will log a warning for all status codes except 420. This code is encountered when the stream has reached its limit, and therefore we need to close it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a76608c2e90022364e90bcfd36dbccd5/href">https://medium.com/media/a76608c2e90022364e90bcfd36dbccd5/href</a></iframe><p><em>on_status()</em> is more involved and will handle processing of individual tweets. First let us look at <em>StreamListener</em> class’ __init__:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b197badb64468191d5c4fde9ec22db7e/href">https://medium.com/media/b197badb64468191d5c4fde9ec22db7e/href</a></iframe><p>Apart from calling the base __init__ we define two additional attributes. Firstly keywords, which is simply a list of keywords that we use to filter the stream. Although the listener doesn’t directly handle filtering the stream, we will use these when storing tweets on our database. The second attribute is an instance of SentimentIntensityAnalyzer from vaderSentiment. This will be used to assign a sentiment score to each tweet. We could use a more complex model to perform the sentiment analysis (e.g. BERT) however VADER is perfect for demonstrative purposes, works well with Social Media texts and doesn’t require complex dependencies or a large amount of memory.</p><p>Let’s take a step-by-step look at our <em>on_status() </em>implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6913e751964da72d7e9ef191b542c2a0/href">https://medium.com/media/6913e751964da72d7e9ef191b542c2a0/href</a></iframe><ol><li>If the tweet is a retweet, stop processing to avoid storing duplicates.</li><li>We want to store the full text, so we need to handle truncated tweets by retrieving the full text.</li><li>If the tweet is geo-tagged, convert the coordinates to a string so it is easy to handle with SQLAlchemy.</li><li>Call the check_keyword() method. This simply checks the presence for each of our keywords in the tweet, and returns the keyword that matches.</li><li>Assign a sentiment score to the tweet. If this is zero we stop processing and don’t store it. This is to avoid storing lots of tweets with little sentimental value that would skew our daily/hourly metrics to be largely neutral.</li><li>Finally we create an instance of the Tweet SQLAlchemy model we defined earlier, and insert the row through our insert_tweet() method.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f2bd3798ba7a7a194705f1d36cb378/href">https://medium.com/media/a9f2bd3798ba7a7a194705f1d36cb378/href</a></iframe><p>All that is left to do is create an instance of Tweepy’s <em>Stream </em>class using our customer listener and auth classes. The code below shows how we’ll start the stream, including parsing the keywords as command line arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d446f5bfd10b18750b28cc77d89b6d/href">https://medium.com/media/83d446f5bfd10b18750b28cc77d89b6d/href</a></iframe><h4>Streamlit App</h4><p>Once our stream is up and running we need a way to view our data in real time. For this we’ll use streamlit which allows us to build a interactive web app using a single python script. There are great examples on the streamlit website and the documentation is easy to follow.</p><p>I won’t go through all the code for the app in this article as it can be viewed on GitHub. The app will display following information:</p><ol><li>Influential Tweets: Tweets from users with the largest number of followers.</li><li>Recent Tweets: The most recent tweets for the keywords in question.</li><li>Hourly/Daily volume by keyword</li><li>Hourly/Daily sentiment by keyword</li><li>Location of tweets</li></ol><p>These metrics/visualisations will allow users to keep track of trends in near real-time. We make use of the following streamlit features:</p><ul><li>Caching: this is a key feature of streamlit. We can cache computationally expensive operation simply using the @st.cache decorator. These can be configured to expire after a set time (e.g. for loading fresh data)</li><li>Widgets: streamlit makes it easy to add interactivity to your app with buttons, drop downs etc.</li></ul><p>Tweepy is easy to use and can be a powerful tool for tracking public sentiment towards key topics. Coupled with streamlit you can get an interactive web app up and running in an afternoon.</p><p>Additional work could include:</p><ul><li>Named Entity Recognition: what are users tweeting about in addition to our keywords (places, companies etc.)?</li><li>Incorporate additional data sources, such as a news API</li><li>Using the streamed tweets and sentiment as input to a downstream model e.g election predictions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6084e88b4dd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tracking-the-race-for-10-downing-street-live-tweet-dashboard-using-tweepy-mysql-and-streamlit-6084e88b4dd8">Building a Live Tweet Dashboard using Tweepy, MySQL and Streamlit</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>