<?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 Anshul Sharma on Medium]]></title>
        <description><![CDATA[Stories by Anshul Sharma on Medium]]></description>
        <link>https://medium.com/@anshuls235?source=rss-baee49d6b712------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T2pqHe1DT8PkgDmdBLvYAg@2x.jpeg</url>
            <title>Stories by Anshul Sharma on Medium</title>
            <link>https://medium.com/@anshuls235?source=rss-baee49d6b712------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 13:21:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anshuls235/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[️ Tool-Calling with LangChain & Open-Source Models — Run It Locally, Seamlessly!]]></title>
            <link>https://anshuls235.medium.com/%EF%B8%8F-tool-calling-with-langchain-open-source-models-run-it-locally-seamlessly-8d31ff4c7a76?source=rss-baee49d6b712------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d31ff4c7a76</guid>
            <dc:creator><![CDATA[Anshul Sharma]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 12:42:14 GMT</pubDate>
            <atom:updated>2025-06-12T12:42:14.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>🛠️ Tool-Calling with LangChain &amp; Open-Source Models — Run It Locally, Seamlessly!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Te8fmFDgWGFBTwZQrsCmA.png" /><figcaption>Like an executive assistant coordinating with specialists through written notes, LLMs use function calling to delegate specific tasks — each tool responding with precision, while the model orchestrates the workflow without ever leaving its central prompt.</figcaption></figure><h3>TL;DR</h3><p>Tool-calling with LangChain works out-of-the-box with Hugging Face endpoints — but running models locally while supporting function-calling requires custom abstraction. This article shares a robust, model-agnostic wrapper (tested on LLaMA, Gemma, Qwen, and more) that allows effortless tool binding locally — even when system prompts aren’t supported (like in Gemma!). Works great in agentic workflows too.</p><h3>🤖 The Problem</h3><p>LangChain supports tool calling (a.k.a. function calling) cleanly when using inference endpoints from Hugging Face. Here’s how easy it looks:</p><pre>from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace<br><br>repo_id = &quot;Qwen/Qwen2.5-7B-Instruct&quot;<br>model = HuggingFaceEndpoint(repo_id=repo_id, temperature=0)<br>chat = ChatHuggingFace(llm=model)<br><br>from langchain.tools import tool<br><br>@tool<br>def multiply(a: int, b: int) -&gt; int:<br>    return a * b<br><br>chat_with_tools = chat.bind_tools([multiply])<br>chat_with_tools.invoke(&quot;What is 2 multiplied by 6&quot;)</pre><p>✅ Done! Works like magic. As long as the model supports tool calls, you’re good.</p><p>But what happens when you want <strong>data privacy</strong>, <strong>low latency</strong>, and <strong>zero cloud calls</strong>?</p><p>You’ll need to:</p><ul><li>Load open-source models locally</li><li>Inject tools effectively</li><li>Parse tool call outputs reliably</li></ul><p>… and that’s where it gets tricky.</p><h3>⚙️ The Solution — A Custom LocalChatModel Wrapper</h3><p>To bridge this gap, I created a LocalChatModel class that:</p><ol><li><strong>Wraps any open-source HF model</strong> (LLaMA, Gemma, Mistral, Qwen, etc.)</li><li><strong>Handles prompt formatting dynamically</strong>, even if system prompts aren’t supported (e.g., Gemma)</li><li><strong>Parses tool call formats robustly</strong> from AI responses</li><li><strong>Supports multiple formats</strong> like JSON blocks, raw function calls, etc.</li><li><strong>Allows </strong><strong>bind_tools()</strong>, just like official LangChain models</li></ol><p>This means you can write:</p><pre>local_model = create_local_chat_model(&quot;google/gemma-2-9b-it&quot;, ...)<br>chat_with_tools = local_model.bind_tools([multiply, get_weather, get_population])<br>chat_with_tools.invoke(&quot;What is 200,0000 x 10,560 and Delhi&#39;s population?&quot;)</pre><p>And get structured tool call output like:</p><pre>{<br>  &quot;tool_calls&quot;: [<br>    {&quot;name&quot;: &quot;multiply&quot;, &quot;arguments&quot;: {&quot;a&quot;: 2000000, &quot;b&quot;: 10560}},<br>    {&quot;name&quot;: &quot;get_population&quot;, &quot;arguments&quot;: {&quot;location&quot;: &quot;Delhi, India&quot;}}<br>  ]<br>}</pre><h3>🔍 Code Walkthrough (Key Parts Only)</h3><p>The full code is available in this <a href="https://colab.research.google.com/drive/1dWLPCm4xfN2U0EryS6XyVvCRalTJVhLp?usp=sharing">Colab notebook</a>, but let’s highlight important components:</p><h3>1. ToolCallParser</h3><p>This is where the magic of decoding tool invocations happens. It tries multiple strategies:</p><ul><li>json blocks ( ```json {&quot;tool_calls&quot;: [...]} )</li><li>Incomplete JSON blocks</li><li>Raw function calls like multiply(2, 6)</li><li>Patterns without markdown wrappers</li></ul><p>This is critical for local models that may not adhere strictly to OpenAI-style output.</p><h3>2. DynamicPromptBuilder</h3><p>Builds prompts dynamically using the tokenizer’s apply_chat_template. If system prompts aren&#39;t supported (like in Gemma), it <strong>injects tool instructions into the first user prompt</strong>.</p><h3>3. LocalChatModel</h3><p>A LangChain-compatible class that implements _generate, bind_tools, and uses the tokenizer’s native chat format. Model loading supports quantization, attention tweaks, and smart padding.</p><h3>💡 Why This Matters</h3><ul><li>✅ <strong>Model-Agnostic</strong>: Works with LLaMA, Gemma, Mistral, Qwen — anything with a chat_template</li><li>✅ <strong>No Need for System Prompt</strong>: Falls back gracefully for models like gemma</li><li>✅ <strong>Agent-Ready</strong>: Once tools are bound, you can use this in an agentic workflow</li><li>✅ <strong>Data Privacy</strong>: Everything runs locally, including tool output parsing</li></ul><h3>🧪 Tested Models</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19b8d8aadf4f1121c9b4098de94d91d1/href">https://medium.com/media/19b8d8aadf4f1121c9b4098de94d91d1/href</a></iframe><h3>🛠️ Next Steps</h3><ul><li>Add retry logic for tool call parsing</li><li>Add support for streaming token-by-token output</li><li>Create Runnable agents using this abstraction</li></ul><h3>🚀 Conclusion</h3><p>With this approach, you get the best of both worlds:</p><ul><li><strong>LangChain’s powerful abstractions</strong></li><li><strong>Open-source model flexibility</strong></li><li><strong>Tool-calling in secure, local environments</strong></li></ul><p>Check out the <a href="https://colab.research.google.com/drive/1dWLPCm4xfN2U0EryS6XyVvCRalTJVhLp?usp=sharing">Colab notebook</a> to try it yourself!</p><blockquote><em>Questions? Feedback? Let’s discuss in the comments or reach out on </em><a href="https://www.linkedin.com/in/anshuls235"><em>LinkedIn</em></a><em>!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d31ff4c7a76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plotly Dash: From Development to Deployment]]></title>
            <link>https://medium.com/data-science/plotly-dash-from-development-to-deployment-c9500d16581a?source=rss-baee49d6b712------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9500d16581a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dashboard]]></category>
            <dc:creator><![CDATA[Anshul Sharma]]></dc:creator>
            <pubDate>Sun, 23 May 2021 18:47:57 GMT</pubDate>
            <atom:updated>2021-05-25T03:17:19.692Z</atom:updated>
            <content:encoded><![CDATA[<h4>An easy-to-follow hands-on tutorial on Plotly Dash. Learn a bit of <strong>HTML</strong>, <strong>CSS</strong>, <strong>Python Decorators</strong>, and <strong>Docker</strong> in the process.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMcMzdN5vqFKcCjj" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Plotly Dash </strong>is an amazing framework to build interactive dashboards purely using Python. As a dashboard is akin to a website, definitely a bit of HTML &amp; CSS is also involved, but be rest assured it is so rudimentary that even I learned it while creating my first dashboard.</p><p>In this tutorial, we will be building a COVID19 dashboard showing the growth/decline of COVID19 cases, recoveries, and deaths in India. The dashboard can be accessed using this <a href="https://covid-dashboard-india.herokuapp.com/">link</a> and the underlying code can be accessed using this <a href="https://github.com/anshuls235/covid19-dashboard">GitHub repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiXEDC8AykUqtr5hSqWXAQ.png" /><figcaption>Screenshots are taken from the Aarogya Setu(COVID Updates section)</figcaption></figure><p>Below is a GIF showcasing the Dashboard built by me using Plotly Dash. I have taken inspiration from the Aarogya Setu app as I don’t think I have the design acumen. Also, I feel the app does a pretty good job of articulating the data insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Aofh5mVGqg0uZA6gJB022A.gif" /><figcaption>COVID19 Dashboard built using Plotly Dash</figcaption></figure><p>The steps that went into the whole process of developing and setting up the dashboard for everyone to see, broadly are</p><ol><li>Figuring out the Datasource 💽</li><li>Creating a Static Dashboard 📊</li><li>Making it Interactive 💹</li><li>Containerizing Everything 📦</li><li>Deploying the Project 🖥️</li></ol><p>Now, I will be elaborating on each of the points.</p><blockquote>I would recommend to always create a separate environment for all your Python projects. It makes it easy as you don’t face any dependency issues and also it helps a lot in deployment. <a href="https://www.anaconda.com/products/individual#Downloads">Anaconda</a> is my go-to tool for the same.</blockquote><h3>1. Figuring out the Datasource</h3><p>This is one task that can be as simple as using a CSV file downloaded from Kaggle or any other data platform or as difficult as scraping a large dataset off of a website.</p><p>The dataset I’m using for my dashboard is coming from <a href="https://github.com/covid19india/api">this API</a>. There are multiple APIs and one can use these as per their needs. The only thing to keep in mind is that although all the historical data is present, the data is refreshed daily for the present day. So, this is one thing you need to take care of when designing your data source: That the new data should get added daily.</p><p>Now that the data source is figured out, you need a way to store the data. It can be anything such as CSV, SQL table, e.t.c. As the data is not much and to keep everything simple I have used CSV files as <a href="https://github.com/anshuls235/covid19-dashboard/tree/master/data">my database</a> and the logic for adding and updating records can be found <a href="https://github.com/anshuls235/covid19-dashboard/blob/master/dataset.py">here</a>.</p><h3>2. Creating a Static Dashboard</h3><p>For building static web pages one definitely needs to know HTML and CSS, but with Plotly Dash it&#39;s exactly not the case. Dash is a web application framework that adds pure Python abstraction over HTML, CSS, and javascript. Having said that, one can learn the basics of HTML and CSS through <a href="https://www.w3schools.com/">W3 schools</a>. It&#39;s super basic! (At least for creating a dashboard like mine 😛)</p><blockquote><strong>Note</strong>: For the CSS changes to show, make sure to save your CSS file in the folder path ./assets/typography.css (Here ‘.’ represents the main project folder). The naming has to be just like this only. Also, you can use the HTML tag, id or class to reference the component in the app.py file directly.</blockquote><p>Dash provides us with a lot of functionalities out of the box but I won’t be covering all of them. Following are the ones used by me:-</p><ul><li><a href="https://dash.plotly.com/dash-html-components">Dash HTML components</a>: Instead of writing HTML or using an HTML templating engine, you compose your layout using Python structures with the dash-html-components library. It provides all the HTML tags.</li><li><a href="https://dash.plotly.com/dash-core-components">Dash Core components</a>: Dash ships with supercharged components for interactive user interfaces. A core set of components, written and maintained by the Dash team, is available in the dash-core-components library.</li><li><a href="https://dash.plotly.com/dash-daq">Dash DAQ</a>: Dash DAQ comprises a robust set of controls that make it simpler to integrate data acquisition and controls into your Dash applications.</li></ul><p>The basic app layout can be easily found on the tutorials. Below, I will try to explain each and every component of my dashboard and how did I come up with it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9834aacc995c7335da0619f80a8d25fb/href">https://medium.com/media/9834aacc995c7335da0619f80a8d25fb/href</a></iframe><p><strong>2.1 The Top Section</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w95i9wo7sPq81h5zFwRO7Q.png" /><figcaption>Top Section of the Dashboard</figcaption></figure><p>This section contains the title along with some of my advertising(LOL) followed by showing the total metrics to date and their jump from the previous day. This section will definitely change on a daily basis but still, we can create its static version. In the layout.py file above, lines 13–39make up this section.</p><blockquote><strong>Note</strong>: For the images to show up in your dashboard, they should be stored inside the path ./assets/ . Kindly pay attention to the spelling of the folder ‘assets’. The subfolders can be named anything.</blockquote><p>If you see carefully, the HTML tag &lt;h1&gt;COVID19 India Dashboard&lt;/h1&gt; changes to html.h1(‘COVID19 India Dashboard’). The HTML tag attributes can be sent using parameters to dash HTML components.</p><p>Another example &lt;img src=’/assets/images/kaggle.png’ class=’img’&gt; is equivalent to html.Img(src=’/assets/images/kaggle.png’,className=’img’)</p><p>The function(below) shows the function that was used to create a table(using dash HTML components) from pandas dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff3d56c304323bb21c0235da1a83bfdc/href">https://medium.com/media/ff3d56c304323bb21c0235da1a83bfdc/href</a></iframe><p><strong>2.2 The Middle Section</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_IW92pvI8Sv_UR42JMEsw.png" /><figcaption>The Middle Section of the Dashboard</figcaption></figure><p>This is the heart of the dashboard containing the dropdown menu, the tabs(active, confirmed, recovered &amp; deceased), the graph(line+bar), and the toggle switch. Lines 40–64 make up the middle section in the layout.py file shown above.</p><ul><li><strong>dropdown</strong> is pretty easy to add and <a href="https://dash.plotly.com/dash-core-components/dropdown">here</a> are a lot of examples for you to refer to. It’s a part of <strong>dash-core-components</strong>.</li><li><strong>tabs</strong> are added using <a href="https://dash.plotly.com/dash-core-components/tabs">this documentation</a>. It’s a part of <strong>dash-core-components</strong>.</li><li><strong>graph</strong>, which is too a part of <strong>dash-core-components</strong>, can be added using <a href="https://dash.plotly.com/dash-core-components/graph">this</a>. dcc.graph() should contain a plotly figure object. A plotly figure object can be created using <a href="https://plotly.com/python/plotly-express/">plotly express</a> or <a href="https://plotly.com/python/graph-objects/">graph objects</a>. plotly express is very easy to use API while graph objects is a bit non-trivial but provides a lot of customization.</li><li><strong>ToggleSwitch</strong>, which is a part of <strong>dash daq</strong>, can be added <a href="https://dash.plotly.com/dash-daq/toggleswitch">referring to this link</a>.</li></ul><p><strong>2.3 The Bottom Section</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5FWHZWP0RpfqsMVe14fwQ.png" /><figcaption>The Bottom Section of the Dashboard</figcaption></figure><p>Lines 65–70 make up this section and it contains the heading along with a table showing the state-wise breakdown. The table will be dynamic(as the position of states can change depending on the total cases), so I have created a function that creates a table that can be shown using <strong>dash-html-components </strong>from a pandas dataframe. The function is almost similar to the one used for the 2.1 section. It is by the name generate_table() in the <a href="https://github.com/anshuls235/covid19-dashboard/blob/74acf376755efdcc6a53c4e51f392c54ec585194/app.py">code</a>.</p><h3>3. Making it Interactive</h3><p>Usually, JavaScript is needed to make websites interactive, but don’t worry we don&#39;t need to know it for creating dashboards using plotly dash. You just need to know Python!</p><p>Dash provides <a href="https://dash.plotly.com/basic-callbacks"><strong>callback functions</strong></a>, which are nothing but Python <strong>Decorators</strong> that are automatically called by Dash whenever an input component’s property changes. Refer to <a href="https://www.youtube.com/watch?v=FsAPt_9Bf3U">this Youtube Video</a> to learn more about Decorators.</p><p>If you have seen my dashboard or even the GIF at the top, you can make out that all the interactivity involved is in the graph:-</p><ul><li>Change based on the state selected in the dropdown. By default, it shows data for India as a whole.</li><li>Change based on the tab selected: Active, Confirmed, Recovered, or Deceased.</li><li>On hover, show values along with the date on the top-left corner.</li><li>Change based on the toggle switch: Cumulative(Line graph) or Daily(Bar graph).</li></ul><p>All the changes take place in the same graph only, so we would require only a single callback function. I’ll try to explain it below in simple words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*JuYRuFu9D9-Fbe2SIgflGg.png" /><figcaption>An explanation of the Callback Function. Pay attention to the order of the Input and also the id, parameter, and value of the Inputs.</figcaption></figure><ol><li>state-dropdown is the “id” of the dropdown and we are getting the value of its “value” parameter as 1st input. The default value is <strong>India</strong>.</li><li>india-graph is the “id” of the graph itself, but here we are getting the value of its “hoverData” parameter as the 2nd input. The default value is <strong>Null</strong>. (As we are not hovering over the graph once we open the app.)</li><li>my-toggle-switch is the “id” of the ToggleSwitch and we are getting the value of its “value” parameter as the 3rd input. The default value is <strong>True</strong> that I assume is <strong>Cumulative</strong>.</li><li>tabs is the “id” of the Tabs component and we are getting the value of its “value” parameter as the 4th input. The default value is <strong>Active</strong>.</li></ol><p>The output of the callback is a graph whose “id” is india-graph and the output is sent to the graph’s <strong>figure</strong> parameter. (I would request you to refer to <a href="https://plotly.com/python/graph-objects/">plotly graph objects documentation</a> in case you find any problem in understanding it.)</p><blockquote>So, once you open the app you will be seeing Cumulative(3) Active(4) COVID19 Cases for India(1) without any hoverinfo(2) as per the callback function parameters. The number within the parenthesis shows the Input order sent to the callback function.</blockquote><p>The <strong>Input</strong> &amp; <strong>Output</strong> you see in the callback function are the dash dependencies. If these are multiple then they are required to be sent as a list (4 Inputs in the above example). Just keep in mind you need to send these to the decorator/callback function and below you can define a function with any name and give them any parameter names you like.</p><p>The function update_tab_graph takes in the 4 Inputs defined in the callback:(One can think of these parameters as mappings to the callback inputs)</p><ol><li>state = value in Input 1.</li><li>hdata = hoverData in Input 2.</li><li>r_value = value in Input 3.</li><li>col = value in Input 4.</li></ol><p>Output is the figure object returned by the function.</p><p>Now, if someone changes anything among the 4 inputs, the callback will be triggered and the graph will be updated. <em>Like the figure above shows an example for Delhi.</em></p><h3>4. Containerizing Everything</h3><p><a href="https://docs.docker.com/get-started/">Docker</a> is an amazing tool for creating containers and it is pretty easy to use. The best part is that the containers are OS agnostic. Most of the containers are Linux-based but can run on Windows/Mac OS without any issues thanks to some awesome technology that’s out of the scope of this article.</p><p>Docker in itself is huge and can’t be explained in this article for sure. So, I will just try to explain it in my own simple words.</p><p>Let’s just say you created a Python project. Now you want to share it with your friend. One simple way is to share the entire project folder. Your friend will then create a new environment and install the dependencies in the requirements.txt file and then will be able to run the project. This approach is very easy for seasoned developers but for someone who’s just starting out or even not much aware of the setup process, will surely face a lot of issues. This is where Docker comes to the rescue. Your friend just needs to have Docker installed(<a href="https://www.docker.com/products/docker-desktop">Docker Desktop preferred</a>) and then he/she can import your Docker image and then just run it to see your project. <strong>Basically, if your docker container runs on your local machine, it will surely run any other machine irrespective of the OS.</strong></p><p>To clear out the confusion, you just need to know these 3 things to get started with Docker:</p><ul><li><strong>Dockerfile</strong>: This is the file that contains all the instructions line by line to create your Docker Image.</li><li><strong>Image</strong>: The entire package/build containing the Dockerfile along with all the required project files(you can ignore some files by mentioning them in the <strong>.dockerignore</strong> file) and all the dependencies installed.</li><li><strong>Container</strong>: An instance of an image that is run by following the steps/layers in the Dockerfile sequentially.</li></ul><blockquote>An amazing analogy I read somewhere: A Container is a cookie, an image is the mould used to create that cookie and a Dockerfile are the instructions that went into creating that mould.</blockquote><p>Below is the Dockerfile that I used for my project. I’ll try to explain all the steps/layers one by one.</p><pre>FROM python:3.8-slim</pre><pre>WORKDIR /app </pre><pre>COPY . . </pre><pre>RUN pip install -r requirements.txt </pre><pre>EXPOSE 8050 </pre><pre>CMD [“python”, “app.py”]</pre><ul><li>FROM python:3.8-slim imports the python image (basically, python3.8 installed on Linux OS). I have imported the slim version as I wanted to keep my image lightweight.</li><li>WORKDIR /app creates a directory with the name “app” in our python image.</li><li>COPY . . copies all the files and folders in the project folder to the app directory. Files/Folders mentioned in the .dockerignore file are ignored.</li><li>RUN pip install -r requirements.txt runs the command line that installs all the dependencies inside the requirements.txt file. This file was copied in the previous step.</li><li>EXPOSE 8050 exposes the port 8050 on the docker side. You need to be careful while mapping your machine’s port to this.</li><li>CMD [“python”, “app.py”] runs your project. It&#39;s exactly similar to the command line(just the text split into a list at spaces) you’ll use to run your project in your local machine.</li></ul><p>Once, the Dockerfile is completed, execute the below code in the same folder to build your docker image.</p><pre>docker build -t covid-dashboard-india .</pre><p>Finally, to run your container execute the code below. Pay attention to the port mapping I have done. It’s done using the -p tag and on the left side of the semicolon is your local machine’s port and on the right side is the container’s port.</p><pre>docker run -p 8050:8050 covid-dashboard-india</pre><p>Navigate to your localhost at port 8050 to see the Dashboard and play around with it.</p><h3>5. Deploying the Project</h3><p>If you are satisfied with everything, then the final step is just choosing a registry where you could deploy your docker image. There are a plethora of registries out there such as Heroku, AWS ECR, e.t.c. The best thing is that Heroku is free of cost and I have used it for this project of mine.</p><p>Just follow all the steps mentioned in <a href="https://devcenter.heroku.com/articles/container-registry-and-runtime">this link</a> to get your image deployed. It is pretty easy to follow.</p><h3>TA-DA! You just developed and deployed a Dashboard 👏</h3><p>I hope that you find this article useful. Feel free to reach out to me in case of any queries :)</p><h4><a href="https://www.linkedin.com/in/anshuls235/">LinkedIn</a><br><a href="http://anshuls235@gmail.com/">Gmail</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9500d16581a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/plotly-dash-from-development-to-deployment-c9500d16581a">Plotly Dash: From Development to Deployment</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[Vaccine Slot Notifier using AWS & Python]]></title>
            <link>https://medium.com/analytics-vidhya/vaccine-slot-notifier-using-aws-python-bbfe7dd60e84?source=rss-baee49d6b712------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfe7dd60e84</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Anshul Sharma]]></dc:creator>
            <pubDate>Fri, 14 May 2021 07:18:33 GMT</pubDate>
            <atom:updated>2024-01-17T11:00:02.415Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to build your own notification system using few simple steps!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ir4-al-cwk7xWYTf" /><figcaption>Photo by <a href="https://unsplash.com/@diana_pole?utm_source=medium&amp;utm_medium=referral">Diana Polekhina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>India announced that from May 1, 2021, it will start vaccination of people in the age group 18–44 years. Earlier, it was only for all 45+ years old. Also, it is mandatory to be registered and booked for an appointment on the <a href="https://www.cowin.gov.in/home">COWIN portal</a> prior to coming for vaccination. India has a population of 594.6 million for the age group 18–44 years and only a single portal to register for vaccination. So definitely, this called for the techies to use their skills and build notification systems to save everyone from the hassle. The tweet below pretty much sums it up 😜</p><h3>Praveen Gopal Krishnan on Twitter: &quot;If you are 18+ and live in Bangalore, the only way to get vaccine appointments is to use python scripts that ping CoWin&#39;s public API and setup notification alerts via Telegram, Twitter or SMS.Yes, the vaccination drive is now officially a hackathon. / Twitter&quot;</h3><p>If you are 18+ and live in Bangalore, the only way to get vaccine appointments is to use python scripts that ping CoWin&#39;s public API and setup notification alerts via Telegram, Twitter or SMS.Yes, the vaccination drive is now officially a hackathon.</p><p>There are a plethora of notification systems out there and they are quite helpful as well. I wanted to create my own version and just thought of documenting it as the same process can be replicated across many other things, not only COVID vaccinations.</p><p>Coming straight to the point, the following are the steps I used to come up with my own notification system. Will elaborate on each step later on.</p><ol><li>Locate the source of data.</li><li>Fetch and Manipulate data.</li><li>Create a pipeline that implements step 2 indefinitely and also sends notifications.</li></ol><h3><strong>STEP 1: LOCATE THE SOURCE OF DATA -</strong></h3><ul><li>The best thing is that <strong>public APIs</strong> are already available so you can straightaway check out <a href="https://www.analyticsvidhya.com/blog/2021/05/analyze-covid-vaccination-progress-using-python/">this link</a> and fetch the data as per your needs.</li><li>A more generic way is to use <strong>developer tools</strong> and find the API through the <strong>Network</strong> tab. Better to filter by XHR requests in case there are a lot of requests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_DI6ywpbgGqT4WdFz8bMw.png" /></figure><h3>STEP 2: FETCH AND MANIPULATE DATA -</h3><p>Now that you have got the source figured out, you just need to create a script that will fetch the data from the source and manipulate it into your preferred format. For scripting purposes, I have used Python and my preferred format is a table owing to readability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f653df315fa9f5ca1eaaaea56b3a8f5c/href">https://medium.com/media/f653df315fa9f5ca1eaaaea56b3a8f5c/href</a></iframe><p>Few points regarding the code:-</p><ul><li>Since I’m using <strong>AWS lambda</strong>, the code is for the lambda function. It’s just that it is encapsulated inside the function <strong>lambda_handler</strong>.</li><li>In order to import <strong>pandas</strong> and <strong>requests</strong> into my lambda function, I used lambda layers. <a href="https://medium.com/analytics-vidhya/aws-adding-python-libraries-to-lambda-layers-8c4eaf8fed80">Follow this article</a> to add non-standard python libraries to lambda.</li><li>Lambda runs the code as per the UTC timezone. I forgot to import pytz and also it isn’t a standard library. So, that&#39;s why manually changing the timezone in <strong>line 13</strong>.</li><li>I have hardcoded the districts in <strong>line 14</strong> because I and my friends wanted updates for Delhi NCR only. So, the logic can be implemented as per your needs.</li><li>As I built the service for my friends and myself, I added the recipients as an <strong>environment variable</strong>. You can read them from your DB or from S3 as per your needs.</li><li><strong>send_email </strong>function is in utils.py. I have taken <a href="https://kuharan.medium.com/sending-emails-with-aws-lambda-aws-simple-email-service-ses-513839bc53ab">this amazing article</a> as a reference to create this function.</li></ul><h3>STEP 3: CREATE A PIPELINE THAT IMPLEMENTS STEP 2 INDEFINITELY AND ALSO SENDS NOTIFICATIONS -</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maflAAxB-SXakl3fwOOQ6w.png" /></figure><p>Above is the simple AWS architecture used for the vaccine notifier. The schedule expression enables <strong>EventBridge</strong> to trigger the <strong>lambda</strong> function in step 2 after every <strong>2 minutes</strong>. The frequency totally depends on your needs.</p><p>AWS provides 2 notification services: <strong>SNS</strong> &amp; <strong>SES</strong>. <strong>SNS</strong> enables you to send messages or emails in a simple text format. <strong>SES </strong>enabled you to send formatted emails or text messages using HTML. You can even send emails with attachments. Since <strong>Pandas</strong> provides a function <strong>df.to_html() </strong>to convert<strong> </strong>dataframe into HTML, it motivated me to use SES.</p><ul><li>SES is a pretty easy to use service. You just need to go to SES in your AWS console and add the email/identities there. As soon as you create an identity, a verification mail is sent to the same and on verification, a verified with a green tick is added as the status of the identity.</li></ul><blockquote><strong>Please note</strong>: SES mails can only be sent to verified mails in sandbox. Also, the sender needs to be verified irrespective of the access(sandbox/production).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyN92-_UO-yhfAvVKAHwyQ.png" /></figure><ul><li>As I was using it personally, I added the emails manually. To automate the whole process you can simply use <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ses.html#SES.Client.verify_email_address">boto3</a>.</li><li>AWS initially provides <strong>sandbox access</strong> to SES and there is a cap on the number of emails(200/day) that you can send. But, you can request <strong>production access </strong>with a valid reason and AWS would be happy to grant one. Also, once you have production access, you can make changes to the verification mail template as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6liOjfgFjFAsn5tWmMKRpg.png" /><figcaption>Screenshot of my account dashboard. My account is in sandbox.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNn5TCHYEr4rnn9w1_ND5g.png" /><figcaption>Example Mail</figcaption></figure><p>Following all the steps will give you your vaccine slot notifier like above using Python &amp; AWS. As I said before, the same process can be used for many other purposes as well.</p><p>I hope that you find this article useful. Feel free to reach out to me in case of any queries :)</p><h3><a href="https://www.linkedin.com/in/anshuls235/">LinkedIn</a><br><a href="http://anshuls235@gmail.com/">Gmail</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfe7dd60e84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/vaccine-slot-notifier-using-aws-python-bbfe7dd60e84">Vaccine Slot Notifier using AWS &amp; Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS: Adding Python Libraries to Lambda Layers]]></title>
            <link>https://medium.com/analytics-vidhya/aws-adding-python-libraries-to-lambda-layers-8c4eaf8fed80?source=rss-baee49d6b712------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4eaf8fed80</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anshul Sharma]]></dc:creator>
            <pubDate>Sun, 04 Apr 2021 09:13:19 GMT</pubDate>
            <atom:updated>2021-05-12T06:33:18.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Um5igHw8BEJ3gcY" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>AWS Lambda</strong> is the way to go when making <em>short workflows</em> or <em>scheduling simple CRON jobs</em> that may run for a maximum of <strong>15 minutes</strong>. The best part about it is that one doesn’t need to worry about setting up the computing environment as it’s all serverless. You can even use it as a <em>dispatcher </em>for triggering your ECS or AWS Batch tasks. There might be a lot of other things as well but I haven’t explored them as of yet.</p><p>Python runtime in Lambda comes with its own set of <a href="https://gist.github.com/gene1wood/4a052f39490fae00e0c3">standard libraries</a>. A lot of libraries such as boto3, requests, e.t.c are already installed that you can import straight away and create your lambda function. But, the problem arises when you want to use libraries that are not available (<em>even Pandas is not available </em>😐).</p><p>So, now to do away with this problem one can follow any of these approaches:</p><ol><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/python-package.html"><strong>AWS Deployment package</strong></a>: Package the code and all its dependencies into a ZIP file and upload it to AWS. Don’t find this useful as you always need to upload the packages even if you are using the same libraries every time. Definitely, a bit counter-intuitive.</li><li><strong>AWS Lambda Layers</strong>: Just package the dependencies into a ZIP file and upload it to AWS. Also, once a layer is defined, all its underlying dependencies can be used by any number of Lambda functions.</li></ol><p>I feel the latter approach to be the best one as it saves a lot of time, space and promotes reproducibility. I will be discussing this approach only from now on.</p><blockquote><strong>Please Note</strong>: Lambda uses amazon linux environment as its OS. Therefore, all the python packages that you install on your Windows laptop/PC may not work on it. Packages installed on Linux based distributions such as Ubuntu work. Mac should also work but not sure. Using <a href="https://www.docker.com/products/docker-desktop">Docker</a> on my windows machine, I will be uploading packages installed on Ubuntu to my lambda layer. So, I would also recommend you to install Docker if not already.</blockquote><p>Now, this is where we start adding the required packages into Lambda Layers. Pardon me from digressing from the topic, but I thought it’s always better to give an overview :)</p><p>Just follow the below steps in order. The highlighted commands are to run in your CLI.</p><ol><li>docker run ubuntu : Pulls the image if not there and runs a container.</li><li>apt update : Update the advanced package tool.</li><li>apt install python3.8 : Install Python(be careful of the version. I’m installing 3.8).</li><li>apt install python3-pip : Install pip.</li><li>mkdir -p lambda_layer/python/lib/python3.8/site-packages : Make a directory where you will install the packages (Make sure the directory path is the same. The first folder name can be of your choice as is ‘lambda_layer ’in my case. Just be cautious of the python version).</li><li>pip3 install &lt;package-name&gt; -t lambda_layer/python/lib/python3.8/site-packages/ : Install the required python packages into the directory made. For multiple packages separate packages by space.</li><li>apt-get install zip : Install zip if not already there.</li><li>cd lambda_layer: CD into the folder made.</li><li>zip -r python.zip * : Store all the packages installed into a ZIP file.</li><li>Open a new command prompt session on your pc side by side.</li><li>docker ps -a : List all the running containers.</li><li>Copy the <strong>CONTAINER ID</strong> of your ubuntu image. Its an alphanumeric such as <strong>79e37f5ff0db</strong>.</li><li>docker cp 79e37f5ff0db:/lambda_layer/python.zip C:\Users\anshul.sharma\aws : Copy the zip file from docker container to your PC using this convention — docker cp &lt;CONTAINER_ID&gt;:&lt;path of zip in container&gt; &lt;source directory&gt;</li><li>Upload the <strong>python.zip</strong> file to lambda layer directly if it’s less than <strong>10MB</strong> or else, upload it first to s3 and enter the path when defining a lambda layer.</li></ol><p>At first, these may seem like a lot of steps. But, as I said it&#39;s a one-time activity, and once uploaded any user can use these libraries by just adding the respective layer to their lambda function.</p><p>I hope that you find this article helpful. I spent a lot of time trying to figure out a way to add libraries to lambda layers and thought of sharing it. Feel free to reach out to me in case of any queries :)</p><h4><a href="https://www.linkedin.com/in/anshuls235/">LinkedIn</a><br><a href="http://anshuls235@gmail.com/">Gmail</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4eaf8fed80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/aws-adding-python-libraries-to-lambda-layers-8c4eaf8fed80">AWS: Adding Python Libraries to Lambda Layers</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DIY Interactive App just using python]]></title>
            <link>https://medium.com/analytics-vidhya/diy-interactive-app-just-using-python-55134429bf35?source=rss-baee49d6b712------2</link>
            <guid isPermaLink="false">https://medium.com/p/55134429bf35</guid>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anshul Sharma]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 07:00:08 GMT</pubDate>
            <atom:updated>2020-06-30T14:04:34.272Z</atom:updated>
            <content:encoded><![CDATA[<h3>DIY Interactive App just using Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ga4G2whs1KV7E95q" /><figcaption>Photo by <a href="https://unsplash.com/@srd844?utm_source=medium&amp;utm_medium=referral">Stephen Dawson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Make an interactive app just using python and showcase it through <strong>Jupyter/Kaggle/Colab…….</strong> Notebooks.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkBptuCNtycKSP4UiWg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkBptuCNtycKSP4UiWg%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkBptuCNtycKSP4UiWg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="239" frameborder="0" scrolling="no"><a href="https://medium.com/media/704cb2a328f2461543a4eed97e39c65f/href">https://medium.com/media/704cb2a328f2461543a4eed97e39c65f/href</a></iframe><h3><strong>Motivation</strong></h3><p>Doing visualizations on a huge dataset with a lot of categories can be a tedious task. You always end up showing just the best or the worst as showing details about let’s say 200 different categories is not feasible. So, what could be better than creating an app through which you can show all the required details at once, save on your time, and also people’s time reading your notebook.</p><p>Through this story, I will be providing all the steps on how to create an app just using python. The only prerequisite is good knowledge of python and a little bit of knowledge of the <a href="https://pandas.pydata.org/docs/getting_started/index.html">pandas library</a>(only because I’m using it in this project). I’ll be using <a href="https://ipywidgets.readthedocs.io/en/latest/">ipywidgets library </a>also but knowledge of it is optional as I also worked with it the first time.</p><h3>About the App</h3><p>I call it the Birdcall App. What is does is show an image, description, stats, waveform of the chirp, and the location where the chirp of the bird was recorded. One can scroll through the species of the birds, the recordist who recorded the chirp, and the audio file. The contents of the app change depending on the selection. The same way as you can see in the top gif.</p><p>The dataset I have used is available <a href="https://www.kaggle.com/c/birdsong-recognition">here</a>. It’s a part of an ongoing kaggle competition. The data contains all the details about the birds chirp. The only thing it doesn’t provide is the bird description and the image of the bird. So, that’s the extra bit that needs to be scrapped.</p><h3><strong>Gathering the Data</strong></h3><p>For the app to work we need the data. As mentioned above we have all the data to create our app. Just for the images and description of the bird species, we’ll have to scrape the web.</p><p>Here’s the code to get the bird details such as description and images. I have scrapped these details using beautiful soup and requests library. The webpage from where I have scraped the data is <a href="https://ebird.org/species">https://ebird.org/species</a>.</p><pre><em>dic_bird = {} <br>for code in df_train.ebird_code.unique():</em><br><em>    if code not in dic_bird:</em><br><em>        url = &#39;https://ebird.org/species/&#39;+code</em><br><em>        r = requests.get(url)</em><br><em>        soup = BeautifulSoup(r.content, &#39;html.parser&#39;)</em><br><em>        desc = soup.find(&#39;meta&#39;,property=&quot;og:description&quot;)</em><br><em>        image = soup.find(&#39;meta&#39;,property=&quot;og:image&quot;)</em><br><em>        dic_bird[code]={}</em><br><em>        dic_bird[code][&#39;description&#39;] = desc[&#39;content&#39;]</em><br><em>        dic_bird[code][&#39;image&#39;] = image[&#39;content&#39;]</em></pre><pre>#Convert the dictionary to dataframe.<br><em>df = pd.DataFrame(columns=[&#39;species&#39;,&#39;description&#39;,&#39;image&#39;])</em><br><em>i = 0</em><br><em>for key,val in dic_bird.items():</em><br><em>    df.loc[i,&#39;species&#39;] = key</em><br><em>    df.loc[i,&#39;description&#39;] = val[&#39;description&#39;]</em><br><em>    df.loc[i,&#39;image&#39;] = val[&#39;image&#39;]</em><br><em>    i+=1</em><br><em>df.to_csv(&#39;bird_details.csv&#39;,index=False)</em></pre><p>As can be seen from the code, to get the details of a particular species of the bird we need to append its `ebird_code` to the site URL.</p><h3>Designing the Components</h3><p>After collecting all the data, the next logical step is to create the components of the app one by one. I’ll be listing down the steps for all components one by one in sequence.</p><blockquote><strong>1. Species, Recordist &amp; Audio options</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYLwQNGH4_zDNrAA9F9h0A.png" /><figcaption>Example of how the scrolling options look in the app</figcaption></figure><p>The user can easily scroll through all the options easily. Also, the values of recordists and filename change on the basis of the species selected. This will be covered in the interactions section later. The code to implement this is as follows:</p><p>I have used a dictionary to add initial values and created separate methods to get the data. You can write your own.</p><pre>import ipywidgets as widgets</pre><pre>species = widgets.Dropdown(<br>    description = &#39;Species:   &#39;,<br>    value = default_values[&#39;species&#39;],<br>    options = df_train[&#39;species&#39;].unique().tolist(),<br>    layout=dict(width=&#39;233px&#39;)<br>)</pre><pre>recordists = widgets.Dropdown(<br>    description = &#39;Recordist:   &#39;,<br>    value = default_values[&#39;recordist&#39;],<br>    options = get_recordist_options(default_values[&#39;species&#39;]),<br>    layout=dict(width=&#39;233px&#39;)<br>)</pre><pre>audios = widgets.Dropdown(<br>    description = &#39;Filename:    &#39;,<br>    value = default_values[&#39;audio&#39;],<br>    options = get_audio_options(default_values[&#39;species&#39;],default_values[&#39;recordist&#39;]),<br>    layout=dict(width=&#39;233px&#39;)<br>)<br>container1 = widgets.HBox(children=[species, recordists, audios])</pre><blockquote><strong>2. Title + Audio Container</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8xYmRPsh-Z7aAtbAwXi_w.png" /><figcaption>The container with the title and option to play the mp3 file</figcaption></figure><p>The title can be easily added using the HTML widgets. It changes depending on the species selected. The audio is shown using the Audio widget.</p><pre>title = widgets.HTML(&#39;&lt;h1&gt;{}&lt;/h1&gt;&#39;.format(default_values[&#39;species&#39;]),layout=dict(width=&#39;350px&#39;))<br>out = widgets.Output(layout=dict(width=&#39;350px&#39;,margin=&#39;10px 0px 0px 0px&#39;))<br>out.append_display_data(ipd.Audio(default_values[&#39;filename&#39;]))<br>container2 = widgets.HBox(children=[title,out])</pre><blockquote><strong>3. Image + Description Container</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Whlb32fpXU-KlqQaEEyTQA.png" /><figcaption>Container showing Bird Image and Description</figcaption></figure><p>I have added image and description using the HTML widget. Later, both are pooled into a Horizontal Box container using HBox widget. Also, layout can be defined for each widget separately. This is exactly similar to CSS.</p><pre>im = widgets.HTML(&#39;&lt;img src=&quot;{}&quot;/&gt;&#39;.format(default_values[&#39;image&#39;]),<br>                 layout=dict(height=&#39;250px&#39;,width=&#39;300px&#39;))<br>text = widgets.HTML(&#39;&lt;h5&gt;{}&lt;/h5&gt;&#39;.format(default_values[&#39;text&#39;]),<br>                 layout=dict(height=&#39;250px&#39;,width=&#39;400px&#39;,margin=&#39;10px 0px 0px 10px&#39;))<br>container3 = widgets.HBox(children=[im,text])</pre><blockquote><strong>4. Bird Stats</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWiRy5YqYYMzAhEJTb-RnQ.png" /><figcaption>Bird Statistics</figcaption></figure><p>Avg. Rating is the mean rating of all the ratings for short recordings of bird’s species calls generously uploaded by users of <a href="https://www.xeno-canto.org/">xenocanto.org</a>. Average duration is the mean duration of the bird calls. Average elevation as the name suggests is the mean height the bird travels at.</p><pre>r,d,e = get_stats(default_values[&#39;species&#39;])<br>rating = widgets.HTML(&#39;&lt;h2&gt;Avg. Rating&lt;/h2&gt;&lt;h4&gt;{}&lt;/h4&gt;&#39;.format(r),layout=dict(width=&#39;233px&#39;))<br>duration = widgets.HTML(&#39;&lt;h2&gt;Avg. Duration&lt;/h2&gt;&lt;h4&gt;{} s&lt;/h4&gt;&#39;.format(d),layout=dict(width=&#39;233px&#39;))<br>elevation = widgets.HTML(&#39;&lt;h2&gt;Avg. Elevation&lt;/h2&gt;&lt;h4&gt;{} m&lt;/h4&gt;&#39;.format(e),layout=dict(width=&#39;233px&#39;))<br>container4 = widgets.HBox(children=[rating,duration,elevation])</pre><blockquote><strong>5. Waveform Plot</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kw49sRLGC7-Wm3XRVaJx2g.png" /><figcaption>Birdcall waveform plotted using Plotly</figcaption></figure><p>I have used a helper function to <a href="https://stackoverflow.com/questions/53633177/how-to-read-a-mp3-audio-file-into-a-numpy-array-save-a-numpy-array-to-mp3">convert mp3 to NumPy array</a> and then used Plolty <a href="https://plotly.com/python/figurewidget/">FigureWidget</a> to create the waveform plot. Simple matplotlib plots can be used as well but I always prefer Plotly owing to its added interactivity. The waveform changes on the basis of the audio file selected.</p><pre>rate, arr = read(default_values[&#39;filename&#39;])<br>title_g = widgets.HTML(&#39;&lt;h2&gt;Waveform of the bird chirp&lt;/h2&gt;&#39;)<br>g = plot_waveform(arr,default_values[&#39;filename&#39;].split(&#39;/&#39;)[-1])</pre><blockquote><strong>6. Map Plot</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gPQ-yWnbEcAmhqWnvGcSA.png" /><figcaption>Map showing the recording location</figcaption></figure><p>I have used Plotly’s <a href="https://plotly.com/python/scattermapbox/">scattermapbox</a> to plot the recording location on the map. It also changes depending on the audio file selected.</p><pre>title_map = widgets.HTML(&#39;&lt;h2&gt;Where the recording was made?&lt;/h2&gt;&#39;)<br>loc_map = plot_location(default_values[&#39;latitude&#39;],default_values[&#39;longitude&#39;],default_values[&#39;location&#39;])</pre><p><em>Please note all the plotly plots are ultimately added to the plotly.graph_objects.Figurewidget for ipywidgets to work properly with them.</em></p><blockquote><strong>7. Combining all components</strong></blockquote><p>After designing all the components, just pool them into a single component.</p><pre>widgets.VBox(children=[container1,container2,container3,container4,title_g,g,title_map,loc_map])</pre><h3>App Interactions</h3><p>Nobody likes a static app! So, to add interactions to our ipywidgets app we need to add callback functions which will take care of changing the data of the components we designed.</p><p>The following are the interactions which take place in my app:</p><ul><li><strong>change species</strong>-&gt; change <em>recordists </em>dropdown, change <em>audios </em>dropdown, change <em>title</em>, <em>image </em>&amp; <em>text</em>, and change <em>bird stats</em>.</li><li><strong>change recordist</strong>-&gt; change <em>audios </em>dropdown.</li><li><strong>change audio</strong>-&gt; change <em>waveform </em>and<em> recording location map</em>.</li></ul><p>I have kept separate callbacks to stick to the flow listed above. Please note when <strong><em>response_sp()</em> </strong>callback is triggered it will automatically trigger <strong><em>response_re()</em></strong> and <strong><em>response_au()</em></strong> callbacks respectively as recordists and audio values are changing in the species change callback function.</p><p>Similarly, <strong><em>response_re() </em></strong>will trigger<strong><em> response_au(). </em></strong>And response_au() alone won’t trigger any callbacks.</p><pre>def response_sp(change):<br>    ecode = get_ebird_code(species.value)<br>    <br>    #change recordists dropdown<br>    options = get_recordist_options(species.value)<br>    recordists.options = options<br>    recordists.value = options[0]<br>    <br>    #change filename dropdown<br>    options = get_audio_options(species.value,recordists.value)<br>    audios.options = options<br>    audios.value = options[0]<br>    <br>    #change title, image and text<br>    title.value = &#39;&lt;h1&gt;{}&lt;/h1&gt;&#39;.format(species.value)<br>    im.value = &#39;&lt;img src=&quot;{}&quot;/&gt;&#39;.format(get_image(ecode))<br>    text.value = &#39;&lt;h5&gt;{}&lt;/h5&gt;&#39;.format(get_text(ecode))<br>    <br>    #change bird stats<br>    r,d,e = get_stats(species.value)<br>    rating.value = &#39;&lt;h2&gt;Avg. Rating&lt;/h2&gt;&lt;h4&gt;{}&lt;/h4&gt;&#39;.format(r)<br>    duration.value = &#39;&lt;h2&gt;Avg. Duration&lt;/h2&gt;&lt;h4&gt;{} s&lt;/h4&gt;&#39;.format(d)<br>    elevation.value = &#39;&lt;h2&gt;Avg. Elevation&lt;/h2&gt;&lt;h4&gt;{} m&lt;/h4&gt;&#39;.format(e)</pre><pre>def response_re(change):<br>    #change audios dropdown<br>    options = get_audio_options(species.value,recordists.value)<br>    audios.options = options<br>    audios.value = options[0]</pre><pre>def response_au(change):<br>    ecode = get_ebird_code(species.value)<br>    file = audios.value<br>    filename = get_filename(ecode,file)<br>    with out:<br>        ipd.clear_output()<br>        ipd.display(ipd.Audio(filename))<br>    rate, arr = read(filename)<br>    g_new = plot_waveform(arr,filename.split(&#39;/&#39;)[-1])<br>    g.update(data=g_new.data,layout=g_new.layout)<br>    lat = df_train.loc[df_train[&#39;filename&#39;]==audios.value,&#39;latitude&#39;].tolist()[0]<br>    lon = df_train.loc[df_train[&#39;filename&#39;]==audios.value,&#39;longitude&#39;].tolist()[0]<br>    location = df_train.loc[df_train[&#39;filename&#39;]==audios.value,&#39;location&#39;].tolist()[0]<br>    loc_map_new = plot_location(float(lat),float(lon),location)<br>    loc_map.update(data=loc_map_new.data,layout=loc_map_new.layout)</pre><pre>#Callback functions    <br>species.observe(response_sp, names=&quot;value&quot;)<br>recordists.observe(response_re, names=&quot;value&quot;)<br>audios.observe(response_au, names=&quot;value&quot;)</pre><p>The last three lines of the code show how to declare the callback functions for a widget.</p><h3>Finally, our app is complete!!</h3><blockquote>To access the full code of the app <a href="https://www.kaggle.com/anshuls235/diy-interactive-birdcall-app">click here</a>.</blockquote><blockquote>To see more projects on which I have worked <a href="https://www.kaggle.com/anshuls235">click here</a>.</blockquote><p>I hope I have explained it in a clear manner. In case you have any doubts or have any feedback do leave a comment. Thanks for reading this far :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55134429bf35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/diy-interactive-app-just-using-python-55134429bf35">DIY Interactive App just using python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>