<?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 Fatih KIR on Medium]]></title>
        <description><![CDATA[Stories by Fatih KIR on Medium]]></description>
        <link>https://medium.com/@fatikir15?source=rss-f44f55442950------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_du78tyH1qrw-hX8.jpg</url>
            <title>Stories by Fatih KIR on Medium</title>
            <link>https://medium.com/@fatikir15?source=rss-f44f55442950------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:46:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fatikir15/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[Create a Local MCP Stack to Investigate Apache Spark Job Failures Privately]]></title>
            <link>https://medium.com/@fatikir15/create-a-local-mcp-stack-to-investigate-apache-spark-job-failures-privately-9b5ece62ffad?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b5ece62ffad</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 16:32:54 GMT</pubDate>
            <atom:updated>2025-07-17T16:32:54.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8yKcykY7_vRdvYBO" /><figcaption>Photo by <a href="https://unsplash.com/@realaxer?utm_source=medium&amp;utm_medium=referral">T K</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Debugging Apache Spark jobs can feel like reading hieroglyphs, endless executor logs, cryptic error traces, and unclear root causes. For data engineers working in production environments, this isn’t just a nuisance, it’s a productivity killer.</p><p>Today, many are turning to LLMs for help. But shipping sensitive Spark logs to cloud APIs like OpenAI or Anthropic isn’t always an option. Especially when you’re working with internal data or operating in regulated environments.</p><p>That’s where <strong>Model Context Protocol (MCP)</strong> and <strong>local LLMs like Ollama</strong> come in.</p><p>In this article, I’ll show you how to build a <strong>local, private MCP server</strong> with custom tools that can:</p><ul><li>Read and serve raw Spark log files</li><li>Interface with a local LLM agent using LangChain</li><li>Analyze job failures intelligently — and even suggest fixes</li><li>Display the reasoning process in a lightweight Streamlit UI</li></ul><p>By the end, you’ll have your own <strong>LLM-powered Spark log inspector</strong>, running entirely on your machine. No external APIs, no data leakage, and full control over the stack.</p><p>Let’s build it.</p><h3>Project Overview</h3><p>This project builds a local stack for analyzing Apache Spark job failures using a private LLM agent. The entire system is designed to run offline, making it ideal for teams that need to keep logs confidential or work in restricted environments.</p><p>Here’s what the stack includes:</p><ul><li><strong><em>FastMCP</em></strong><em>:</em> A lightweight MCP server implementation that lets you expose tools and resources (like log files) to LLM agents</li><li><strong><em>LangChain</em></strong><em>:</em> Used to orchestrate agent behavior, connect to MCP tools, and enable tool usage during multi-step reasoning</li><li><strong><em>Ollama</em></strong><em>:</em> Runs a local large language model (In this project we will use Qwen 3) directly on your machine, eliminating the need for API keys or cloud access</li><li><strong><em>Streamlit</em></strong><em>: </em>Provides a simple interface for selecting applications and viewing the agent’s reasoning and output</li></ul><p>By following this guide, you’ll build:</p><ul><li>An <strong>MCP server</strong> that exposes log files as resources and provides tools for listing and reading them</li><li>A <strong>LangChain-powered client agent</strong> that uses a local LLM to analyze Spark logs and suggest root causes and resolutions</li><li>A <strong>Streamlit dashboard</strong> where you can select a Spark application, run the analysis, and view step-by-step reasoning from the LLM</li></ul><p>In the next section, we’ll start with the server and define the tools and resources it needs to make the logs accessible to the agent</p><h3>Building the MCP Server</h3><p>Our MCP server will serve as the backend interface between the LLM and the log files. It will expose tools to list and read logs, and make those logs available as resources using FastMCP.</p><p>We will first start by importing the necessary libraries and initiating the MCP server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf13185e93b7f11cea01d11a823e095c/href">https://medium.com/media/bf13185e93b7f11cea01d11a823e095c/href</a></iframe><p>This will enable the LLM agents to interact with our log files. Also, we need to add explanatory descriptions of tools to inform LLM agent about capabilities of the MCP server.</p><p>After that we need to first expose our log files as a resource to an agent to interact:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/024948a181df5500123fc289aafa8765/href">https://medium.com/media/024948a181df5500123fc289aafa8765/href</a></iframe><p>This function maps file URIs (like file://logs/app-123/executor.log) to local files. The agent can call this internally when resolving a read_logs request. We will read log files one by one for every application as necessary so that we will define a resource uri for every .log file in the system.</p><p>Generally, an Apache Spark log file would have at least one log for a single executor and the overall folder format of Apache Spark logs are like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVgvmt7laVWhra3UpVTqPw.png" /></figure><p>If you do not already have log files, you can simulate it or you can just use <a href="https://github.com/logpai/loghub">this Github repository</a>. There are about 150 different Spark application logs to use. I will use only 3 of them for illustration purposes in this project.</p><p>After defining our resource, we need tools to interact with them. We will define a tool to get a list of log files for a specific applications and another tool to retrieve the raw log files themselves:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/908edb83bbc561d4369555d03c352d62/href">https://medium.com/media/908edb83bbc561d4369555d03c352d62/href</a></iframe><p>Finally, we need a small code block to run our MCP server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1195faec0f98a5f38df399d06a17a98/href">https://medium.com/media/a1195faec0f98a5f38df399d06a17a98/href</a></iframe><p>We start the server using streamable-http transport on localhost:9000. This allows LangChain clients to connect over HTTP.</p><p>Now that the server is ready, we can start building our LLM agent to interact with it.</p><h3>Building the Client Agent</h3><p>The client will use a local LLM to reason over the log files by calling the tools exposed via our MCP server.</p><p>We’ll connect to the server using MultiServerMCPClient, create an agent with LangChain, and run it on top of the locally hosted <strong>Qwen 3</strong> model via <strong>Ollama</strong>.</p><p>First, we would start with the imports and a helper function to parse the LLM output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc9ce2c1d3ed48e631ee2873f9865628/href">https://medium.com/media/cc9ce2c1d3ed48e631ee2873f9865628/href</a></iframe><p>Before diving into the logic, here’s what each library in this section is responsible for:</p><ul><li><strong><em>MultiServerMCPClient:</em></strong> This class lets us connect to one or more MCP servers from the client side. It allows LangChain agents to discover and use the tools exposed by the server. In this project, we use it to connect to our local DataInspector MCP server</li><li><strong><em>create_react_agent:</em></strong> This is a utility function from LangGraph that builds a <strong>ReAct-style agent</strong> (Reasoning + Acting). The agent will take an LLM, use the tools and handles multi-step interactions like thinking, tool usage and decision making</li><li><strong><em>ChatOllama:</em></strong><em> </em>This connects LangChain to a local Ollama instance running on your machine. You can plug in any supported model (in this case, we use qwen3:latest). The benefit here is full privacy and no external API calls</li><li><strong><em>asyncio:</em></strong><em> </em>Since all MCP and LangChain interactions are asynchronous, asyncio is used to manage and run the async code in both the terminal and the Streamlit app later</li></ul><p>After that, we need to have some kind of a parser function to organize the raw output coming from the react thought chain. The parse_ai_response function takes the raw state returned by the agent and extracts each meaningful step the model took during its reasoning. This includes:</p><ul><li><strong><em>Thoughts:</em></strong><em> </em>Each time the model “thinks” about what tool to use</li><li><strong><em>Tool Calls:</em></strong> The tools invoked and the arguments used</li><li><strong><em>Observations:</em></strong> The responses returned by the tools</li><li><strong><em>Final Thought:</em></strong> The model’s final answer after completing all reasoning steps</li></ul><p>After building the helper function and importing necessary libraries we can now initialize our private llm using ollama (we will use qwen3 in this case) and build our core logic that is callable from a streamlit ui:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4362f756e388a0511236323c7595ca9/href">https://medium.com/media/a4362f756e388a0511236323c7595ca9/href</a></iframe><p>This will return the llm’s steps that it needs to be take, the tools that it called, observations it has made and the final output of the model.</p><p>Thats it. Now we have a fully private llm that can interact with the tools that we have defined. We can now build a nice ui to it so that users can interact more easily.</p><h3>Building the Streamlit UI</h3><p>I will not go into the much of the details of the streamlit ui so much since it is user dependant and it should be customized according to the user requirements. However, while working with the asynchronous functions streamlit can be a bit of a headache and you need to use a bit of workarounds.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15407622d814abeba261a1f1b1e0a1df/href">https://medium.com/media/15407622d814abeba261a1f1b1e0a1df/href</a></iframe><p>You need to add a small code block like from line 17–23 to call your asynchronous functions in another thread. Since streamlit also works on asynchronous calls itself, it wont let you open another event loop inside an application so this trick would be necessary for now at least until they bring support for these kinds of applications.</p><p>This application would search for your log directory to find which applications there are, creates some dropbox for selection and creates an analyze button to apply the application. Then, it would display the thought process and the final result from the log files provided like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rf8OVuVMPH1_djbuhfCusw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RT3Qgo0705JATOHc9BNTw.png" /></figure><p>Thats it. Now you have a template for building an mcp server and using your local llms for a real data engineering use case.</p><h3>How to run the full stack?</h3><ul><li>You need to first download your Ollama model. It will be running on the background if you have already Ollama Desktop is installed. If you are not installed Ollama Desktop i highly recommend it.</li><li>Then, you need to fire up your server. I had used uv package manager for it so ‘uv run server.py’ is enough. If you don’t use the uv package manager you can just run the server script as its a normal python script but i highly recommend using uv. I will add another article about it if you want me to do in the comments section!</li><li>After that, you can fire up your frontend with ‘streamlit run app.py’ and start using it</li></ul><h3>Limitations and Future work</h3><p>Of course, at this point this is just a PoC level implementation for a specific use case (for analyzing Apache Spark logs). However, you can change the use case by adding different data as your resources, you can add different tools, such as you can connect your databases, your APIs etc.</p><p>One thing to mention is that local LLMs generally small since it is hard to find a powerful computer to run the big models and this affects the performance. I would suggest using models that is in general a mid size model like 30B+ if possible. But if you do not want to use local models, you can switch the client to use some API providers like OpenAI or Google Gemini. It is up to the requirements of your project and that the beauty of the MCP servers, you can just bring your own LLM models.</p><h3>Conclusion</h3><p>We just walked through building a complete, private, and extensible LLM-powered system to analyze Apache Spark logs using MCP, LangChain, and Ollama.</p><p>This project serves as a flexible template, whether you’re debugging logs, inspecting data pipelines, or building internal developer tools. The best part? You’re in full control of your data and your models.</p><p>Here’s what you now have:</p><ul><li>An MCP server that serves your data as tools and resources</li><li>A local agent that thinks and acts using your own LLM</li><li>A simple UI that shows the entire reasoning process, step by step</li></ul><p>You can extend this in many directions:</p><ul><li>Add new tools to query databases, trigger alerts, or summarize reports</li><li>Plug in different local or cloud-based LLMs</li><li>Use it to debug other log types or ETL pipelines</li></ul><p>This is the kind of architecture that makes local-first, privacy-aware AI practical for real-world engineering tasks. I hope it inspires you to build your own agents for your workflows.</p><p>If you enjoyed this, feel free to leave a comment — I’m planning to share more use cases and deep dives into MCP, Ollama, and advanced LLM toolchains soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b5ece62ffad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up a Local Apache Spark Cluster for Data Engineering Projects]]></title>
            <link>https://medium.com/@fatikir15/how-to-set-up-a-local-apache-spark-cluster-for-data-engineering-projects-e4fe77736fd8?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4fe77736fd8</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 16:27:28 GMT</pubDate>
            <atom:updated>2025-02-17T16:27:28.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Xbm6hR7larOSj9M" /><figcaption>Photo by <a href="https://unsplash.com/@cgbriggs19?utm_source=medium&amp;utm_medium=referral">Chris Briggs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Apache Spark has become a powerhouse in modern data engineering, enabling large-scale data processing with speed and efficiency. Whether you’re working with batch processing, real-time streaming, or machine learning workloads, Spark’s distributed computing capabilities make it an essential tool in the data engineer’s toolkit.</p><p>While cloud-based Spark clusters are widely used in production, setting up a <strong>local Apache Spark cluster</strong> can be invaluable for development, testing, and learning. A local environment allows you to experiment with Spark’s architecture, debug applications efficiently, and prototype data pipelines without incurring cloud costs.</p><p>In this guide, we’ll walk through the process of setting up a standalone Apache Spark cluster on your local machine.</p><p>By the end of this article, you’ll have a fully functional local Spark cluster, ready to support your data engineering projects. Let’s get started after a brief overview of the components!</p><h3>Understanding Spark Components</h3><p>Apache Spark follows a <strong>master-slave architecture</strong>, where a <strong>Master Node</strong> manages multiple <strong>Worker Nodes</strong> that execute tasks in parallel. This distributed approach allows Spark to handle large-scale data efficiently.</p><p><strong>Key Components of a Spark Cluster</strong></p><ul><li><strong>Master Node</strong> — Acts as the cluster manager, assigning tasks to worker nodes and monitoring execution.</li><li><strong>Worker Nodes</strong> — Execute Spark tasks. Each worker can run multiple <strong>Executors</strong>, which are independent processes that handle tasks in parallel.</li><li><strong>Application Master (Driver)</strong> — Manages each Spark job, coordinates execution, and aggregates results.</li><li><strong>History Server</strong> — Logs and tracks completed Spark applications, helping with debugging and performance tuning.</li><li><strong>Spark UI</strong> — A built-in web interface for real-time monitoring of jobs, stages, and resource usage.</li></ul><p>When a Spark job is submitted:</p><ol><li>The <strong>Master Node</strong> assigns tasks to <strong>Worker Nodes</strong>.</li><li><strong>Executors</strong> on workers process data in parallel.</li><li>The <strong>Driver</strong> coordinates execution.</li><li>The <strong>Spark UI</strong> provides real-time monitoring.</li><li>The <strong>History Server</strong> stores logs for analysis.</li></ol><p>Understanding these components and the workflow will help you set up and optimize your local Spark cluster. Now, let’s move on to the setup!</p><h3>Setting Up the Cluster</h3><p>We will use <strong>Docker Compose </strong>for the cluster setup. This approach makes it easy to configure, deploy, and manage multiple Spark services in isolated containers. We can then use this setup for multiple projects and spark jobs.</p><p><strong>Project Structure</strong></p><pre>pyspark_cases/<br>│── pi_estimator/<br>│   │── conf/<br>│   │   ├── spark-defaults.conf<br>│   │── Dockerfile<br>│   │── main.py<br>│   │── requirements.txt<br>│── .env<br>│── docker-compose.yml</pre><p><em>pyspark_cases </em>folder will be our main folder to store our all pyspark applications that we want to submit. In this main folder we will have required environmental variables that are common in all projects. Also, the <em>docker-compose.yml</em> file that will be used to create the spark cluster will reside here.</p><p><em>pi_estimator</em> folder would be an example pyspark project with general components that are required to run a pyspark application. We will submit this project to the cluster as an example.</p><p>Inside of the <em>pi_estimator</em> and for a generic pyspark project, the required files would be as follows:</p><ul><li>A <em>Dockerfile</em> to dockerize the spark job and add it to the docker-compose network to submit the application to the cluster</li><li>Application source files to submit (represented as <em>main.py</em>)</li><li><em>requirements.txt</em> file to install necessary required modules</li><li><em>spark-defaults.conf</em> to adjust default configurations for the spark application.</li></ul><p><strong>Creating the Spark Application</strong></p><p>Before we setup the cluster, we should create a spark job to run. This application would be a pi estimator for our case but you will add your own application for this part to run.</p><pre>from random import random<br>from operator import add<br>from pyspark.sql import SparkSession<br><br>spark = (<br>    SparkSession.builder.appName(&quot;PiEstimator&quot;)<br>    .getOrCreate()<br>)<br><br>sc = spark.sparkContext<br>n = 10000000<br><br>def f(_):<br>    x = random() * 2 - 1<br>    y = random() * 2 - 1<br>    return 1 if x ** 2 + y ** 2 &lt;= 1 else 0<br><br>count = sc.parallelize(range(1, n + 1), 2).map(f).reduce(add)<br>print(&quot;Pi is roughly %f&quot; % (4.0 * count / n))<br><br>spark.stop()</pre><p>Then, we would need to create a <em>requirements.txt</em> file. We do not need to add any modules in this file since our basic app does not need any extra modules to run but you can replace this your <em>requirements.txt</em> file. You can create a <em>requirements.txt</em> file by running this command:</p><pre>pip freeze &gt; requirements.txt</pre><p>After that, we would create a configuration file. This is required for setting up the history server to monitor and inspect the logs of finished applications. Also, you can add more settings to your specific needs in this file.</p><pre>spark.eventLog.enabled true<br>spark.eventLog.dir file:/opt/spark/spark-events<br>spark.history.fs.logDirectory file:/opt/spark/spark-events<br>spark.history.retainedApplications 10<br>spark.history.ui.port 18080</pre><p>These settings will set a directory to enable and write the logs for the latest 10 application runs. History logs are disabled by default so we need to enable them manually like this.</p><p>Finally, we will create the Dockerfile to containarize our application and add it to the docker-compose network to run with the Spark cluster.</p><pre># Use an official Spark base image with Python support<br>FROM apache/spark:python3<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Change to root to install packages<br>USER root<br><br># Copy the Python dependencies file to the container<br>COPY requirements.txt /app/<br><br># Install required Python packages<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy the Spark configuration file<br>COPY conf/spark-defaults.conf /opt/spark/conf/spark-defaults.conf<br><br># Copy the source code of the Spark job into the container<br>COPY ./ /app/<br><br># Ensure the spark-events directory exists before changing ownership<br>RUN mkdir -p /opt/spark/spark-events &amp;&amp; chown -R spark:spark /app /opt/spark/spark-events<br><br># Switch back to the spark user<br>USER spark<br><br># Command to run the Spark job script<br>CMD [&quot;/opt/spark/bin/spark-submit&quot;, &quot;--master&quot;, &quot;spark://spark-master:7077&quot;, &quot;./main.py&quot;]</pre><p>This <em>Dockerfile</em> will install requirements, create necessary directories for history server and submit the job to the spark cluster. If your spark job has different main file, you should change the <em>“./main.py”</em> in the last command with your application main file.</p><p>Now, everything is ready for the Spark Application we can fire up our cluster.</p><p><strong>Creating the Spark Cluster</strong></p><p>Creating a docker-compose.yamls file is pretty straitforward. You just need to define a network definition to enable communication between containers, add some volume to store the log data and define the services.</p><pre>networks:<br>  bridge:<br>    driver: bridge<br><br>volumes:<br>  spark-events:<br><br><br>services:<br><br>  spark-master:<br>    image: apache/spark:python3<br>    ports:<br>      - &quot;8080:8080&quot;<br>      - &quot;7077:7077&quot;<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.master.Master --ip spark-master --port 7077 --webui-port 8080 &amp;&amp; tail -f /dev/null&quot;<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-master<br><br>  spark-worker-1:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077 &amp;&amp; tail -f /dev/null&quot;<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-worker-1<br><br>  spark-worker-2:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077 &amp;&amp; tail -f /dev/null&quot;<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-worker-2<br><br>  spark_job:<br>    build: ${SPARK_JOB_PATH}<br>    depends_on:<br>      - spark-master<br>      - spark-worker-1<br>      - spark-worker-2<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      - bridge<br>    environment:<br>      - SPARK_MASTER_URL=spark://spark-master:7077<br><br>  spark-history-server:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/sbin/start-history-server.sh &amp;&amp; tail -f /dev/null&quot;<br>    ports:<br>      - &quot;18080:18080&quot;<br>    environment:<br>      - SPARK_HISTORY_OPTS=-Dspark.history.fs.logDirectory=file:/opt/spark/spark-events -Dspark.history.ui.port=18080<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-history-server</pre><p>This is a long chuck of code but we will go step by step:</p><p>First the network definition:</p><pre>networks:<br>  bridge:<br>    driver: bridge</pre><p>This will enable our services to communicate on a common ground. Next, we will define a volume to store our log data:</p><pre>volumes:<br>  spark-events:</pre><p>This will create a volume named <em>spark-events</em> that can be used by all our services.</p><p>Finally, we will define our cluster under <em>services</em> section:</p><pre>  spark-master:<br>    image: apache/spark:python3<br>    ports:<br>      - &quot;8080:8080&quot;<br>      - &quot;7077:7077&quot;<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.master.Master --ip spark-master --port 7077 --webui-port 8080 &amp;&amp; tail -f /dev/null&quot;<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-master</pre><p>This will create our master node and assign the volume and the network that we created. Also, <em>ports</em> section is to provide a port mapping that will allow us to reach the docker network from our computer using localhost.</p><p>Next comes the worker nodes:</p><pre>  spark-worker-1:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077 &amp;&amp; tail -f /dev/null&quot;<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-worker-1<br><br>  spark-worker-2:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077 &amp;&amp; tail -f /dev/null&quot;<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-worker-2</pre><p>As you can see, it is not much different from the master node. Only important differences are that we add a <em>depends_on</em> in the workers, this is to make worker nodes up and running only after the master node is up and running. Also, we specify the Java class as <em>Worker</em> instead of <em>Master</em> in the command part to run the service as a worker node.</p><p>We have created only 2 worker nodes but you can create more with the same logic.</p><p>Next, our application would be added like this:</p><pre>  spark_job:<br>    build: ${SPARK_JOB_PATH}<br>    depends_on:<br>      - spark-master<br>      - spark-worker-1<br>      - spark-worker-2<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      - bridge<br>    environment:<br>      - SPARK_MASTER_URL=spark://spark-master:7077</pre><p>In the build path, we will get our value from the environment to easily change between different projects later. The path would be the relative path of the <em>Dockerfile</em> of our pyspark application. We can define this in the <em>.env</em> file later.</p><p>Since our application should start after the spark cluster is started, depends_on section consists of both the master node and the worker node.</p><p>Finally, we can define our history server and our docker-compose file is done. The service definition would be familiar by now from the previous parts:</p><pre>  spark-history-server:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/sbin/start-history-server.sh &amp;&amp; tail -f /dev/null&quot;<br>    ports:<br>      - &quot;18080:18080&quot;<br>    environment:<br>      - SPARK_HISTORY_OPTS=-Dspark.history.fs.logDirectory=file:/opt/spark/spark-events -Dspark.history.ui.port=18080<br>    volumes:<br>      - spark-events:/opt/spark/spark-events<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-history-server</pre><p>After adding this as well, one last thing is to create an environment for our cluster. .env file should look like this:</p><pre>SPARK_JOB_PATH=./pi_estimator</pre><p>You can add your environment variables in here as well for the spark cluster.</p><p>And thats it. Now you have a local Apache Spark cluster.</p><p><strong>Running the Pyspark Application</strong></p><p>You can your application now and fire up your cluster via:</p><pre>docker-compose up -d --build</pre><p>After that you can see the Spark UI at localhost:8080 and you can see yor finished applications at localhost:18080</p><p>When you finish your work don’t forget the shut down the cluster and the application via:</p><pre>docker-compose down</pre><p>And thats it.</p><h3>Conclusion</h3><p>Congratulations! You now have a fully functional <strong>local Apache Spark cluster</strong> running with <strong>Docker Compose</strong>. This setup provides a <strong>lightweight, scalable, and reusable</strong> environment for developing and testing Spark applications without relying on cloud resources.</p><p>By following this guide, you have:<br>- Set up a <strong>Spark Master and Worker nodes</strong> in a distributed architecture.<br>- Configured a <strong>history server</strong> to track completed applications.<br>- Created a <strong>containerized Spark job</strong> and submitted it to the cluster.</p><p>This local setup serves as a <strong>solid foundation</strong> for further exploration. You can now experiment with <strong>different Spark configurations</strong>, run more complex data pipelines, or even extend this setup by integrating it with <strong>HDFS, Kafka, or cloud storage</strong>.</p><p>As you continue working on your data engineering projects, this environment will allow you to <strong>iterate quickly, troubleshoot efficiently, and optimize your Spark applications</strong> in a controlled setting.</p><p>If you have any thoughts, questions, or improvements, feel free to share them in the comments. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4fe77736fd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking Locally, Acting Privately: Building a Reasoning-Powered Q&A App with Deepseek R1 using…]]></title>
            <link>https://medium.com/@fatikir15/thinking-locally-acting-privately-building-a-reasoning-powered-q-a-app-with-deepseek-r1-using-3d487627251b?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d487627251b</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 23:21:44 GMT</pubDate>
            <atom:updated>2025-01-24T23:21:44.634Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Thinking Locally, Acting Privately: Building a Reasoning-Powered Q&amp;A App with Deepseek R1 using Ollama, Streamlit and RAG</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fTWZ2PvEp9L_0zkf" /><figcaption>Photo by <a href="https://unsplash.com/@ninjason?utm_source=medium&amp;utm_medium=referral">Jason Leung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In an era where artificial intelligence (AI) is becoming increasingly integrated into our daily lives, one concern remains at the forefront: <strong>privacy</strong>. As powerful as cloud-based AI systems are, they often come with a significant trade-off — your data is processed on remote servers, raising questions about security and confidentiality. For many applications, especially those handling sensitive information, this simply isn’t acceptable. What if we could harness the power of AI while keeping everything local, ensuring that your data never leaves your machine? This is where <strong>local AI</strong> shines, and it’s the foundation of the project we’re about to explore.</p><p>Enter <strong>Deepseek R1</strong>, a cutting-edge reasoning model designed to tackle complex questions with human-like logic. Unlike traditional language models that focus solely on pattern recognition, Deepseek R1 is built to <strong>think</strong>. It doesn’t just retrieve information — it reasons through it, making it an ideal choice for question-answering (Q&amp;A) and retrieval-augmented generation (RAG) applications. But why is reasoning so important in these contexts? In Q&amp;A systems, users don’t just want answers; they want <strong>insightful, context-aware responses</strong> that demonstrate understanding. A reasoning model like Deepseek R1 bridges the gap between raw data and meaningful answers, making it a game-changer for AI-driven interactions.</p><p>In this project, we will combine the privacy of local AI with the intelligence of Deepseek R1 to create a <strong>fully local, reasoning-powered Q&amp;A bot</strong>. Using <strong>Ollama</strong> for local model execution, <strong>ChromaDB</strong> for efficient document storage and retrieval, and <strong>Streamlit</strong> for a user-friendly interface, we will build a system that allows you to load documents, ask questions, and receive answers — all while keeping your data secure. But that’s not all. The app also lets you <strong>see the thinking process of the model</strong> and the source texts it uses to generate responses, providing transparency and deeper insights into how the AI works.</p><p>By the end of this article, you’ll have a clear understanding of how to build your own privacy-focused Q&amp;A bot, and how to leverage modern tools like Ollama and ChromaDB to create powerful, local AI solutions. The final app would be look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLx5J5CZgLOhB18TU1dgNw.png" /></figure><h3>Deep Dive Into Project Architecture</h3><p>Before we dive into the code, let’s quickly cover the <strong>setup requirements</strong> to get this project up and running:</p><p><strong>Ollama</strong>: You’ll need to run Ollama locally with two key models:</p><ul><li><strong>deepseek-r1</strong>: The reasoning-focused language model that powers the Q&amp;A capabilities.</li><li><strong>nomic-embed-text</strong>: The embedding model used for tokenizing and retrieving relevant document chunks.</li></ul><p>In order to setup ollama for this project, just download the application and use these commands:</p><pre>ollama pull deepseek-r1<br>ollama pull nomic-embed-text<br>ollama serve</pre><p>these commands will download the deepseek-R1 7b for the reasoning and nomic-embed-text for creating embeddings from our documents. Last command will create a local server for us to interact with these models.</p><p><strong>Python Dependencies</strong>: The project relies on a few Python libraries, which you can install via requirements.txt. These include chromadb for vector storage, streamlit for the UI, and other supporting tools. The requirements file for this project would be in the github link at the end of the article.</p><p>You can load the required modules via:</p><pre>pip install requirements.txt</pre><p>Once the environment is set up, the project follows a straightforward yet powerful workflow: <strong>document ingestion → retrieval → question-answering → user interface</strong>. Each step is designed to ensure privacy, efficiency, and intelligent reasoning. Let’s break it down:</p><ol><li><strong>Document Ingestion</strong>: Your files are loaded, processed, and stored locally in <strong>ChromaDB</strong>, a vector database that ensures your data never leaves your machine.</li><li><strong>Retrieval</strong>: When you ask a question, the app retrieves the most relevant chunks of text from the database using semantic search.</li><li><strong>Question-Answering</strong>: The retrieved chunks are passed to <strong>Deepseek R1</strong>, which processes the information and generates intelligent, context-aware answers.</li><li><strong>User Interface</strong>: The <strong>Streamlit app</strong> ties everything together, providing a clean and intuitive interface for interacting with the bot, asking questions, and exploring the model’s reasoning process.</li></ol><p>This modular architecture not only ensures privacy but also makes the system flexible and easy to extend. Let’s explore each component in detail.</p><p>We will start with the ingestion process. <strong>ingest.py</strong> would be something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41057baaa09d56b11ce345874e29a075/href">https://medium.com/media/41057baaa09d56b11ce345874e29a075/href</a></iframe><p>Imports and dependencies:</p><pre>import os<br>import uuid<br>from langchain_community.document_loaders import PyPDFLoader<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.vectorstores import Chroma<br>from langchain_community.embeddings import OllamaEmbeddings</pre><ul><li><strong>PyPDFLoader</strong>: Used to load and extract text from PDF files.</li><li><strong>RecursiveCharacterTextSplitter</strong>: Splits text into smaller chunks for processing.</li><li><strong>Chroma</strong>: The vector database where processed documents are stored.</li><li><strong>OllamaEmbeddings</strong>: Generates embeddings for the text using the nomic-embed-text model.</li><li><strong>uuid</strong>: Generates unique identifiers for document chunks.</li></ul><p>Initialize embeddings and text splitter:</p><pre>embeddings = OllamaEmbeddings(model=&quot;nomic-embed-text&quot;)<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=3000,<br>    chunk_overlap=500,<br>    length_function=len,<br>    is_separator_regex=False,<br>)</pre><ul><li><strong>OllamaEmbeddings</strong>: Uses the nomic-embed-text model to generate embeddings. This model is run locally via Ollama, ensuring privacy.</li><li><strong>RecursiveCharacterTextSplitter</strong>:</li><li>chunk_size=3000: Splits text into chunks of 3000 characters.</li><li>chunk_overlap=500: Ensures a 500-character overlap between chunks to maintain context.</li><li>length_function=len: Uses Python’s len function to calculate chunk sizes.</li><li>is_separator_regex=False: Indicates that the text splitter does not use regex for splitting.</li></ul><p>Load and Process PDF Files:</p><pre>pdf_files = [f for f in os.listdir(docs_dir) if f.endswith(&quot;.pdf&quot;)]<br>if not pdf_files:<br>    raise ValueError(f&quot;No PDF files found in {docs_dir}&quot;)<br><br>all_docs = []<br>for pdf_file in pdf_files:<br>    file_path = os.path.join(docs_dir, pdf_file)<br>    loader = PyPDFLoader(file_path)<br>    pages = loader.load()</pre><ul><li>The script checks for PDF files in the specified directory. If none are found, it raises an error.</li><li><strong>PyPDFLoader</strong>: Loads each PDF file and extracts its pages as separate documents to create separate metadata about every single page</li><li><strong>pages</strong>: A list of Document objects, where each object represents a page from the PDF.</li></ul><p>Add Metadata to Pages:</p><pre>for page_num, page in enumerate(pages, start=1):<br>    page.metadata.update({<br>        &quot;source&quot;: pdf_file,<br>        &quot;page_number&quot;: page_num,<br>        &quot;chunk_id&quot;: str(uuid.uuid4())[:8]<br>    })</pre><ul><li>Each page is enriched with metadata to find the source file for the text chunks:</li><li><strong>source</strong>: The name of the PDF file.</li><li><strong>page_number</strong>: The page number within the PDF.</li><li><strong>chunk_id</strong>: A unique identifier for the chunk (truncated UUID).</li></ul><p>Split Pages Into Chunks:</p><pre>chunks = text_splitter.split_documents(pages)<br>all_docs.extend(chunks)</pre><ul><li>The RecursiveCharacterTextSplitter splits each page into smaller chunks based on the specified chunk_size and chunk_overlap.</li><li>The chunks are added to the all_docs list, which accumulates all processed documents.</li></ul><p>Store Documents in ChromaDB:</p><pre>Chroma.from_documents(<br>    documents=all_docs,<br>    embedding=embeddings,<br>    persist_directory=&quot;chroma_db&quot;,<br>    collection_metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;},<br>    collection_name=&quot;main_collection&quot;<br>)</pre><ul><li><strong>Chroma.from_documents</strong>:</li><li>Ingests all processed documents into ChromaDB.</li><li>Uses the nomic-embed-text embeddings to vectorize the text.</li><li>Persists the database locally in the chroma_db directory.</li><li>Configures the collection with cosine similarity for retrieval (hnsw:space&quot;: &quot;cosine&quot;).</li><li>Names the collection &quot;main_collection&quot;.</li></ul><p>After we have structured the ingestion process with <strong>ingest.py</strong>, we can continue with how to retrieve the stored documents based on our question. We wil use <strong>retreive.py</strong> file for this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa18bae8a95c453b9f1ffe0de0975d8d/href">https://medium.com/media/aa18bae8a95c453b9f1ffe0de0975d8d/href</a></iframe><p>Imports and Dependencies:</p><pre>import os<br>from langchain_community.vectorstores import Chroma<br>from langchain_community.embeddings import OllamaEmbeddings</pre><ul><li><strong>Chroma</strong>: Used to interact with the ChromaDB vector store.</li><li><strong>OllamaEmbeddings</strong>: Generates embeddings for the query using the nomic-embed-text model.</li><li><strong>os</strong>: Used for directory operations (e.g., creating the chroma_db directory if it doesn’t exist).</li></ul><p><em>__init__</em> Method of the <em>DocumentRetreiver</em> Class:</p><pre>def __init__(self):<br>    self.embeddings = OllamaEmbeddings(model=&quot;nomic-embed-text&quot;)<br>    self.persist_dir = &quot;chroma_db&quot;<br>    <br>    # Create directory if it doesn&#39;t exist<br>    os.makedirs(self.persist_dir, exist_ok=True)<br>    <br>    # Initialize with empty collection if needed<br>    self.vector_store = Chroma(<br>        persist_directory=self.persist_dir,<br>        embedding_function=self.embeddings,<br>        collection_name=&quot;main_collection&quot;  # Fixed collection name<br>    )<br>    <br>    # Workaround for Chroma&#39;s empty DB issue<br>    if not self.vector_store.get()[&#39;documents&#39;]:<br>        self.vector_store.add_texts([&quot;Initial empty document&quot;])<br>        self.vector_store.delete(ids=[&quot;0&quot;])  # Remove placeholder</pre><ul><li><strong>self.embeddings</strong>: Initializes the OllamaEmbeddings with the nomic-embed-text model for generating query embeddings.</li><li><strong>self.persist_dir</strong>: Specifies the directory (chroma_db) where the ChromaDB data is stored.</li><li><strong>os.makedirs</strong>: Ensures the chroma_db directory exists, creating it if necessary.</li><li><strong>self.vector_store</strong>: Initializes the ChromaDB vector store with the specified persist_directory, embedding_function, and collection_name.</li><li>ChromaDB may raise errors when querying an empty collection. To avoid this, the script adds a placeholder document and immediately deletes it. This ensures the collection is properly initialized.</li></ul><p><em>query_documents</em> Method:</p><pre>def query_documents(self, query: str, k: int = 5):<br>    results = self.vector_store.similarity_search_with_score(query, k=k)<br>    <br>    formatted_results = []<br>    for doc, score in results:<br>        metadata = doc.metadata<br>        formatted_results.append({<br>            &quot;text&quot;: doc.page_content,<br>            &quot;source&quot;: metadata[&quot;source&quot;],<br>            &quot;page&quot;: metadata[&quot;page_number&quot;],<br>            &quot;chunk_id&quot;: metadata[&quot;chunk_id&quot;],<br>            &quot;score&quot;: float(score)<br>        })<br>    <br>    return formatted_results</pre><ul><li><strong>query</strong>: The user’s query string.</li><li><strong>k</strong>: The number of relevant chunks to retrieve (default is 5).</li><li><strong>similarity_search_with_score</strong>:</li><li>Queries the ChromaDB vector store for documents that are semantically similar to the query.</li><li>Returns a list of tuples, where each tuple contains a Document object and its similarity score.</li><li><strong>formatted_results</strong>:</li><li>Processes the raw results into a more user-friendly format.</li><li>Each result includes:</li><li><strong>text</strong>: The content of the document chunk.</li><li><strong>source</strong>: The name of the PDF file the chunk came from.</li><li><strong>page</strong>: The page number within the PDF.</li><li><strong>chunk_id</strong>: The unique identifier for the chunk.</li><li><strong>score</strong>: The similarity score.</li><li><strong>Return Value</strong>: A list of dictionaries, each representing a retrieved document chunk.</li></ul><p>Now that we have done the document related tasks, we are ready to build out Q&amp;A chain which will retrieve the related documents from the database and combine it with our question to get an answer and the thought process of the model while creating that result. We will use <strong>qa.py </strong>file for this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f72e5806c9cb1e2c861a3daf0bdd04b/href">https://medium.com/media/2f72e5806c9cb1e2c861a3daf0bdd04b/href</a></iframe><p>Imports and Dependencies:</p><pre>from retrieve import DocumentRetriever<br>import ollama<br>import regex as re</pre><ul><li><strong>DocumentRetriever</strong>: The class from retrieve.py that handles document retrieval.</li><li><strong>ollama</strong>: Used to interact with the local Ollama server and generate responses using Deepseek R1.</li><li><strong>regex</strong>: Used for parsing the model’s response to extract the thinking process and answer.</li></ul><p><em>QAPipeline</em> Class:</p><p><em>__init__</em> Method:</p><pre>def __init__(self):<br>    self.retriever = DocumentRetriever()</pre><ul><li>Initializes an instance of DocumentRetriever to handle document retrieval.</li><li>This ensures that the Q&amp;A pipeline has access to the vector store and can retrieve relevant chunks.</li></ul><p><em>PROMPT_TEMPLATE</em> variable:</p><pre>PROMPT_TEMPLATE = &quot;&quot;&quot;Context information:<br>    {context}<br><br>    Using the context above and your general knowledge, answer this question:<br>    Question: {question}<br><br>    Format requirements:<br><br>    - If uncertain, say &quot;The documents don&#39;t specify&quot;&quot;&quot;</pre><ul><li>This template defines the structure of the prompt sent to Deepseek R1.</li><li>It includes:</li><li><strong>{context}</strong>: The retrieved document chunks formatted as context.</li><li><strong>{question}</strong>: The user’s query.</li><li><strong>Formatting Instructions</strong>: The model is instructed to indicate uncertainty if the context doesn’t provide enough information.</li></ul><p><em>parse_response</em> Method:</p><pre>def parse_response(self, response: str) -&gt; dict:<br>    &quot;&quot;&quot;Extract thinking and answer components without &lt;answer&gt; tags&quot;&quot;&quot;<br>    # Extract thinking process<br>    think_match = re.search(r&#39;&lt;think&gt;(.*?)&lt;/think&gt;&#39;, response, re.DOTALL)<br>    <br>    # Get everything AFTER &lt;/think&gt; as the answer<br>    answer_start = response.find(&#39;&lt;/think&gt;&#39;) + len(&#39;&lt;/think&gt;&#39;)<br>    answer = response[answer_start:].strip()<br>    <br>    return {<br>        &quot;thinking&quot;: think_match.group(1).strip() if think_match else &quot;&quot;,<br>        &quot;answer&quot;: answer,<br>        &quot;raw_response&quot;: response<br>    }</pre><ul><li>This method parses the raw response from Deepseek R1 to extract the <strong>thinking process</strong> and <strong>answer</strong>.</li><li><strong>&lt;think&gt; and </strong><strong>&lt;/think&gt; Tags</strong>:</li><li>The thinking process is enclosed in &lt;think&gt; tags.</li><li>The answer is everything after the &lt;/think&gt; tag.</li><li>Return value is<strong> a </strong>dictionary containing:</li><li><strong>thinking</strong>: The model’s reasoning process.</li><li><strong>answer</strong>: The final answer.</li><li><strong>raw_response</strong>: The unparsed response for debugging.</li></ul><p><em>generate_answer</em> Method:</p><pre>def generate_answer(self, question: str, k: int = 5) -&gt; dict:<br>    &quot;&quot;&quot;Full QA workflow with enhanced output&quot;&quot;&quot;<br>    try:<br>        # Retrieve documents<br>        context_docs = self.retriever.query_documents(question, k=k)<br>        <br>        # Format context preserving full metadata<br>        context_str = &quot;\n&quot;.join(<br>            f&quot;[Document {idx+1}] {doc[&#39;source&#39;]} (Page {doc[&#39;page&#39;]}):\n{doc[&#39;text&#39;]}&quot;<br>            for idx, doc in enumerate(context_docs)<br>        )<br>        <br>        # Generate response<br>        response = ollama.generate(<br>            model=&quot;deepseek-r1:latest&quot;,<br>            prompt=self.PROMPT_TEMPLATE.format(<br>                context=context_str,<br>                question=question<br>            )<br>        )<br>        <br>        # Parse components<br>        parsed = self.parse_response(response[&#39;response&#39;])<br>        <br>        return {<br>            **parsed,<br>            &quot;sources&quot;: [<br>                {<br>                    &quot;source&quot;: doc[&quot;source&quot;],<br>                    &quot;page&quot;: doc[&quot;page&quot;],<br>                    &quot;confidence&quot;: doc[&quot;score&quot;],<br>                    &quot;full_text&quot;: doc[&quot;text&quot;]<br>                } for doc in context_docs<br>            ]<br>        }<br>        <br>    except Exception as e:<br>        return {<br>            &quot;error&quot;: str(e),<br>            &quot;thinking&quot;: &quot;&quot;,<br>            &quot;answer&quot;: &quot;Failed to generate response&quot;,<br>            &quot;sources&quot;: []<br>        }</pre><ul><li><strong>question</strong>: The user’s query.</li><li><strong>k</strong>: The number of document chunks to retrieve (default is 5).</li></ul><p><strong>Workflow</strong>:</p><p><strong>Retrieve Documents</strong>:</p><ul><li>Calls self.retriever.query_documents to retrieve relevant chunks.</li></ul><p><strong>Format Context</strong>:</p><ul><li>Combines the retrieved chunks into a single string, preserving metadata (source, page number).</li></ul><p><strong>Generate Response</strong>:</p><ul><li>Sends the formatted context and question to Deepseek R1 via Ollama.</li></ul><p><strong>Parse Response</strong>:</p><ul><li>Extracts the thinking process and answer using parse_response.</li></ul><p><strong>Return Result</strong>:</p><ul><li>Returns a dictionary containing:</li><li>The parsed response (thinking, answer, raw_response).</li><li>The sources used (source, page, confidence, full_text).</li><li>If an error occurs, the method returns a dictionary with an error message and empty/default values.</li></ul><p>By building the Q&amp;A chain, our core functionality is done. Now, we need to enclose all this logic into a easy to use UI. We will use <strong>app.py </strong>for that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47be67676e650e7d5f940fee26d81999/href">https://medium.com/media/47be67676e650e7d5f940fee26d81999/href</a></iframe><p>Import and dependencies:</p><pre>import streamlit as st<br>from qa import QAPipeline<br>from ingest import process_documents<br>import os<br>import shutil<br>import random</pre><ul><li><strong>streamlit</strong>: Used to build the web interface.</li><li><strong>QAPipeline</strong>: The class from qa.py that handles the Q&amp;A workflow.</li><li><strong>process_documents</strong>: The function from ingest.py that processes and ingests uploaded documents.</li><li><strong>os and </strong><strong>shutil</strong>: Used for file and directory operations (e.g., creating directories, deleting files).</li><li><strong>random</strong>: Used to generate unique keys for Streamlit components.</li></ul><p><em>reset_database Function:</em></p><pre>def reset_database():<br>    &quot;&quot;&quot;Clear all stored data and reset session state&quot;&quot;&quot;<br>    try:<br>        if &#39;qa_pipeline&#39; in st.session_state:<br>            st.session_state.qa_pipeline.retriever.vector_store.delete_collection()<br>        <br>        if os.path.exists(&quot;documents&quot;):<br>            shutil.rmtree(&quot;documents&quot;)<br>            os.makedirs(&quot;documents&quot;)<br>        <br>        st.session_state.qa_pipeline = QAPipeline()<br>        st.success(&quot;Database cleared successfully!&quot;)<br>    except Exception as e:<br>        st.error(f&quot;Error clearing database: {str(e)}&quot;)</pre><ul><li>This function resets the system by:</li><li>Deleting the ChromaDB collection.</li><li>Removing the documents directory and recreating it.</li><li>Reinitializing the QAPipeline in the session state.</li></ul><p>Initialize Session State:</p><pre>if &#39;qa_pipeline&#39; not in st.session_state:<br>    st.session_state.qa_pipeline = QAPipeline()<br>if &#39;ingested&#39; not in st.session_state:<br>    st.session_state.ingested = False<br>if &#39;history&#39; not in st.session_state:<br>    st.session_state.history = []</pre><ul><li><strong>st.session_state</strong>: Used to persist data across app reruns.</li><li><strong>qa_pipeline</strong>: Stores the QAPipeline instance.</li><li><strong>ingested</strong>: Tracks whether documents have been ingested.</li><li><strong>history</strong>: Stores the history of questions and answers.</li></ul><p>Sidebar for Column Management:</p><pre>with st.sidebar:<br>    st.header(&quot;Document Management&quot;)<br>    uploaded_files = st.file_uploader(<br>        &quot;Upload PDF documents&quot;, <br>        type=[&quot;pdf&quot;],<br>        accept_multiple_files=True<br>    )<br>    <br>    col1, col2 = st.columns(2)<br>    with col1:<br>        if st.button(&quot;Ingest Documents&quot;):<br>            if uploaded_files:<br>                try:<br>                    reset_database()<br>                    os.makedirs(&quot;documents&quot;, exist_ok=True)<br>                    for file in uploaded_files:<br>                        with open(os.path.join(&quot;documents&quot;, file.name), &quot;wb&quot;) as f:<br>                            f.write(file.getbuffer())<br>                    with st.spinner(&quot;Processing documents...&quot;):<br>                        process_documents()<br>                        st.session_state.ingested = True<br>                        st.success(f&quot;Ingested {len(uploaded_files)} documents!&quot;)<br>                except Exception as e:<br>                    st.error(f&quot;Error processing documents: {str(e)}&quot;)<br>            else:<br>                st.warning(&quot;Please upload documents first&quot;)<br>    with col2:<br>        st.button(&quot;Clear Database&quot;, on_click=reset_database)</pre><ul><li><strong>st.sidebar</strong>: Creates a sidebar for document management.</li><li><strong>st.file_uploader</strong>: Allows users to upload multiple PDF files.</li><li><strong>Ingest Documents Button</strong>:</li><li>Resets the database.</li><li>Saves uploaded files to the documents directory.</li><li>Calls process_documents to ingest the files into ChromaDB.</li><li>Updates the ingested flag in the session state.</li><li><strong>Clear Database Button</strong>: Calls reset_database to clear all stored data.</li></ul><p>Display Chat History:</p><pre>for qa in st.session_state.history:<br>    with st.expander(f&quot;Q: {qa[&#39;question&#39;]}&quot;, expanded=False):<br>        # Thinking Process Section<br>        with st.container():<br>            st.markdown(&quot;#### 🧠 Thinking Process of the Assistant&quot;)<br>            st.markdown(qa[&#39;thinking&#39;])<br>            st.markdown(&quot;---&quot;)<br>        <br>        # Final Answer Section<br>        with st.container():<br>            st.markdown(&quot;#### 📝 Final Answer&quot;)<br>            st.markdown(qa[&#39;answer&#39;])<br>            st.markdown(&quot;---&quot;)<br>        <br>        # Source Documents Section<br>        if qa[&quot;sources&quot;]:<br>            st.markdown(&quot;#### 🔍 Source Documents&quot;)<br>            for idx, source in enumerate(qa[&quot;sources&quot;], 1):<br>                with st.container():<br>                    st.write(f&quot;📄 **{source[&#39;source&#39;]}** (Page {source[&#39;page&#39;]})&quot;)<br>                    st.text_area(<br>                        &quot;Relevant text excerpt:&quot;,<br>                        value=source[&#39;full_text&#39;],<br>                        key=f&quot;source_{idx}_{random.randint(0, 999999)}&quot;,<br>                        disabled=True<br>                    )</pre><ul><li>Displays the chat history using st.expander for each question-answer pair.</li><li><strong>Thinking Process</strong>: Shows the model’s reasoning process.</li><li><strong>Final Answer</strong>: Displays the generated answer.</li><li><strong>Source Documents</strong>: Lists the source documents used, including the source file, page number, and relevant text excerpt.</li></ul><p>Question Input:</p><pre>question = st.chat_input(<br>    &quot;Ask a question about your documents:&quot;,<br>    disabled=not st.session_state.ingested<br>)</pre><ul><li><strong>st.chat_input</strong>: Provides a text input for users to ask questions.</li><li><strong>Disabled State</strong>: The input is disabled until documents are ingested.</li></ul><p>Process Question:</p><pre>if question and st.session_state.ingested:<br>    # Add to history immediately<br>    st.session_state.history.append({<br>        &quot;question&quot;: question,<br>        &quot;thinking&quot;: &quot;&quot;,<br>        &quot;answer&quot;: &quot;Processing...&quot;,<br>        &quot;sources&quot;: []<br>    })<br>    <br>    try:<br>        with st.status(&quot;🧠 Processing your question...&quot;, expanded=True) as status:<br>            st.write(&quot;🔍 Retrieving relevant documents...&quot;)<br>            result = st.session_state.qa_pipeline.generate_answer(question)<br>            status.update(label=&quot;✅ Processing complete&quot;, state=&quot;complete&quot;)<br>        <br>        # Update history with results<br>        st.session_state.history[-1] = {<br>            &quot;question&quot;: question,<br>            &quot;thinking&quot;: result.get(&#39;thinking&#39;, &#39;&#39;),<br>            &quot;answer&quot;: result.get(&#39;answer&#39;, &#39;No answer generated&#39;),<br>            &quot;sources&quot;: result.get(&#39;sources&#39;, [])<br>        }<br>        <br>        st.rerun()<br>        <br>    except Exception as e:<br>        st.error(f&quot;Error generating answer: {str(e)}&quot;)<br>        st.session_state.history.pop()</pre><ul><li><strong>Immediate Feedback</strong>: Adds the question to the history with a “Processing…” placeholder.</li><li><strong>Processing Status</strong>:</li><li>Uses st.status to show the progress of the Q&amp;A workflow.</li><li>Updates the status once processing is complete.</li><li><strong>Update History</strong>: Replaces the placeholder with the actual results.</li></ul><p>And thats it. What a journey!</p><h3>Future Enhancements</h3><p>While this project already delivers a powerful, privacy-focused Q&amp;A bot, there’s always room for improvement. Here are some potential enhancements and features that could take it to the next level:</p><h4>1. Support for More Document Formats</h4><p>Currently, the system supports PDF files, but expanding to other formats like Word documents, Markdown, or even plain text files would make it more versatile. This would allow users to work with a wider range of documents without needing to convert them first.</p><h4>2. Integration with Other Local LLMs</h4><p>Deepseek R1 is a fantastic reasoning model, but integrating support for other local LLMs (e.g., LLaMA, Mistral, or Falcon) would give users more flexibility. This could be done through a modular architecture, allowing users to choose their preferred model based on their needs.</p><h4>3. Enhanced UI Features</h4><p>The Streamlit interface is already user-friendly, but additional features could improve the experience:</p><ul><li><strong>Searchable History</strong>: Allow users to search through past questions and answers.</li><li><strong>Customizable Themes</strong>: Add support for light/dark modes or custom themes.</li><li><strong>Export Functionality</strong>: Enable users to export answers, sources, or the entire chat history.</li></ul><h4>4. Advanced Retrieval Techniques</h4><p>Improving the retrieval process could enhance the quality of answers:</p><ul><li><strong>Hybrid Search</strong>: Combine keyword-based and semantic search for better results.</li><li><strong>Reranking</strong>: Use a smaller model to rerank retrieved chunks for improved relevance.</li></ul><h4>5. Scalability Improvements</h4><p>As the system grows, scalability will become increasingly important. Potential improvements include:</p><ul><li><strong>Efficient Indexing</strong>: Optimize ChromaDB or explore alternative vector databases for faster retrieval with large datasets.</li><li><strong>Batch Processing</strong>: Allow bulk ingestion of documents to handle large collections more efficiently.</li><li><strong>Distributed Processing</strong>: Explore distributed computing frameworks (e.g., Ray or Dask) to handle larger workloads.</li></ul><h3>Conclusion</h3><p>Building a <strong>local, privacy-focused Q&amp;A bot</strong> using <strong>Deepseek R1</strong>, <strong>Ollama</strong>, <strong>ChromaDB</strong>, and <strong>Streamlit</strong>has been an exciting journey. This project demonstrates how modern AI tools can be combined to create powerful, secure, and user-friendly applications that respect user privacy while delivering intelligent, reasoning-based answers.</p><p>By leveraging <strong>Deepseek R1’s advanced reasoning capabilities</strong>, we’ve built a system that doesn’t just retrieve information — it <strong>thinks through it</strong>, providing insightful and context-aware responses. The use of <strong>Ollama</strong> ensures that all processing happens locally, keeping your data secure and private. Meanwhile, <strong>ChromaDB</strong> enables efficient document storage and retrieval, and <strong>Streamlit</strong> provides a clean, intuitive interface for interacting with the bot.</p><p>Throughout this article, we’ve walked through the entire process — from <strong>document ingestion</strong> and <strong>retrieval</strong> to <strong>question-answering</strong> and <strong>UI integration</strong>. We’ve also explored the importance of <strong>reasoning models</strong> in Q&amp;A applications and highlighted how this project can be extended with features like <strong>support for more document formats</strong>, <strong>integration with other local LLMs</strong>, and <strong>scalability improvements</strong>.</p><p>Feel free to check out the <a href="https://github.com/firefly-cmd/qa-agent-deepseek">GitHub repository</a> for the full code and try building your own version. If you have any feedback, suggestions, or ideas for improvement, <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">I’d love to hear from you</a>. Together, we can push the boundaries of what’s possible with local AI and create tools that empower users while safeguarding their privacy.</p><p>Thank you for joining us on this journey — <strong>thinking locally, acting privately</strong>, and building the future of AI, one step at a time!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d487627251b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL, and…]]></title>
            <link>https://medium.com/@fatikir15/end-to-end-real-time-data-engineering-a-project-template-guide-with-kafka-spark-postgresql-and-d4f9ffd94738?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f9ffd94738</guid>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[interactive-dashboard]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Sun, 19 May 2024 10:56:04 GMT</pubDate>
            <atom:updated>2024-05-19T10:56:04.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL, and Dash | Part 3: Interactive Visualizations with Plotly Dash</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Opitp2YUMFEXXyiqEClb4w.gif" /><figcaption>Final Dashboard</figcaption></figure><h4><strong>Introduction</strong></h4><p>In the first part of our series, “End-to-End Real-Time Data Engineering,” we laid the foundation for our data pipeline by setting up data production and messaging using Kafka. We created a Kafka Python producer to simulate log data and configured Kafka with Docker Compose. Moving on to Part 2, we delved into real-time data processing and storage by integrating Apache Spark for stream processing and PostgreSQL for persistent storage.</p><p>Now, in Part 3, we will complete our real-time data engineering journey by creating interactive visualizations using Plotly Dash and build the dashboard in the above GIF. Interactive dashboards play a crucial role in making data insights accessible and actionable, allowing stakeholders to monitor key metrics in real time.</p><p>Here’s what we’ll cover in the last part of these series:</p><ul><li><strong>Building the Dash Application:</strong> We’ll develop the logic for our Dash application, connecting it to our PostgreSQL database to read and visualize real-time data. This will involve creating interactive charts and graphs to monitor key metrics.</li><li><strong>Setting Up Plotly Dash with Docker Compose:</strong> We’ll add a Dash service to our Docker Compose setup, ensuring seamless integration with our existing services. This approach simplifies deployment and ensures consistency across different environments.</li><li><strong>Deploying and Accessing the Dashboard:</strong> After building the Dash application, we’ll deploy it using Docker Compose and demonstrate how to access the dashboard through a web browser. We’ll verify that the real-time visualizations are working correctly.</li></ul><h4><strong>Building the Dash Application</strong></h4><p>Our dash application would require the application script as app.py which will consists of the main logic for the dashboard, a requirements.txt file for the dependencies that needs to be installed inside the docker compose environment and a Dockerfile that will enable us to integrate our Dash service to the other services. Create a separate folder for this service for modularity of our program. The folder structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*WadUJMaI8rmGQviPR9kr_w.png" /></figure><p>Let`s start with the app.py by importing necessary libraries:</p><pre>import dash<br>from dash import dcc, html<br>from dash.dependencies import Input, Output<br>import dash_bootstrap_components as dbc<br>import plotly.graph_objs as go<br>import pandas as pd<br>import sqlalchemy<br>from dash_bootstrap_templates import load_figure_template</pre><ul><li><strong>dash, dcc, html, Input, Output:</strong> The core components and functions from the Dash library. dcc (Dash Core Components) and html (Dash HTML Components) are used to create interactive user interfaces. Input and Output are used for setting up callbacks to update the app dynamically.</li><li><strong>dash_bootstrap_components:</strong> Provides Bootstrap-themed components for Dash applications. It helps in creating visually appealing layouts with minimal effort.</li><li><strong>plotly.graph_objs:</strong> Part of the Plotly library, which is used for creating interactive plots and charts.</li><li><strong>pandas:</strong> A powerful data manipulation and analysis library for Python.</li><li><strong>sqlalchemy:</strong> A SQL toolkit and Object-Relational Mapping (ORM) library for Python. It is used here to manage database connections and queries.</li><li><strong>dash_bootstrap_templates:</strong> Used to load Bootstrap themes for the Dash app.</li></ul><p>Then, load the theme for the dashboard and initialize the application:</p><pre># Load the dark theme for the entire app<br>load_figure_template(&quot;DARKLY&quot;)<br><br>app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])</pre><ul><li><strong>load_figure_template(“DARKLY”):</strong> Loads the “DARKLY” theme for the entire app, giving it a dark mode appearance.</li><li><strong>dash.Dash:</strong> Initializes the Dash application with the “DARKLY” Bootstrap theme.</li></ul><p>Now, we can define the layout of our application:</p><pre>app.layout = html.Div(<br>    [<br>        dbc.NavbarSimple(<br>            brand=&quot;Real-time Application Analysis&quot;,<br>            brand_href=&quot;#&quot;,<br>            color=&quot;dark&quot;,<br>            dark=True,<br>        ),<br>        dbc.Container(<br>            [<br>                dbc.Row(<br>                    [<br>                        dbc.Col(dcc.Graph(id=&quot;app-1-gauge&quot;), width=4),<br>                        dbc.Col(dcc.Graph(id=&quot;app-2-gauge&quot;), width=4),<br>                        dbc.Col(dcc.Graph(id=&quot;app-3-gauge&quot;), width=4),<br>                    ],<br>                    align=&quot;center&quot;,<br>                ),<br>                dbc.Row([dbc.Col(dcc.Graph(id=&quot;error-trends&quot;), width=12)]),<br>                dbc.Row(<br>                    [<br>                        dbc.Col(dcc.Graph(id=&quot;latency-metrics&quot;), width=6),<br>                        dbc.Col(dcc.Graph(id=&quot;request-distribution&quot;), width=6),<br>                    ]<br>                ),<br>                dcc.Interval(<br>                    id=&quot;interval-component&quot;, interval=10 * 1000, n_intervals=0<br>                ),<br>            ],<br>            fluid=True,<br>        ),<br>    ]<br>)</pre><ul><li><strong>html.Div:</strong> A container for all HTML elements.</li><li><strong>dbc.NavbarSimple:</strong> A simple navigation bar with a brand name “Real-time Application Analysis” and a dark color theme.</li><li><strong>dbc.Container:</strong> A Bootstrap container to hold the layout elements, set to be fluid to take the full width of the screen.</li><li><strong>dbc.Row:</strong> A Bootstrap row to organize the layout into columns.</li><li><strong>dcc.Graph:</strong> Dash core component to render interactive graphs.</li><li><strong>dcc.Interval:</strong> A component to update the graphs at regular intervals, here set to update every 10 seconds.</li></ul><p>After that, we should define a callback function to fill this layout:</p><pre>@app.callback(<br>    [<br>        Output(&quot;app-1-gauge&quot;, &quot;figure&quot;),<br>        Output(&quot;app-2-gauge&quot;, &quot;figure&quot;),<br>        Output(&quot;app-3-gauge&quot;, &quot;figure&quot;),<br>        Output(&quot;error-trends&quot;, &quot;figure&quot;),<br>        Output(&quot;latency-metrics&quot;, &quot;figure&quot;),<br>        Output(&quot;request-distribution&quot;, &quot;figure&quot;),<br>    ],<br>    Input(&quot;interval-component&quot;, &quot;n_intervals&quot;),<br>)<br>def update_metrics(n):<br>    # Create database connection<br>    engine = sqlalchemy.create_engine(&quot;postgresql://admin:admin@postgres:5432/logs&quot;)<br><br>    # Using context managers for handling database connections<br>    with engine.connect() as conn:<br>        df = pd.read_sql(<br>            &quot;SELECT * FROM application_metrics ORDER BY enddate DESC LIMIT 3&quot;, conn<br>        )<br><br>        error_data = pd.read_sql(<br>            &quot;&quot;&quot;<br>            SELECT application_id, enddate, error_rate<br>            FROM application_metrics<br>            ORDER BY application_id, enddate<br>            LIMIT 300;<br>            &quot;&quot;&quot;,<br>            conn,<br>        )</pre><ul><li><strong>@app.callback:</strong> A decorator to define the callback function that updates the graphs. It takes the output components (the graphs) and input components (the interval component).</li><li><strong>update_metrics(n):</strong> The function that fetches the data from the PostgreSQL database and updates the graphs. It is triggered every time the interval component updates.</li><li><strong>sqlalchemy.create_engine:</strong> Creates a connection to the PostgreSQL database.</li><li><strong>pd.read_sql:</strong> Reads data from the database into a pandas DataFrame.</li></ul><p>After handling the db connections and retrieve the data, we can define our visualizations. Lets, start with the gauges at the top of the dashboard:</p><pre>    # Create gauges for the latest error rates as percentages<br>    gauges = []<br>    for i in range(1, 4):<br>        app_data = df[df[&quot;application_id&quot;] == f&quot;app_{i}&quot;]<br>        error_rate = app_data[&quot;error_rate&quot;].values[0] if not app_data.empty else 0<br>        gauge = go.Figure(<br>            go.Indicator(<br>                mode=&quot;gauge+number&quot;,<br>                value=error_rate,<br>                domain={&quot;x&quot;: [0, 1], &quot;y&quot;: [0, 1]},<br>                title={&quot;text&quot;: f&quot;App {i} Error Rate&quot;, &quot;align&quot;: &quot;center&quot;},<br>                gauge={&quot;axis&quot;: {&quot;range&quot;: [None, 100]}},<br>            )<br>        )<br>        gauge.update_layout(template=&quot;plotly_dark&quot;)<br>        gauges.append(gauge)</pre><ul><li><strong>gauges:</strong> A list to hold the gauge figures.</li><li><strong>for i in range(1, 4):</strong> Loop through three applications.</li><li><strong>app_data = df[df[“application_id”] == f”app_{i}”]</strong>: Filter the DataFrame for each application.</li><li><strong>go.Indicator:</strong> A Plotly component to create gauge charts.</li><li><strong>gauge.update_layout:</strong> Apply the “plotly_dark” template to the gauge chart.</li></ul><p>Now continue with the line chart on the middle:</p><pre>    # Error Trends Plot<br>    error_trends = go.Figure()<br>    for app_id in error_data[&quot;application_id&quot;].unique():<br>        app_data = error_data[error_data[&quot;application_id&quot;] == app_id]<br>        error_trends.add_trace(<br>            go.Scatter(<br>                x=app_data[&quot;enddate&quot;],<br>                y=app_data[&quot;error_rate&quot;],<br>                mode=&quot;lines+markers&quot;,<br>                name=f&quot;App {app_id}&quot;,<br>            )<br>        )<br><br>    error_trends.update_layout(<br>        title=&quot;Error Rate Trends Over Time&quot;,<br>        xaxis_title=&quot;Time&quot;,<br>        yaxis_title=&quot;Error Rate (%)&quot;,<br>        legend_title=&quot;Application ID&quot;,<br>        template=&quot;plotly_dark&quot;,<br>    )</pre><ul><li><strong>error_trends = go.Figure():</strong> Initialize a Plotly figure for error trends.</li><li><strong>for app_id in error_data[“application_id”].unique():</strong> Loop through each unique application ID.</li><li><strong>go.Scatter:</strong> A Plotly component to create scatter plots.</li><li><strong>error_trends.add_trace:</strong> Add each application’s error rate data as a trace to the figure.</li><li><strong>error_trends.update_layout:</strong> Set the layout properties, including titles and the “plotly_dark” template.</li></ul><p>And finalize our plots with the grouped bar charts at the end:</p><pre>    # Latency Metrics Plot<br>    latency_metrics = go.Figure(<br>        go.Bar(<br>            x=df[&quot;application_id&quot;],<br>            y=df[&quot;average_latency&quot;],<br>            text=df[&quot;average_latency&quot;],<br>            textposition=&quot;auto&quot;,<br>        )<br>    )<br>    latency_metrics.update_layout(<br>        title=&quot;Average Latency per Application&quot;,<br>        xaxis_title=&quot;Application ID&quot;,<br>        yaxis_title=&quot;Latency (ms)&quot;,<br>        template=&quot;plotly_dark&quot;,<br>    )<br><br>    # Request Distribution Plot<br>    request_distribution = go.Figure()<br>    request_types = [&quot;get_requests&quot;, &quot;post_requests&quot;, &quot;put_requests&quot;, &quot;delete_requests&quot;]<br>    for request_type in request_types:<br>        request_distribution.add_trace(<br>            go.Bar(<br>                x=df[&quot;application_id&quot;],<br>                y=df[request_type],<br>                name=request_type.split(&quot;_&quot;)[0].upper(),<br>            )<br>        )<br><br>    request_distribution.update_layout(<br>        barmode=&quot;group&quot;,<br>        title=&quot;Request Distribution per Application&quot;,<br>        xaxis_title=&quot;Application ID&quot;,<br>        yaxis_title=&quot;Number of Requests&quot;,<br>        template=&quot;plotly_dark&quot;,<br>    )</pre><ul><li><strong>latency_metrics = go.Figure(go.Bar()):</strong> Initialize a Plotly figure with a bar chart for latency metrics.</li><li><strong>go.Bar:</strong> A Plotly component to create bar charts.</li><li><strong>latency_metrics.update_layout:</strong> Set the layout properties, including titles and the “plotly_dark” template.</li><li><strong>request_distribution = go.Figure():</strong> Initialize a Plotly figure for request distribution.</li><li><strong>for request_type in request_types:</strong> Loop through each request type (GET, POST, PUT, DELETE).</li><li><strong>go.Bar:</strong> Create a bar for each request type.</li><li><strong>request_distribution.add_trace:</strong> Add each request type as a trace to the figure.</li><li><strong>request_distribution.update_layout:</strong> Set the layout properties, including titles and the “plotly_dark” template.</li></ul><p>Finally return all our plots with:</p><pre>    return gauges + [error_trends, latency_metrics, request_distribution]</pre><p>This is it for our callback function. In your applications, you can change the callback function and layout to create interactive and live dashboards. For the last touch of our app.py file we need call our application and initialize it by adding these lines at the end of the script:</p><pre>if __name__ == &quot;__main__&quot;:<br>    app.run_server(debug=False, host=&quot;0.0.0.0&quot;)</pre><ul><li><strong>if name == “main”:</strong> Ensure the server runs only if this script is executed directly.</li><li><strong>app.run_server(debug=False, host=”0.0.0.0&quot;):</strong> Start the Dash app server with debug mode off and host set to &quot;0.0.0.0&quot; to make it accessible within the Docker network to interact with other components.</li></ul><p>The major part of the dash application is done already. All we need to add is to add this requirements.txt file and add a Dockerfile to build the docker component for our service in our overall docker compose:</p><pre>dash<br>pandas<br>plotly<br>sqlalchemy<br>psycopg2-binary<br>dash-bootstrap-components<br>dash-bootstrap-templates</pre><p>Dockerfile:</p><pre># Use an official Python runtime as a parent image<br>FROM python:3.9-slim<br><br># Set the working directory to /app<br>WORKDIR /app<br><br># Copy the current directory contents into the container at /app<br>COPY . /app<br><br># Install any needed packages specified in requirements.txt<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Make port 8050 available to the world outside this container<br>EXPOSE 8050<br><br># Run app.py when the container launches<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>That is it. Our dash service is ready now. All we need to do is to add this service into the docker compose.</p><h4><strong>Setting Up Plotly Dash with Docker Compose</strong></h4><p>In order to add this service to the docker-compose.yml and interact with other services that we created earlier, we just need to add the service definition into the services part of our docker-compose like this:</p><pre>  dash_app:<br>    build: ./dash_app<br>    ports:<br>      - &quot;8050:8050&quot;<br>    depends_on:<br>      - kafka<br>      - spark-master<br>      - spark-worker<br>      - kafka-producer<br>      - postgres<br>      - spark_job<br>    networks:<br>      bridge:<br>        aliases:<br>          - dash_app</pre><ul><li>dash_app:The name of the service. This name is used to reference the service within the Docker Compose file and network.</li><li>build: ./dash_app:Specifies the build context for the service. The path ./dash_app indicates the directory containing the Dockerfile and application code for the Dash service. Docker Compose will use this directory to build the Docker image for the Dash service.</li><li>ports: - &quot;8050:8050&quot;:Maps port 8050 on the host machine to port 8050 on the container. This makes the Dash application accessible via http://localhost:8050 on the host machine.</li><li>depends_on:Lists the services that the Dash service depends on. Docker Compose ensures that these services are started before the Dash service.</li><li>- kafka:The Kafka broker service, which is part of the data pipeline.</li><li>- spark-master:The master node of the Spark cluster, which coordinates the Spark jobs.</li><li>- spark-worker:The worker node(s) of the Spark cluster, which execute the Spark tasks.</li><li>- kafka-producer:The custom service we have built that sends data into Kafka.</li><li>- postgres:The PostgreSQL database service, which stores the processed data.</li><li>- spark_job:The Spark streaming job that processes data from Kafka and writes to PostgreSQL.</li><li>networks:Specifies the network(s) that the service is connected to.</li><li>bridge:Indicates that the service is connected to the bridge network. This is a custom Docker network defined in the Docker Compose file, allowing services to communicate with each other.</li><li>aliases: - dash_app: Sets dash_app as a network alias for the service within the bridge network. This alias allows other services on the same network to refer to this service by the name dash_app.</li></ul><p>With the addition of our service to the docker compose, we can now run our application.</p><h4><strong>Deploying and Accessing the Dashboard</strong></h4><p>We have everything set up and now all we have to do to initialize all our services is to run:</p><pre>docker-compose up --build</pre><p>This will initiate all the services one by one. You can access the dashboard at localhost:8050. You may need to wait the services to start and stream the data into the database and the dashboard.</p><h4>Final words</h4><p>In this comprehensive series, “End-to-End Real-Time Data Engineering,” we built a robust real-time data pipeline using Kafka, Spark, PostgreSQL, and Dash. Our goal was to create an end-to-end solution that handles real-time data ingestion, processing, and visualization.</p><p>In <strong>Part 1</strong>, we focused on <strong>data production and messaging</strong>. We set up Kafka and created a Kafka Python producer to simulate log data, establishing a scalable messaging infrastructure.</p><p>In <strong>Part 2</strong>, we moved to <strong>real-time data processing and storage</strong>. We integrated Apache Spark for stream processing and used PostgreSQL for persistent storage. Our Spark Streaming application analyzed the data produced by our Kafka producers.</p><p>In <strong>Part 3</strong>, we developed <strong>interactive visualizations</strong> with Plotly Dash. We built a Dash application connected to our PostgreSQL database, visualizing data through dynamic charts and graphs. We integrated the Dash service into our Docker Compose setup, ensuring seamless deployment.</p><p>Throughout this series, we:</p><ul><li><strong>Built the Dash Application:</strong> Developed the logic for our Dash app, connected it to PostgreSQL, and created interactive charts and graphs.</li><li><strong>Set Up Plotly Dash with Docker Compose:</strong> Added the Dash service to Docker Compose, ensuring integration with existing services and simplifying deployment.</li><li><strong>Deployed and Accessed the Dashboard:</strong> Deployed the Dash application, accessed it via a web browser, and verified the real-time visualizations.</li></ul><p>By following this series, you now have a complete template for building a real-time data engineering pipeline. This template can be customized and expanded for specific needs.</p><p>Thank you for joining this journey. I hope you found this series informative and practical. Connect with me on <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">LinkedIn</a> for more discussions on data engineering. The full project is available on <a href="https://github.com/firefly-cmd/data-engineering-template">GitHub</a>. Let’s keep exploring and innovating in real-time data engineering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f9ffd94738" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL and…]]></title>
            <link>https://medium.com/@fatikir15/end-to-end-real-time-data-engineering-a-project-template-guide-with-kafka-spark-postgresql-and-55b99bcc2c5c?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/55b99bcc2c5c</guid>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Fri, 10 May 2024 13:17:58 GMT</pubDate>
            <atom:updated>2024-05-10T13:17:58.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL and Dash | Part 2: Spark Streaming and Database Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5mToFE__1cHLxUrm" /><figcaption>Photo by <a href="https://unsplash.com/@yoannlaheurte?utm_source=medium&amp;utm_medium=referral">Yoann Laheurte</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>In <strong>Part 1</strong> of our series, “End-to-End Real-Time Data Engineering,” we established a robust data production and messaging system using Kafka. We explored setting up a Kafka Python producer and configuring Kafka and Zookeeper with Docker Compose, creating a scalable messaging infrastructure. As we transition to <strong>Part 2: Spark Streaming and Database Setup</strong>, our focus shifts from data production to the processing and storage phases of our real-time data pipeline.</p><p>This part will dive into using Apache Spark to process data streams in real time. Apache Spark is a powerful tool for big data processing, and its streaming module enables high-throughput, fault-tolerant stream processing of live data streams. We’ll set up Spark within our Docker environment and develop a Spark Streaming application to analyze the data produced by our Kafka producers.</p><p>Here’s what we’ll cover:</p><ul><li><strong>Setting Up Apache Spark with Docker Compose:</strong> We’ll integrate Spark and a Spark Worker service into our Docker Compose setup. This approach simplifies development and ensures consistency across different environments.</li><li><strong>Developing the Spark Streaming Application:</strong> We’ll build the logic to process streaming data, using Spark SQL and DataFrames to perform real-time analytics. This will involve reading from Kafka topics, applying transformations, and performing aggregations.</li><li><strong>Setting Up PostgreSQL for Data Storage:</strong> After processing the data, we need to store it for further analysis. We’ll use PostgreSQL for this purpose and configure it within Docker Compose. We’ll then show how to save processed data from Spark into PostgreSQL, ensuring that our data pipeline is both powerful and persistent.</li><li><strong>Debugging and Monitoring the Stream Processing:</strong> Effective monitoring is essential in data pipelines. We’ll explore using Spark’s UI to monitor our jobs and discuss techniques to ensure that data flows correctly through our pipeline.</li></ul><h4>Setting Up Apache Spark with Docker Compose</h4><p>In order to integrate the spark master and workers to the docker compose architecture in the first part, you need to add necessary services to the services part to the docker-compose.yml.</p><pre>  spark-master:<br>    image: apache/spark:python3<br>    ports:<br>      - &quot;8080:8080&quot;  <br>      - &quot;7077:7077&quot;  <br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.master.Master --ip spark-master --port 7077 --webui-port 8080 &amp;&amp; tail -f /dev/null&quot;<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-master<br><br>  spark-worker:<br>    image: apache/spark:python3<br>    depends_on:<br>      - spark-master<br>    command: bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077 &amp;&amp; tail -f /dev/null&quot;<br>    networks:<br>      bridge:<br>        aliases:<br>          - spark-worker</pre><p><strong>Spark Master Service:</strong></p><ul><li><strong>image: apache/spark:python3</strong>: This line specifies the Docker image to use for the container. apache/spark:python3 is the official image from Apache Spark pre-built with Python 3 support. This image includes all necessary Spark binaries and libraries to run Spark applications.</li><li><strong>ports: </strong>This is the necessary port mappings for spark master</li><li><strong>&quot;8080:8080&quot;</strong>: Maps port 8080 on the host to port 8080 on the container. This port is used for the Spark master web UI, which provides a user interface to view cluster and job statistics. By mapping this port, you can access the Spark web UI from your browser using <a href="http://localhost:8080.">http://localhost:8080</a></li><li><strong>&quot;7077:7077&quot;</strong>: Maps port 7077 on the host to port 7077 on the container. This port is the default port that the Spark master listens on for communication with Spark workers. It’s crucial for cluster mode as workers register themselves on this port.</li><li><strong>command:</strong>The command starts the Spark master process inside the Docker container.</li><li><strong>bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.master.Master --ip spark-master --port 7077 --webui-port 8080 &amp;&amp; tail -f /dev/null&quot;</strong>: This command uses bash -c to run multiple commands in the container.</li><li><strong>/opt/spark/bin/spark-class org.apache.spark.deploy.master.Master</strong>: This part runs the Spark master by calling the Spark class responsible for the master node.</li><li><strong>--ip spark-master</strong>: Specifies the IP address or hostname of the Spark master. Here, it’s set to spark-master, which will be the alias defined in the Docker network, allowing other services to resolve this hostname to the master container.</li><li><strong>--port 7077</strong>: The port on which the master will listen for worker connections.</li><li><strong>--webui-port 8080</strong>: The port for the web UI where you can monitor the Spark master.</li><li><strong>&amp;&amp; tail -f /dev/null</strong>: This part of the command is a common trick in Docker to keep the container running by tailing the /dev/null file. This ensures that the master process doesn’t exit and the container keeps running.</li><li><strong>networks: bridge: aliases: - spark-master</strong>: Sets spark-master as a network alias for the container within the bridge network. This alias allows other containers on the same network to refer to the master using the hostname spark-master.</li></ul><p><strong>Spark worker service:</strong></p><ul><li><strong>image: apache/spark:python3</strong>: Uses the same Spark image as the master, ensuring that the master and worker nodes run the same version of Spark and Python.</li><li><strong>depends_on:</strong></li><li><strong>- spark-master</strong>: Specifies that the spark-worker service depends on the spark-master service. This means the worker will only start after the master is started, ensuring the master is available when the worker tries to connect.</li><li><strong>command: </strong>The command to start the Spark worker process.</li><li><strong>bash -c &quot;/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker spark://spark-master:7077 &amp;&amp; tail -f /dev/null&quot;</strong>: This command uses bash -c to run multiple commands in the container:</li><li><strong>/opt/spark/bin/spark-class org.apache.spark.deploy.worker.Worker</strong>: This part runs the Spark worker by calling the Spark class responsible for the worker node.</li><li><strong>spark://spark-master:7077</strong>: This tells the worker the address of the master node. spark://spark-master:7077 points to the master service using its network alias and the port on which the master listens.</li><li><strong>&amp;&amp; tail -f /dev/null</strong>: Keeps the container running by preventing the worker process from exiting.</li><li><strong>networks: bridge: aliases: - spark-worker</strong>: Sets spark-worker as a network alias for this service within the bridge network, allowing it to be referenced by this name from other services.</li></ul><p>After setting up our Apache spark infrastructure, we can build our streaming application.</p><h4><strong>Building Spark Streaming Application</strong></h4><p>In order to build the our streaming service and integrate it into other components, we need a Dockerfile and a spark_streaming job.py file. Normally, you need a requirements.txt file for the python dependencies but we will use only native pyspark function so we do not need it. You can add this file in your projects. You can create a separate folder for this service to make it modular. Lets first start by creating the ingredients of our spark_streaming_job.py</p><p>First import the necessary libraries:</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import (<br>    col,<br>    count,<br>    from_json,<br>    sum,<br>    avg,<br>    to_timestamp,<br>    when,<br>    window,<br>)<br>from pyspark.sql.types import StructType, StructField, StringType, IntegerType</pre><ul><li><strong>SparkSession</strong>: The entry point to programming Spark with the Dataset and DataFrame API. It&#39;s used to create and manipulate the datasets.</li><li><strong>col, count, sum, avg, to_timestamp, when, window</strong>: These are functions from pyspark.sql.functions which are used to operate on the data in columns.</li><li>col is used to refer to a column in a DataFrame.</li><li>count counts the number of rows in a DataFrame.</li><li>sum and avg are used to compute the sum and average of a column.</li><li>to_timestamp converts a column to timestamps.</li><li>when is similar to SQL&#39;s CASE WHEN statement.</li><li>window is used for time-based aggregations.</li><li><strong>StructType, StructField, StringType, IntegerType</strong>: These define the schema of a DataFrame. StructType is a collection of StructField that defines the name, type, and nullable property for each column.</li></ul><p>After importing necessary things, we can create a helper function to write our data to the postgresql. We will setup the postgresql and necessary table structure in the next section.</p><pre>def write_to_postgres(df, epoch_id, table_name: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Writes a DataFrame to PostgreSQL using JDBC.<br><br>    Args:<br>        df: DataFrame to write.<br>        epoch_id: Epoch ID of the streaming batch.<br>        table_name: Name of the PostgreSQL table.<br>    &quot;&quot;&quot;<br>    jdbc_url = &quot;jdbc:postgresql://postgres:5432/logs&quot;<br>    properties = {<br>        &quot;user&quot;: &quot;admin&quot;,<br>        &quot;password&quot;: &quot;admin&quot;,<br>        &quot;driver&quot;: &quot;org.postgresql.Driver&quot;,<br>    }<br>    df.write.jdbc(url=jdbc_url, table=table_name, mode=&quot;append&quot;, properties=properties)</pre><ul><li><strong>jdbc_url</strong>: JDBC connection string that specifies the PostgreSQL server (postgres), port (5432), and database name (logs).</li><li><strong>properties</strong>: Contains the database credentials and the JDBC driver needed for the connection.</li><li><strong>df.write.jdbc</strong>: Writes the DataFrame to the PostgreSQL table using the specified URL, table name, mode, and connection properties.</li><li><strong>mode=&quot;append&quot;</strong>: Data is appended to the specified table.</li></ul><p>Now, we can write our main logic for this application. In order to use this template in your projects, you can change the logic in this part.</p><pre><br>def main() -&gt; None:<br>    &quot;&quot;&quot;<br>    Main function to initialize Spark session and process streaming data.<br>    &quot;&quot;&quot;<br>    # Initialize Spark session for processing<br>    spark = SparkSession.builder.appName(&quot;KafkaStreamExample&quot;).getOrCreate()<br>    spark.sparkContext.setLogLevel(&quot;WARN&quot;)<br><br>    # Kafka configuration details<br>    kafka_topic_name = &quot;logs&quot;<br>    kafka_bootstrap_servers = &quot;kafka:9092&quot;<br><br>    # Define the schema for the incoming logs<br>    schema = StructType(<br>        [<br>            StructField(&quot;timestamp&quot;, StringType(), True),<br>            StructField(&quot;application_id&quot;, StringType(), True),<br>            StructField(&quot;log_level&quot;, StringType(), True),<br>            StructField(&quot;error_code&quot;, IntegerType(), True),<br>            StructField(&quot;message&quot;, StringType(), True),<br>            StructField(&quot;request_type&quot;, StringType(), True),<br>            StructField(&quot;url&quot;, StringType(), True),<br>            StructField(&quot;user_agent&quot;, StringType(), True),<br>            StructField(&quot;session_id&quot;, IntegerType(), True),<br>            StructField(&quot;response_time_ms&quot;, IntegerType(), True),<br>        ]<br>    )<br><br>    # Read data from Kafka using structured streaming<br>    df = (<br>        spark.readStream.format(&quot;kafka&quot;)<br>        .option(&quot;kafka.bootstrap.servers&quot;, kafka_bootstrap_servers)<br>        .option(&quot;subscribe&quot;, kafka_topic_name)<br>        .option(&quot;startingOffsets&quot;, &quot;earliest&quot;)<br>        .load()<br>    )<br><br>    # Parse the JSON data and apply the schema<br>    json_df = df.selectExpr(&quot;CAST(value AS STRING) as json&quot;).select(<br>        from_json(col(&quot;json&quot;), schema).alias(&quot;data&quot;)<br>    )<br><br>    # Extract relevant fields from the JSON data<br>    exploded_df = json_df.select(<br>        to_timestamp(col(&quot;data.timestamp&quot;)).alias(&quot;timestamp&quot;),<br>        &quot;data.application_id&quot;,<br>        &quot;data.log_level&quot;,<br>        &quot;data.error_code&quot;,<br>        &quot;data.request_type&quot;,<br>        &quot;data.response_time_ms&quot;,<br>        &quot;data.user_agent&quot;,<br>    )<br><br>    # Aggregate data based on application ID and a sliding window<br>    app_metrics_df = (<br>        exploded_df.groupBy(&quot;application_id&quot;, window(&quot;timestamp&quot;, &quot;10 seconds&quot;))<br>        .agg(<br>            (<br>                sum(when(col(&quot;error_code&quot;) &gt;= 400, 1).otherwise(0)) / count(&quot;*&quot;) * 100<br>            ).alias(&quot;error_rate&quot;),<br>            avg(&quot;response_time_ms&quot;).alias(&quot;average_latency&quot;),<br>            count(when(col(&quot;request_type&quot;) == &quot;GET&quot;, True)).alias(&quot;get_requests&quot;),<br>            count(when(col(&quot;request_type&quot;) == &quot;POST&quot;, True)).alias(&quot;post_requests&quot;),<br>            count(when(col(&quot;request_type&quot;) == &quot;PUT&quot;, True)).alias(&quot;put_requests&quot;),<br>            count(when(col(&quot;request_type&quot;) == &quot;DELETE&quot;, True)).alias(&quot;delete_requests&quot;),<br>        )<br>        .select(<br>            &quot;application_id&quot;,<br>            col(&quot;window.start&quot;).alias(&quot;startdate&quot;),<br>            col(&quot;window.end&quot;).alias(&quot;enddate&quot;),<br>            &quot;error_rate&quot;,<br>            &quot;average_latency&quot;,<br>            &quot;get_requests&quot;,<br>            &quot;post_requests&quot;,<br>            &quot;put_requests&quot;,<br>            &quot;delete_requests&quot;,<br>        )<br>    )<br><br>    # Setup the streaming query to write the aggregated results to PostgreSQL<br>    app_query = (<br>        app_metrics_df.writeStream.outputMode(&quot;update&quot;)<br>        .foreachBatch(<br>            lambda df, epoch_id: write_to_postgres(df, epoch_id, &quot;application_metrics&quot;)<br>        )<br>        .start()<br>    )<br><br>    # Wait for all processing to be done<br>    app_query.awaitTermination()</pre><ul><li><strong>In order to start spark session:</strong></li><li><strong>SparkSession.builder.appName(&quot;KafkaStreamExample&quot;).getOrCreate()</strong>: Creates a SparkSession with the application name &quot;KafkaStreamExample&quot;. If a session is already created, it returns the existing session.</li><li><strong>setLogLevel(&quot;WARN&quot;)</strong>: Sets the log level to &quot;WARN&quot; to reduce the verbosity of log messages.</li><li><strong>Define kafka related properties:</strong></li><li><strong>kafka_topic_name</strong>: The name of the Kafka topic from which the data will be consumed.</li><li><strong>kafka_bootstrap_servers</strong>: Specifies the Kafka broker address with the port (kafka:9092).</li><li><strong>Define the schema of the related data:</strong></li><li><strong>schema</strong>: Defines the structure of the incoming JSON data from Kafka. It includes the name, data type, and nullable flag for each field.</li><li><strong>Initialize reading data as a stream:</strong></li><li><strong>spark.readStream.format(&quot;kafka&quot;)</strong>: Specifies that the source format is Kafka for streaming data.</li><li><strong>option(&quot;kafka.bootstrap.servers&quot;, kafka_bootstrap_servers)</strong>: Sets the address of the Kafka server.</li><li><strong>option(&quot;subscribe&quot;, kafka_topic_name)</strong>: Specifies the Kafka topic to subscribe to.</li><li><strong>option(&quot;startingOffsets&quot;, &quot;earliest&quot;)</strong>: Starts consuming data from the earliest offset, ensuring no data is missed when the query starts.</li><li><strong>Extract, transform and aggregate data:</strong></li><li><strong>selectExpr(&quot;CAST(value AS STRING) as json&quot;)</strong>: Converts the binary value column in the Kafka DataFrame to a string column named json.</li><li><strong>from_json(col(&quot;json&quot;), schema)</strong>: Applies the JSON schema to the json column and extracts data into a structured format.</li><li><strong>to_timestamp(col(&quot;data.timestamp&quot;)).alias(&quot;timestamp&quot;)</strong>: Converts the timestamp field into a Spark SQL timestamp.</li><li>The select function is used to extract and transform relevant fields from the structured JSON data for further processing.</li><li><strong>groupBy(&quot;application_id&quot;, window(&quot;timestamp&quot;, &quot;10 seconds&quot;))</strong>: Groups the data by application_id and a 10-second window based on the timestamp.</li><li><strong>agg(...)</strong>: Performs the following aggregations:</li><li><strong>error_rate</strong>: Calculates the percentage of requests that resulted in an error (HTTP status &gt;= 400).</li><li><strong>average_latency</strong>: Computes the average response time in milliseconds.</li><li><strong>get_requests, post_requests, put_requests, delete_requests</strong>: Counts the number of GET, POST, PUT, and DELETE requests, respectively.</li><li>The select function then structures the output, including the start and end of the window.</li><li><strong>Write the streaming data:</strong></li><li><strong>writeStream.outputMode(&quot;update&quot;)</strong>: Specifies that the output mode is &quot;update&quot;, where only the rows that were updated in the streaming DataFrame will be written to the sink.</li><li><strong>foreachBatch(...)</strong>: For each micro-batch, the write_to_postgres function is called to write the batch DataFrame to the PostgreSQL table &quot;application_metrics&quot;.</li><li><strong>awaitTermination()</strong>: Waits for the termination of the app_query (the streaming query), either by query failure or manual termination.</li></ul><p>Finally, add these lines to start the service in a docker compose configuration:</p><pre>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>After finalizing the streaming job, we will define the required Dockerfile like this:</p><pre># Use an official Spark base image with Python support<br>FROM apache/spark:python3<br><br># Set the working directory in the container<br>WORKDIR /app<br><br># Change to root to install packages<br>USER root<br><br># Copy the Python dependencies file to the container<br>COPY requirements.txt /app/<br><br># Install any needed packages specified in requirements.txt<br>RUN pip install --no-cache-dir -r requirements.txt<br><br># Copy the source code of the Spark job into the container<br>COPY ./src /app/<br><br># Command to run the Spark job script<br>CMD [&quot;/opt/spark/bin/spark-submit&quot;, &quot;--master&quot;, &quot;spark://spark-master:7077&quot;, &quot;--packages&quot;, &quot;org.apache.spark:spark-sql-kafka-0-10_2.12:3.5.0,org.postgresql:postgresql:42.2.18&quot;, &quot;--conf&quot;, &quot;spark.jars.ivy=/tmp/.ivy&quot;, &quot;/app/spark_streaming_job.py&quot;]</pre><ul><li><strong>FROM apache/spark:python3</strong>: This line sets the base image for the Docker container. Here, we are using the official Apache Spark image with Python 3 support. This image includes the complete Spark framework and a compatible Python environment, which are necessary to run our Spark Streaming job.</li><li><strong>WORKDIR /app</strong>: This directive sets /app as the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow in the Dockerfile. This means that all subsequent actions are performed in the /app directory inside the container. This is a common practice to structure the files within Docker containers.</li><li><strong>USER root</strong>: Switches the user to root to ensure we have the necessary permissions to install packages and make other required changes to the container. This step is crucial because some Docker images might use a non-root user by default, which could restrict the permissions.</li><li><strong>COPY requirements.txt /app/</strong>: This line copies the requirements.txt file from your project directory (on the host) into the /app/ directory inside the Docker container. The requirements.txt file typically contains a list of Python packages that your application needs. This setup ensures that all your Python dependencies are available in the container.</li><li><strong>RUN pip install --no-cache-dir -r requirements.txt</strong>: Executes the command to install the Python packages specified in requirements.txt.</li><li><strong>--no-cache-dir</strong>: This option tells pip not to cache the installed packages, which helps reduce the size of the Docker image by avoiding unnecessary files.</li><li><strong>COPY ./src /app/</strong>: Copies the contents of the src directory from our host machine into the /app/ directory inside the container. This src directory should contain the Python script for our Spark Streaming job (spark_streaming_job.py) and any other supporting files we have.</li><li><strong>CMD [&quot;/opt/spark/bin/spark-submit&quot;, ...]</strong>: Specifies the default command to run when the Docker container starts. Here’s a breakdown of this command:</li><li><strong>/opt/spark/bin/spark-submit</strong>: This is the path to the Spark submit script that runs our Spark application.</li><li><strong>--master spark://spark-master:7077</strong>: Specifies the master URL for the cluster, which in this case is the Spark master service defined in your Docker Compose file.</li><li><strong>--packages</strong>: This option is used to download and include additional Spark packages that are not part of the standard Spark distribution. In this case:</li><li><strong>org.apache.spark:spark-sql-kafka-0-10_2.12:3.5.0</strong>: The Spark SQL Kafka connector package, which allows Spark to read from and write to Kafka topics. This package must match the version of Spark you are using.</li><li><strong>org.postgresql:postgresql:42.2.18</strong>: The PostgreSQL JDBC driver needed to write data to our PostgreSQL database.</li><li><strong>--conf &quot;spark.jars.ivy=/tmp/.ivy&quot;</strong>: Configures Spark to download jars to /tmp/.ivy directory inside the container. This is helpful for managing dependencies.</li><li><strong>/app/spark_streaming_job.py</strong>: The path to our Spark job script inside the container.</li></ul><p>Finally, we need to create a service definition for our spark streaming job in the docker-compose file so that when we initialize our docker compose this streming job is triggered as well:</p><pre>  spark_job:<br>    build: ./spark_jobs<br>    depends_on:<br>      - kafka<br>      - spark-master<br>      - spark-worker<br>      - kafka-producer<br>      - postgres<br>    networks:<br>      - bridge<br>    environment:<br>      - SPARK_MASTER_URL=spark://spark-master:7077</pre><ul><li><strong>build: ./spark_jobs</strong>: This directive tells Docker Compose to build the Docker image for the spark_job service using the Dockerfile located in the ./spark_jobs directory relative to the Docker Compose file.</li><li><strong>depends_on:</strong>: This section specifies that the spark_job service has dependencies on several other services. The spark_job will start only after the listed services are up and running. Here’s what each service does:</li><li><strong>kafka</strong>: The Kafka broker service; our Spark job consumes data from Kafka, so it needs Kafka to be up and ready.</li><li><strong>spark-master</strong>: The master node of the Spark cluster; this service must be running for the Spark workers and the job itself to connect and register with the cluster.</li><li><strong>spark-worker</strong>: The worker node(s) of the Spark cluster; these nodes actually execute the tasks that make up your Spark job. While technically, the job submits tasks to the master, which then schedules them on workers, having workers ready ensures the job can run immediately.</li><li><strong>kafka-producer</strong>: This is our custom service we&#39;ve defined that sends data into Kafka. The Spark depends on this service to ensure there is data in Kafka to process.</li><li><strong>postgres</strong>: The PostgreSQL database service; our Spark job writes results to PostgreSQL, this database needs to be available. we will define this database in the next section</li><li><strong>networks: - bridge</strong>: This specifies that the spark_job service is part of the bridge network. This Docker network configuration ensures that the spark_job can communicate with all other services on the same network, especially important for interacting with Kafka, Spark, and PostgreSQL.</li><li><strong>environment:</strong>: Defines environment variables for the spark_job service. These are key-value pairs that will be available to the Spark application inside the container.</li><li><strong>SPARK_MASTER_URL=spark://spark-master:7077</strong>: This environment variable specifies the URL for the Spark master. The Spark job uses this URL to connect to the Spark master node.</li><li>spark://spark-master:7077 indicates that the Spark master is accessible at the hostname spark-master (which is resolved within the Docker network bridge) and listens on port 7077.</li></ul><p>And this is it for our spark streaming job. After completing all of these steps, we can define our postgresql service and finalize the Part 2 of the series.</p><h4>Setting Up PostgreSQL for Data Storage</h4><p>It is really easy to setup a postgresql database with docker compose. We only need to setup a service definition and create a database initialization file with some sql logic about our tables or some datbase initialization logic. Lets start with the service definition in the docker-compose.yml file:</p><pre>  postgres:<br>    image: postgres:16<br>    environment:<br>      POSTGRES_DB: logs<br>      POSTGRES_USER: admin<br>      POSTGRES_PASSWORD: admin<br>    volumes:<br>      - ./postgres/init:/docker-entrypoint-initdb.d<br>    ports:<br>      - &quot;5432:5432&quot;<br>    networks:<br>      bridge:<br>        aliases:<br>          - postgres</pre><ul><li><strong>image: postgres:16</strong>: Specifies the Docker image to use for the postgres service. This line tells Docker to pull the official PostgreSQL image, version 16, from the Docker Hub. PostgreSQL 16 is a stable release that includes the latest features and updates.</li><li><strong>environment:</strong>: Defines environment variables for the PostgreSQL server. These variables are used to configure the default database, user, and password, making it easier to connect and manage the database:</li><li><strong>POSTGRES_DB: logs</strong>: This sets up a default database named logs. When we connect to this PostgreSQL instance, the logs database will be available for use. This is useful for storing log data processed by our Spark job.</li><li><strong>POSTGRES_USER: admin</strong>: Specifies the default user as admin. This is the username we will use when connecting to the PostgreSQL database unless otherwise configured.</li><li><strong>POSTGRES_PASSWORD: admin</strong>: Sets the password for the admin user. It’s crucial to secure our database, and while admin is used here for demonstration, ensure you use a more secure password in production environments.</li><li><strong>volumes:</strong></li><li><strong>- ./postgres/init:/docker-entrypoint-initdb.d</strong>: This line mounts a volume from ./postgres/init on the host machine to /docker-entrypoint-initdb.d inside the Docker container.</li><li><strong>./postgres/init</strong>: This should be a directory on our host machine that contains SQL or shell scripts to initialize the database. These scripts are executed when the PostgreSQL server first starts.</li><li><strong>/docker-entrypoint-initdb.d</strong>: This is a special directory within the PostgreSQL Docker container. Any scripts or SQL files in this directory are automatically executed during the initial startup of the container. This mechanism is often used to set up databases, tables, and initial data sets.</li><li><strong>ports:</strong></li><li><strong>&quot;5432:5432&quot;</strong>: Maps port 5432 on the host to port 5432 on the Docker container. PostgreSQL by default listens on port 5432. This mapping allows us to connect to the PostgreSQL server running inside the Docker container using localhost:5432 from your host machine. This is essential for accessing PostgreSQL from other applications or for administrative purposes.</li><li><strong>networks: bridge: aliases: - postgres</strong>: Sets postgres as a network alias for this container within the bridge network. This alias allows other containers on the same network to refer to this container as postgres. It simplifies the network configuration since you don’t need to use the container’s dynamically assigned IP address.</li></ul><p>The next part is to define the database initialization logic. Create a separate folder named postgres and create a subfolder named init to store initialization logics. Create a init_db.sql file and write this database sql logic:</p><pre>DROP TABLE IF EXISTS application_metrics;<br><br>CREATE TABLE application_metrics (<br>    application_id TEXT,<br>    startdate TIMESTAMP,<br>    enddate TIMESTAMP,<br>    error_rate DECIMAL(5, 2),<br>    average_latency DECIMAL(10, 2),<br>    get_requests INTEGER,<br>    post_requests INTEGER,<br>    put_requests INTEGER,<br>    delete_requests INTEGER<br>);</pre><p>This will store our data that is created by spark streaming job and it will be used by the dash application. In your projects, you need to change this into your required database schema.</p><p>This is it for the postgresql initializtion and integration. Now we can run all our system by:</p><pre>docker-compose up --build</pre><h4>Debugging and Monitoring the Stream Processing</h4><p>After running the docker compose we can open the spark ui by going into localhost:8080, it will open a ui like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZvE7KxHSK4sZKScBn1P4uA.png" /></figure><p>This shows that our worker node correctly connected into the master node.</p><p>In order to investigate the database (if the data is correctly streaming into the database or not), we can connect to the database with this command:</p><pre>docker exec -it data-engineering-template_postgres_1 psql -U admin -d logs</pre><p>After connecting the database, we can write a select query to see the data:</p><pre>SELECT * FROM application_metrics;</pre><p>Thats it. In <strong>Part 2</strong> of our series, we’ve significantly advanced our data engineering pipeline by integrating Apache Spark for real-time data processing and PostgreSQL for persistent storage. This setup allows us to transform streaming data into actionable insights efficiently.</p><p><strong>Looking Ahead to Interactive Visualizations</strong></p><p>In <strong>Part 3</strong>, we will focus on bringing this data to the forefront through interactive visualizations using Plotly Dash. This will allow users to engage with the data dynamically, enhancing the decision-making process with intuitive and insightful dashboards.</p><p>Thank you for joining me in this exciting exploration of real-time data engineering. I look forward to completing our journey in the upcoming article! Finally, if you wanna connect with me on Linkedin and share thoughts about ml/data engineering applications, you can find me in <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">here</a>. Also, you can find the full project in <a href="https://github.com/firefly-cmd/data-engineering-template">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55b99bcc2c5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL and…]]></title>
            <link>https://medium.com/@fatikir15/end-to-end-real-time-data-engineering-a-project-template-guide-with-kafka-spark-postgresql-and-337bdabd243a?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/337bdabd243a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Wed, 08 May 2024 15:06:53 GMT</pubDate>
            <atom:updated>2024-05-19T10:58:22.718Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL and Dash | </strong>Part 1: Data Production and Messaging</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e3EePunuoOa1uqO-" /><figcaption>Photo by <a href="https://unsplash.com/@realaxer?utm_source=medium&amp;utm_medium=referral">T K</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In today’s fast-paced world, the ability to process and analyze data in real time is more than a luxury — it’s a necessity for any business that aims to deliver timely insights and respond quickly to market changes. This is where real-time data engineering comes into play, forming the backbone of analytics platforms that can handle streaming data efficiently and effectively.</p><p>This series, “End-to-End Real-Time Data Engineering: A Project Template Guide with Kafka, Spark, PostgreSQL, and Dash,” is designed to provide a comprehensive walk-through of setting up a real-time data pipeline, from initial data production and messaging to processing, storage, and finally, interactive visualization.</p><p><strong>Part 1: Data Production and Messaging</strong>, focuses on the foundational step of our pipeline: producing and sending data using Kafka. Here, we’ll explore how to set up a Kafka Python producer to generate and send data streams and how to configure Apache Kafka using Docker-Compose for robust, scalable messaging. This part not only sets the stage for more complex processing in later sections but also highlights the importance of a well-architected data production mechanism.</p><p>We’ll cover the following key areas in this part:</p><ul><li><strong>Building a Kafka Python Producer Service</strong>: We’ll create a producer that generates fake data to simulate real-time application log data feeds and to integrate it with other components we will create a service to use it inside the docker compose.</li><li><strong>Setting Up Kafka with Docker-Compose</strong>: To ensure our Kafka setup is both scalable and easy to manage, we’ll use Docker-Compose, going through configuration and operational insights to get our messaging infrastructure up and running smoothly.</li><li><strong>Debugging and Viewing Data</strong>: No setup is complete without the ability to debug and verify that everything is working as expected. We’ll look at how to use Kafka’s console consumer and other tools to view the data and troubleshoot any issues that arise.</li></ul><p>As we delve into these topics, keep in mind that this is just the beginning. In the upcoming parts of this series, we will expand our pipeline to include real-time data processing with Apache Spark and PostgreSQL in <strong>Part 2</strong>, and create interactive visualizations using Plotly Dash in <strong>Part 3</strong>. These later parts will be linked here once published, forming a complete guide to real-time data engineering.</p><p>Stay tuned, and let’s embark on this journey to unlock the full potential of real-time data pipelines!</p><h3>Building a Kafka Python Producer Service</h3><p>In order to build our service, we need out producer logic in a python script, a Dockerfile to define the container of this python script and a requirements.txt file to install the required dependencies for our python script to run in a containerized environment. Place all these files inside a kafka_producer folder to separate the services from each other in folder level.</p><p>Lets start building our kafka producer service with the python producer script, we will call it produce_log_data.py. The script is using confluent_kafka library to interact with the kafka. Lets import the necessary libraries and modules for our producer:</p><pre>import json<br>import random<br>from datetime import datetime<br>from time import sleep<br>import numpy as np<br>from confluent_kafka import Producer</pre><ul><li>json: Used to encode data structures to JSON format, a common data interchange format. We will publish our messages in json format to kafka for ease of use.</li><li>random: Utilized to generate random numbers, select random elements from lists, which helps in simulating more realistic log data.</li><li>datetime: Needed to stamp logs with the current date and time.</li><li>sleep: Helps in simulating a delay between consecutive log productions, making the simulation more realistic.</li><li>numpy (np): Used here mainly for choosing messages based on predefined probabilities, ensuring some messages are more frequent than others.</li><li>confluent_kafka.Producer: This is the Kafka producer class from the Confluent Kafka library, which is responsible for sending messages to the Kafka cluster.</li></ul><p>Next, we need to configure our producer and create one:</p><pre>conf = {<br>    &quot;bootstrap.servers&quot;: &quot;kafka:9092&quot;,<br>    &quot;client.id&quot;: &quot;log-producer&quot;,<br>    &quot;api.version.request&quot;: True,<br>    &quot;security.protocol&quot;: &quot;PLAINTEXT&quot;,<br>}<br>producer = Producer(conf)</pre><ul><li>bootstrap.servers: Specifies the Kafka broker(s) that the producer will connect to. In this case, it’s connecting to Kafka on kafka:9092.</li><li>client.id: A user-specified string sent in each request to help trace calls. It can be used in Kafka logs and server-side request logging.</li><li>api.version.request: This configuration ensures the producer uses the correct version of the Kafka API.</li><li>security.protocol: Indicates the protocol used to communicate with brokers. Here, it&#39;s set to PLAINTEXT, but in production, you should use SSL or SASL_SSL for security.</li><li><strong>Producer Instance</strong>: The producer is an instance of the Producer class, initialized with the configuration above, ready to send messages to the Kafka cluster.</li></ul><p>Now, an optional part, we can create a delivery report callback function to debug if our messages are successfully published to kafka or not. This function will be triggered every time a message is published from our kafka producer:</p><pre>def delivery_report(err, msg) -&gt; None:<br>    &quot;&quot;&quot;<br>    Callback for reporting the delivery status of a message.<br>    &quot;&quot;&quot;<br>    if err is not None:<br>        print(f&quot;Message delivery failed: {err}&quot;)<br>    else:<br>        print(f&quot;Message delivered to {msg.topic()} [{msg.partition()}]&quot;)</pre><p>After configuring things, we can simulate our log data. In your projects, you can change this part to produce any kinds of fake data or you can replace this part with your ingestion logic from real sources:</p><pre>def simulate_log_data(application_id: int) -&gt; str:<br>    &quot;&quot;&quot;<br>    Simulate log data for a given application ID, generating logs with different<br>    levels, response types, and other attributes.<br>    &quot;&quot;&quot;<br>    urls = [&quot;/api/data&quot;, &quot;/api/info&quot;, &quot;/api/login&quot;, &quot;/api/logout&quot;]<br>    user_agents = [<br>        &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36&quot;,<br>        &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15&quot;,<br>        &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0&quot;,<br>        &quot;Mozilla/5.0 (iPhone; CPU iPhone OS 13_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Mobile/15E148 Safari/604.1&quot;,<br>    ]<br>    log_levels = [&quot;INFO&quot;, &quot;WARNING&quot;, &quot;ERROR&quot;, &quot;DEBUG&quot;]<br>    messages = [&quot;User logged in successfully&quot;, &quot;User attempted a failed login&quot;, ...]<br>    response_statuses = [200, 404, 500, 200, 400]<br>    weights = [0.6, 0.05, 0.15, 0.1, 0.1]<br><br>    message_index = np.random.choice(len(messages), p=weights)<br><br>    log_data = {<br>        &quot;timestamp&quot;: datetime.now().isoformat(),<br>        &quot;application_id&quot;: f&quot;app_{application_id}&quot;,<br>        &quot;log_level&quot;: random.choice(log_levels),<br>        &quot;error_code&quot;: response_statuses[message_index],<br>        &quot;message&quot;: messages[message_index],<br>        &quot;request_type&quot;: random.choice([&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;]),<br>        &quot;url&quot;: random.choice(urls),<br>        &quot;user_agent&quot;: random.choice(user_agents),<br>        &quot;session_id&quot;: f&quot;session_{random.randint(1, 10)}&quot;,<br>        &quot;response_time_ms&quot;: (<br>            random.randint(100, 1000)<br>            if response_statuses[message_index] == 200<br>            else None<br>        ),<br>    }<br><br>    return json.dumps(log_data)</pre><ul><li>urls and user_agents: Lists that simulate the endpoint being accessed and the browser or tool making the request.</li><li>log_levels: Different severity levels of the logs.</li><li>messages and response_statuses: Lists of possible messages and their corresponding HTTP response statuses.</li><li>weights: Probabilities associated with each message to simulate the frequency of certain types of messages.</li><li>message_index: Uses numpy to select an index based on the specified weights, making some messages appear more frequently.</li></ul><p>This function builds a dictionary of log attributes, including a timestamp, the simulated application ID, and other details about the log event. Uses randomness to fill in most values to simulate different scenarios. Converts the dictionary to a JSON string which can then be sent to Kafka.</p><p>Then, last major part of this script is to of course publishing the data:</p><pre>def produce_data() -&gt; None:<br>    &quot;&quot;&quot;<br>    Continuously produce simulated log data for multiple applications and send<br>    it to a Kafka topic with a callback for delivery reports.<br>    &quot;&quot;&quot;<br>    application_count = 3  # Number of different applications<br>    while True:<br>        for application_id in range(1, application_count + 1):<br>            data = simulate_log_data(application_id)<br>            producer.poll(0)<br>            producer.produce(&quot;logs&quot;, value=data, callback=delivery_report)<br>            print(f&quot;Sent data: {data}&quot;)<br>        producer.flush()<br>        sleep(0.1)</pre><ul><li>application_count: Defines how many different applications are simulating log data.</li><li>Infinite loop (while True): Ensures continuous production of data.</li><li>For each application, generates log data, sends it to the Kafka topic logs, and optionally prints the data to the console.</li><li>producer.poll(0): Serves delivery reports (if any) from previous produce calls.</li><li>producer.produce(...): Sends the message to the Kafka topic with the specified value and delivery report callback.</li><li>producer.flush(): Ensures all messages are sent before sending new ones after a short delay (sleep(0.1))</li></ul><p>Finally the last part of this script is to call the related functions:</p><pre>if __name__ == &quot;__main__&quot;:<br>    produce_data()</pre><p>This is a Python standard for executing the main function when the script is run as the main module.</p><p>Now, that our python script is done, we need to create requirements.txt file for dependencies. Create a file called requirements.txt and place these lines inside it:</p><pre>confluent-kafka==2.3.0<br>numpy==1.21.2</pre><p>This is it for this file. Last of all, create a Dockerfile. This will run our application inside a container when we combine other services with docker-compose:</p><pre><br>FROM python:3.9-slim<br><br>WORKDIR /usr/src/app<br><br>COPY . .<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>CMD [&quot;python&quot;, &quot;produce_log_data.py&quot;]</pre><ul><li><strong>FROM python:3.9-slim</strong>: This line specifies the base image for the Docker image. Here, we are using the official Python image (python), version 3.9-slim. The slim version is a lighter version of the Python image that contains the essential components needed to run Python applications but omits many of the additional tools and libraries included in the full Python image. This choice helps keep our Docker image size smaller, which is beneficial for storage, speed, and security.</li><li><strong>WORKDIR /usr/src/app</strong>: This directive sets the working directory for any RUN, CMD, ENTRYPOINT, COPY, and ADD instructions that follow in the Dockerfile. By setting it to /usr/src/app, you ensure that all subsequent commands are run from this directory in the container. This path is also where your application code will reside within the container.</li><li><strong>COPY . .</strong>: This line copies the contents of the current directory (where the Dockerfile resides) into the container at the current working directory (/usr/src/app). This means your Python scripts, requirements.txt, and any other files in the same directory as your Dockerfile are copied into the image.</li><li><strong>RUN pip install --no-cache-dir -r requirements.txt</strong>: This command installs the Python dependencies defined in requirements.txt using pip, the Python package installer. The --no-cache-dir option tells pip not to cache any of the intermediate artifacts that are usually saved between builds. This reduces the Docker image size by avoiding the storage of unnecessary files.</li><li><strong>CMD [&quot;python&quot;, &quot;produce_log_data.py&quot;]</strong>: This is the default command that the container runs when you start it up. Here, it runs the Python interpreter and executes the produce_log_data.py script. The CMD instruction does not execute anything at build time, but specifies the intended command for the container at runtime. If you run the container without specifying any command, this script will execute. However, if you provide a different command when running the container, it will override this default.</li></ul><p>This is it. After creating all the necessary files, our kafka producer service is ready. The final folder structure should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*bswtT_Mh-vDQAx1rZH9wUA.png" /></figure><h3>Setting up Kafka with Docker-Compose</h3><p>In order to setup kafka, we only need to define the containers needed for kafka and zookeeper, we do not need to create any other file.</p><p>Create a docker-compose.yml file in the main folder of the project. It should be on the same level as the kafka_producer folder. In the docker compose file we will define our kafka_producer service as well to connect our producer service with kafka service.</p><pre>version: &quot;3.3&quot;<br><br>networks:<br>  bridge:<br>    driver: bridge<br><br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:latest<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 32181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    networks:<br>      bridge:<br>        aliases:<br>          - zookeeper<br><br>  kafka:<br>    image: confluentinc/cp-kafka<br>    depends_on:<br>      - zookeeper<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:32181<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,EXTERNAL://0.0.0.0:29092<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,EXTERNAL://localhost:29092<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT<br>      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>    ports:<br>      - &quot;29092:29092&quot;<br>    networks:<br>      bridge:<br>        aliases:<br>          - kafka<br><br>  kafka-producer:<br>    build: ./kafka_producer<br>    depends_on:<br>      - kafka<br>    environment:<br>      KAFKA_BROKER_URL: &quot;kafka:9092&quot;<br>    networks:<br>      bridge:<br>        aliases:<br>          - kafka-producer</pre><ul><li><strong>version: &quot;3.3&quot;</strong>: Specifies the version of the Docker Compose file format. This version supports most Docker features and is compatible with Docker Engine releases 17.06.0+.</li><li><strong>Networks Configuration</strong>:</li><li><strong>bridge</strong>: Defines a custom network named bridge using the bridge driver.</li><li><strong>driver: bridge</strong>: The bridge driver creates a private internal network that by default is isolated from other networks. Services connected to the same bridge network can communicate, while those on different bridge networks cannot.</li><li>The services section defines the containers that are part of the Kafka setup.</li><li><strong>Zookeeper service:</strong></li><li><strong>zookeeper:</strong> This service runs Zookeeper, which is crucial for Kafka&#39;s operation as it manages the state of the Kafka cluster nodes and partitions.</li><li><strong>image: confluentinc/cp-zookeeper:latest</strong>: The Docker image used for the Zookeeper service, using the latest version of Confluent&#39;s Zookeeper image.</li><li><strong>ZOOKEEPER_CLIENT_PORT: 32181</strong>: The port Zookeeper listens on for client connections. This port must match the one Kafka uses to connect to Zookeeper.</li><li><strong>ZOOKEEPER_TICK_TIME: 2000</strong>: The length of a single tick, which affects timeouts in Zookeeper (in milliseconds). This is used to configure Zookeeper&#39;s internal timing.</li><li>Networks and Aliases (Zookeeper):</li><li>Connects the Zookeeper service to the bridge network.</li><li><strong>aliases: - zookeeper</strong>: Allows other services to refer to this service as zookeeper within the bridge network, simplifying service discovery.</li><li><strong>Kafka service:</strong></li><li><strong>kafka:</strong> Defines the Kafka broker service. It uses Zookeeper to manage its state and metadata about topics, partitions, and more.</li><li><strong>image: confluentinc/cp-kafka</strong>: The Docker image for Kafka, using the latest Confluent Platform version of Kafka.</li><li><strong>depends_on: - zookeeper</strong>: Ensures that the Zookeeper service is started before the Kafka service.</li><li><strong>KAFKA_BROKER_ID: 1</strong>: Unique identifier for the Kafka broker in the cluster.</li><li><strong>KAFKA_ZOOKEEPER_CONNECT: zookeeper:32181</strong>: Connection string for Kafka to find Zookeeper. Uses the Zookeeper alias and the client port.</li><li><strong>KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,EXTERNAL://0.0.0.0:29092</strong>: Defines the listeners and the ports they use. PLAINTEXT is the internal listener, and EXTERNAL is for external connections.</li><li><strong>KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,EXTERNAL://localhost:29092</strong>: Advertised listeners define how clients connect to Kafka. PLAINTEXT is for internal communications and EXTERNAL for external clients.</li><li><strong>KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT</strong>: Maps listener names to security protocols. Here, both are PLAINTEXT.</li><li><strong>KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT</strong>: The listener name for inter-broker communication.</li><li><strong>KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1</strong>: Replication factor for offset topic. Set to 1 for single-broker setups but should be higher in production for fault tolerance.</li><li><strong>Ports</strong>:</li><li><strong>&quot;29092:29092&quot;</strong>: Maps port 29092 on the host to port 29092 on the Kafka container, allowing external applications to connect to Kafka.</li><li>Networks and Aliases (Kafka):</li><li>Connects Kafka to the bridge network.</li><li><strong>aliases: - kafka</strong>: Allows other services to refer to this service as kafka within the bridge network.</li><li><strong>Kafka Producer Service:</strong></li><li><strong>kafka-producer:</strong> Defines a custom service that runs the Kafka producer application, which sends simulated log data to the Kafka cluster.</li><li><strong>build: ./kafka_producer</strong>: Specifies the directory containing the Dockerfile that builds the Kafka producer image. This directive tells Docker Compose to build the image from the source rather than pulling from a registry.</li><li><strong>depends_on: - kafka</strong>: Ensures that the Kafka service is started before the Kafka producer service.</li><li><strong>KAFKA_BROKER_URL: &quot;kafka:9092&quot;</strong>: Provides the Kafka producer with the connection string to connect to the Kafka service. This URL uses the Kafka service alias and the internal listener port.</li><li>Networks and Aliases (Kafka Producer):</li><li>Connects the Kafka producer to the bridge network.</li><li><strong>aliases: - kafka-producer</strong>: Allows other services to refer to this service as kafka-producer within the bridge network.</li></ul><p>After defining our docker compose file, we can run it by simply running:</p><pre>docker-compose up --build</pre><p>This will first build the producer service and pull the required images for kafka and zookeeper and start the containers. You can start the container statuses with the command</p><pre>docker ps</pre><p>This will list all the active containers. The nice thing about docker-compose is that we can connect to the individual containers and applications as well. Moreover, confluent kafka docker image allows us to use the cli consumer to consume messages from the terminal. You can use this command is like this:</p><pre>docker exec -it &lt;kafka_container_id&gt; kafka-console-consumer --bootstrap-server localhost:29092 --topic &lt;topic_name&gt; --from-beginning</pre><p>You can find the kafka container id by docker ps command and you can change the topic name with the topic you used in the kafka producer service.</p><p>And that is it. In this first installment of our series, we’ve laid the foundation for a robust real-time data engineering pipeline. By setting up a Kafka Python Producer and configuring our Kafka and Zookeeper services with Docker Compose, we have established a scalable and flexible environment that can handle the demands of real-time data processing.</p><p><strong>What’s Next?</strong></p><ul><li><a href="https://medium.com/p/55b99bcc2c5c"><strong>In Part 2</strong></a>, we will dive into the processing of these data streams using Apache Spark. We’ll explore how Spark Streaming can be utilized to analyze data in real time, applying transformations and computations to extract meaningful insights from our data.</li><li><a href="https://medium.com/@fatikir15/end-to-end-real-time-data-engineering-a-project-template-guide-with-kafka-spark-postgresql-and-d4f9ffd94738"><strong>In Part 3</strong></a>, we’ll complete our journey by developing interactive visualizations using Plotly Dash. This will allow us to present our processed data in an informative and engaging manner, making it accessible to users and decision-makers.</li></ul><p>Thank you for joining me in this exciting exploration of real-time data engineering. I look forward to continuing our journey in the upcoming articles! Finally, if you wanna connect with me on Linkedin and share thoughts about ml/data engineering applications, you can find me in <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">here</a>. Also, you can find the full project in <a href="https://github.com/firefly-cmd/data-engineering-template">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=337bdabd243a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Tools for Your AI Team: A YouTube Blog Post Generator using CrewAI and Gemini Pro]]></title>
            <link>https://medium.com/@fatikir15/how-to-create-tools-for-your-ai-team-a-youtube-blog-post-generator-using-crewai-and-gemini-pro-1b65f13ff2ca?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b65f13ff2ca</guid>
            <category><![CDATA[crew-ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 12:50:01 GMT</pubDate>
            <atom:updated>2024-03-03T12:50:01.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oLkzlFZNo8NcZ2uq" /><figcaption>Photo by <a href="https://unsplash.com/@simonkadula?utm_source=medium&amp;utm_medium=referral">Simon Kadula</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a team of highly specialized assistants, each with a unique skillset, working together to complete a complex task. This is the essence of AI agents — virtual collaborators within Crew AI that tackle specific objectives in a coordinated fashion.</p><p>Each agent possesses its own expertise. One might be a master of information retrieval, sifting through mountains of data to find the perfect nugget. Another might be a gifted writer, crafting compelling narratives from raw materials. Yet another could be a critical evaluator, ensuring the final product is polished and error-free.</p><p>These agents communicate and collaborate, passing information back and forth, to achieve a shared goal. Like a well-oiled machine, each agent contributes its unique strength, resulting in a more efficient and effective outcome.</p><p><strong>But why are tools so crucial for this AI team?</strong> Simply put, tools empower each agent to excel at its specific role.</p><p>Think of it like equipping your assistants with the right equipment. A transcript retrieval agent might leverage a tool like a YouTube API to access video transcripts swiftly. A content writer agent might use a grammar checker or style guide to ensure their writing is flawless. By providing the right tools, we unlock the full potential of each agent within the Crew AI team.</p><p>This collaborative approach, powered by specialized agents and the right tools, promises exciting possibilities for content creation, research, and more. In the next section, we’ll delve into how this translates to a practical tool for building educational content using the power of YouTube and Crew AI.</p><p>Before we begin, I highly recommend to check my initial article about CrewAI and Gemini Pro:</p><p><a href="https://medium.com/@fatikir15/how-to-create-an-ai-team-to-write-compelling-stories-with-crewai-and-gemini-pro-3713f53c72c4">How to create an AI team to write compelling stories with CrewAI and Gemini Pro</a></p><h4>Setting Up the Environment</h4><p>First, we will need some libraries to use. You can load these libraries via pip:</p><pre>pip install crewai</pre><pre>pip install langchain-google-genai</pre><pre>pip install youtube-transcript-api</pre><p>Now, we can start building our project. First, we would start by importing our necessary libraries and functions and creation our custom tool:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/851c8df54278c99aec97fedff27c3f41/href">https://medium.com/media/851c8df54278c99aec97fedff27c3f41/href</a></iframe><p>First, we need a helper function to parse the given youtube url into youtube video id since youtube_transcript_api module works with youtube video ids, not with the youtube urls.</p><p>Since urls comes with a fixed structure, we can extract the video id information using regex. Python has a built-in package for this and if you do not what a regex are you can check <a href="https://docs.python.org/3/library/re.html">this</a> module</p><p>After converting the youtube video url into video id, we can directly get the transcript with timestamps using a simple function call like here:</p><pre>transcript = YouTubeTranscriptApi.get_transcript(video_id)</pre><p>This trancript will be an array of dictionaries that has a text and timestamp information for that text. We need to convert this data into a single string so that our agents can use it easily by joining strings to each other.</p><p>When the logic of the function is ready, we need a decorator function to mark our custom function as a langchain tool function. For that, we will use tool decorator from langchain like this:</p><pre>@tool(&quot;Useful to retreive youtube video transcriptions from a youtube url&quot;)</pre><p>Important point here is that, we need to make sure that the explanation that we will give to the decorator should represent what the custom function does clearly. CrewAI agents will use this information to select necessary tools when they are needed.</p><p>Then, we can continue with connecting to the Gemini Pro and building our agents. We will create 4 agents in our task, a search agents that will retrieve the transcription from the youtube, a content writer that will use that transcription to write content, a content evaluator to review the content before outputting an a blog post creator to organize the other agents.</p><p>We can do all these things using this code block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2563e26d719d3e29283b13f800888014/href">https://medium.com/media/2563e26d719d3e29283b13f800888014/href</a></iframe><p>The important part is here is that, for the search agent, we added our tool by giving an extra property like this:</p><pre>tools=[retreive_youtube_transcription]</pre><p>Every agent can use multiple tools and it can be given as a list. Our custom tool will be used when necessary. After defining our agents, we need to create a user input prompt to enter the url in order to be used by the agents. You can create a nice visual interface using Streamlit or Gradio, but for the sake of simplicity we will add a terminal prompt only.</p><p>Then, we will create 2 separate tasks, first task being the transcription retrieval and the second task would be creating the content. We can do all these things by this code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c3f5e715aa69ba2781a625f1705a124/href">https://medium.com/media/4c3f5e715aa69ba2781a625f1705a124/href</a></iframe><p>Finally, we will construct our crew with our agents and submit our tasks to our crew and start the process like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b0dfdbb331e9dacd8d0bab2e09c9f5/href">https://medium.com/media/74b0dfdbb331e9dacd8d0bab2e09c9f5/href</a></iframe><p>Important part here is that, since this is a sequential process, meaning that we need to retrieve the transcription data before the content writing, we need to write the retrieval task before the content task in the tasks parameter like this:</p><pre>tasks=[retreival_task, content_task]</pre><p>and that’s it. Our crew is ready to create content from youtube videos. You can create any number of tools and use them into building AI teams of your own using this structure and automate your tasks easily. You can find the full code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d4cdfd6ee00b73f99a782e65fface31/href">https://medium.com/media/0d4cdfd6ee00b73f99a782e65fface31/href</a></iframe><p>If you like this article and excited about the more advanced implementations you can visit the CrewAI <a href="https://www.crewai.com/">website</a>. Finally, if you wanna connect with me on Linkedin and share thoughts about ml/data engineering applications, you can find me in <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b65f13ff2ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create an AI team to write compelling stories with CrewAI and Gemini Pro]]></title>
            <link>https://medium.com/@fatikir15/how-to-create-an-ai-team-to-write-compelling-stories-with-crewai-and-gemini-pro-3713f53c72c4?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/3713f53c72c4</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[crew-ai]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 19:14:29 GMT</pubDate>
            <atom:updated>2024-02-16T19:14:29.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tSnoOxxIGtrwdUT8" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Are you fascinated by the idea of AI generating stories that capture the imagination? If so, you’re not alone! In this article, we’ll dive into an introductory project that combines the powers of CrewAI and Gemini Pro to create an agent network that crafts short stories with a little help from user input. Whether you’re a budding programmer, a storyteller looking to explore digital frontiers, or simply curious about the potential of artificial intelligence, this guide is for you.</p><h4>What are CrewAI and Gemini Pro?</h4><p>Before we jump into the nuts and bolts of building our AI storyteller, let’s clarify what CrewAI and Gemini Pro are.</p><p><strong>CrewAI</strong> is a fascinating framework designed to orchestrate multiple AI agents, each with its own unique skills and responsibilities, to collaborate on complex tasks. Think of it as a director managing a team of actors, where each actor plays a specific role to bring a story to life. In the context of our project, CrewAI enables us to create a team of specialized agents (like screenwriters, critics, and story masters) to work together on writing stories.</p><p><strong>Gemini Pro</strong>, on the other hand, is a state-of-the-art language model developed by Google. It’s known for its ability to understand and generate human-like text, making it an ideal candidate for creative tasks such as storytelling. By leveraging Gemini Pro, we can ensure our agents have a solid foundation for generating compelling narrative content.</p><h4>Why is This Kind of Structure Important?</h4><p>The combination of CrewAI and Gemini Pro enables a highly collaborative and specialized approach to story generation. This structure allows for:</p><ol><li><strong>Specialization</strong>: Each agent can focus on what it does best, whether it’s crafting dialogue, ensuring consistency, or overseeing the project.</li><li><strong>Collaboration</strong>: Agents can work together, combining their strengths to produce a story that’s greater than the sum of its parts.</li><li><strong>Flexibility</strong>: The setup is highly adaptable, allowing for different story elements to be emphasized or altered based on user input or creative direction.</li></ol><h4><strong>Setting Up the Environment</strong></h4><p>First, we will need some libraries to use. You can load these libraries via pip:</p><pre>pip install crewai</pre><pre>pip install langchain-google-genai</pre><p>After loading the necessary libraries we can start coding. We will start by importing our necessary modules and initialize our Gemini pro api connection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff27dfef0daea4c154f7746a46f8252a/href">https://medium.com/media/ff27dfef0daea4c154f7746a46f8252a/href</a></iframe><p>As you may notice, we will need an API key for Gemini model. You can create this key in Google AI Studio for <a href="https://ai.google.dev/">free</a>. After that, you can copy this key into google_api_key variable or you can load it into environment by running this command in your command line:</p><pre>export GOOGLE_API_KEY=YOUR_KEY</pre><p>Replace the api key that you will get from google ai studio with YOUR_KEY.</p><p>Next, we define our agents: the Screenwriter, Critic, and Story Master. Each agent is assigned a role, goal, and backstory to guide its contributions to the story generation process.</p><p>For example, the Screenwriter is focused on translating ideas into engaging scenes, while the Critic ensures consistency and adherence to genre.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2198e5a19131944516b629cfb7d261d2/href">https://medium.com/media/2198e5a19131944516b629cfb7d261d2/href</a></iframe><p>These agents will work together and create an engaging story. The story master will accept the task, then it will delegate and coordinate tasks between other agents. We allow this behavior by setting allow_delegation parameter to True.</p><p>With our agents ready, we prompt the user for a story idea. This input is then used to create a task that outlines what the story should include, guiding the agents in their creative process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3db5a5538049838d9d75f670d49d7348/href">https://medium.com/media/3db5a5538049838d9d75f670d49d7348/href</a></iframe><p>While creating the task, we submit the task to the story master since it will coordinate our story creation process.</p><p>Finally, we should combine these agents into a crew and run our task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38bf57803b389d40437c39d3ba007f9a/href">https://medium.com/media/38bf57803b389d40437c39d3ba007f9a/href</a></iframe><p>And thats it. When we run this code, it will prompt the user to give a story idea and then write a short story by agent cooperation. Of course, there is much more than this in the CrewAI framework such as tool usage, hierarchical processing, working with ollama to run agents fully locally with different agents etc, but these topics are for another article.</p><p>You can find the full code in here for directly run:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dea09d552036ed8e677cc7e95e7954af/href">https://medium.com/media/dea09d552036ed8e677cc7e95e7954af/href</a></iframe><p>You can use this code as a template for these kinds of applications, you can build game builder crew, stock analyzer crew, marketing crew etc. With imagination, sky is the limit. If you like this article and excited about the more advanced implementations you can visit the CrewAI <a href="https://www.crewai.com/">website</a>. Finally, if you wanna connect with me on Linkedin and share thoughts about ml applications, you can find me in <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3713f53c72c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Speech Privately: A Journey with Whisper, Streamlit, and FastAPI]]></title>
            <link>https://medium.com/@fatikir15/decoding-speech-privately-a-journey-with-whisper-streamlit-and-fastapi-4ecba1650efb?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ecba1650efb</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 15:25:19 GMT</pubDate>
            <atom:updated>2024-01-17T15:25:19.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7cIec5RkBT6aLSlG" /><figcaption>Photo by <a href="https://unsplash.com/@glencarrie?utm_source=medium&amp;utm_medium=referral">Glen Carrie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Welcome to a quick tour of my latest project — a local audio transcription service that speaks volumes about the power of combining modern tech tools. I’ve taken OpenAI’s Whisper model for its stellar transcription capabilities, paired it with the robustness of FastAPI, and wrapped it up with a user-friendly Streamlit frontend and best of all is it works on cpu so that you do not require fancy gpu devices.</p><p>Why keep it local? It’s all about having the reins in your hands — your data, your rules. Plus, it’s a great way to get hands-on with some of the coolest tech out there. This isn’t just a functional tool; it’s a learning experience and a stepping stone for anyone looking to dive into the world of app development.</p><h3><strong>Overview of the Project</strong></h3><p>In this section, we’ll take a bird’s-eye view of the project’s architecture and outline the journey from audio file to transcribed text. The service is structured into two main parts, each responsible for specific functions:</p><ul><li><strong>Part 1: The FastAPI Backend</strong>: We’ll examine how the backend manages the audio files, interacts with the transcription model, and ensures that the process runs smoothly and efficiently.</li><li><strong>Part 2: The Streamlit Frontend</strong>: This portion will explain the frontend’s role in providing a user interface, detailing how users interact with our service to submit and receive their transcriptions.</li></ul><p>This setup illustrates a common pattern in modern web application design: a responsive frontend paired with a powerful backend. In the following sections, we’ll explore the specifics of each part, highlighting the technical choices and the steps involved in bringing this service to life.</p><h3><strong>Part 1: The FastAPI Backend</strong></h3><p>The backbone of our transcription service is a FastAPI backend, a dependable framework adept at managing the complexities of audio processing. Let’s step through the key components that define the structure and functionality of our backend system.</p><p>First, lets start with the necessary imports for our backend service and initialize our app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd88d8fbd320cfedf443e57b8cb812c4/href">https://medium.com/media/fd88d8fbd320cfedf443e57b8cb812c4/href</a></iframe><p>Next, we will initialize our whisper model and the tasks. Since we would want to trancribe long audio files in our backend, it could take a good amount of time. Also, there could be multiple users connecting to the backend and try to transcribe at the same time. In order to keep track of the transcription tasks, we will store them in a dictionary and check the task status continuously using a status endpoint. But first, lets initialize out model and our tasks using this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfb7f06c68c14a98f192de64f7d4ece6/href">https://medium.com/media/dfb7f06c68c14a98f192de64f7d4ece6/href</a></iframe><p>We will use the tiny version of the whisper model which is the fastest whisper model right now, however you can change the model used by giving its name to the load_model function. You can get more information about whisper models in <a href="https://openai.com/research/whisper">here</a>. The python library of the openai whisper model can be examined in <a href="https://github.com/openai/whisper">here</a>.</p><p>After the required initializations, we need a status check api that we will regularly check if our transcription is over and a task id creation function to create unique ids for the new tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eeefb3e8dfca724289c1ca382d153ff/href">https://medium.com/media/5eeefb3e8dfca724289c1ca382d153ff/href</a></iframe><p>After creating the status check endpoint, we are now at the core function of our transcription service. We need a function to handle file objects that is coming from the streamlit service since we will use file uploader widget of streamlit. We need to first convert this uploded file object into required audio format of whisper which is a file path or a numpy array.</p><p>Since we would have already uploded the file into streamlit, we can convert it into required numpy array structure using couple of transformations. Then we will make the transcription and return the results</p><ul><li>We will get the byte object from the file object</li><li>We will convert this bytes object into an audio object with the required 16Khz sampling rate and single channel properties using pydub</li><li>Then we will create required numpy array with the correct datatypes. Whisper uses float32 for cpu use.</li><li>After finalizing the required transformations, we will feed the numpy array into the loaded whisper model and update the task status</li></ul><p>All these steps can be achieved with this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6c9c7a6cf30034c80dfcad46fb309ca/href">https://medium.com/media/f6c9c7a6cf30034c80dfcad46fb309ca/href</a></iframe><p>Finally, we would need an endpoint for our transcription logic. This endpoint will create a task and start the trancription logic in the background:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0509c6c9c5a34d93f3e4d027f7fdddb1/href">https://medium.com/media/0509c6c9c5a34d93f3e4d027f7fdddb1/href</a></iframe><p>You can combine all these parts into a single backend.py file and run the FastAPI server on localhost using this command:</p><pre>uvicorn backend:app --host 0.0.0.0 --port 8000</pre><p>Then, you can see your FastAPI docs and endpoint information at: <a href="http://localhost:8000/docs">http://localhost:8000/docs</a></p><p>It will show something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCGwJQQnj0h141Pcw2d1tA.png" /></figure><p>We are good to go now for the frontend part!!!</p><h3><strong>Part 2: The Streamlit Frontend</strong></h3><p>After setting up the backend with FastAPI, the next step is crafting an intuitive and user-friendly frontend. For this, we turn to Streamlit, an excellent choice for creating interactive web applications with minimal hassle. Streamlit’s simplicity and flexibility make it an ideal match for our transcription service, allowing us to focus on functionality without getting bogged down in frontend complexities.</p><p>The workflow of our frontend service will be like this:</p><ul><li>There will a file uploaded displayed on the start and user will upload the audio file</li><li>Then, we will send a request to the backend with the loaded file in order to transcription.</li><li>We will poll the results by sending requests to status endpoint and we get the transcription when it is finished</li><li>After the transcription over, we stop the polling and display the transcription in a text area and we will display a download button to download the text that is trancribed.</li></ul><p>The code block for the frontend will be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a8f90e1db30080c08cd8d3509f80665/href">https://medium.com/media/5a8f90e1db30080c08cd8d3509f80665/href</a></iframe><p>Since the backend runs on localhost:8000 we will send our requests to the that server with the endpoint appended to the url. You can run this app with this command:</p><pre>streamlit run frontend.py</pre><p>You can change the frontend.py with the filename that you created for the frontend code. You can reach this app in <a href="http://localhost:8501/">http://localhost:8501/</a> since streamlit uses port 8501 by default. The final app with an example transcription would be look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igij4IxLJP0Cjpj99xcUMw.png" /></figure><h3>Wrap It Up</h3><p>As we wrap up this overview of building a local audio transcription service, it’s clear that combining OpenAI’s Whisper model with FastAPI and Streamlit offers a practical and efficient solution. This project is a straightforward example of how different technologies can work together to solve a common problem: transcribing audio quickly and privately.</p><p>I hope this walkthrough has provided valuable insights and inspiration for your own projects, whether they are for learning, building, or just exploring the possibilities of technology. If want to check this project, more enhanced version which has youtube transcription and real time audio transcription using websockets is <a href="https://github.com/firefly-cmd/VerbalizeIt">here</a>. Finally, if you wanna connect with me on Linkedin and share thoughts about ml applications, you can find me in <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ecba1650efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tiny Transformers for a Big Task: Bird Sound Classification in the Deep Learning Era]]></title>
            <link>https://medium.com/@fatikir15/tiny-transformers-for-a-big-task-bird-sound-classification-in-the-deep-learning-era-f6d291b5a3c0?source=rss-f44f55442950------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6d291b5a3c0</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[bird-sounds]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[sound-classification]]></category>
            <dc:creator><![CDATA[Fatih KIR]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 08:36:07 GMT</pubDate>
            <atom:updated>2023-11-04T08:36:07.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C5ceCqweirZTpjvy" /><figcaption>Photo by <a href="https://unsplash.com/@theshuttervision?utm_source=medium&amp;utm_medium=referral">Jonathan Cooper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Hello and welcome to a hands-on journey into the world of bird songs! Have you ever been out in nature and heard a symphony of birds, each with its unique call, and wished you could identify them? This is where technology lends us a friendly ear. I’ve crafted a neat little project to share with all of you — a simple tool for classifying bird sounds using the power of deep learning. And the best part? It’s a solo adventure I’ve embarked on to create something both informative and easy to follow.</p><p>In this article, we’re going to explore how a compact version of a transformer model can turn the complex task of identifying bird calls into an accessible and engaging activity. It’s not about pushing the boundaries of research; it’s about practical, hands-on learning and sharing a tool that anyone can use for their personal or educational projects.</p><p>Bird song classification has implications beyond mere curiosity. It can help in environmental monitoring and in the preservation of biodiversity. But our focus here is to give you the knowledge and the code to start exploring these sounds on your own, with a model that’s small in size.</p><p>Whether you’re new to programming or looking to add a new skill to your repertoire, I’ve broken down the steps, provided the code, and made sure that this guide is something you can follow independently. By the end of this article, you’ll be equipped to identify our feathered friends by their songs with just a few lines of code and a sprinkle of deep learning.</p><p>So, let’s dive in and discover how we can make sense of nature’s melodies together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2O1u6BmH2MM0IqX5" /><figcaption>Photo by <a href="https://unsplash.com/@janmeeus?utm_source=medium&amp;utm_medium=referral">Jan Meeus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Background: Traditional Bird songs Classification &amp; The Advent of Transformers</h3><p>For years, bird enthusiasts and scientists have relied on various methods to classify bird songs. Traditional approaches often involved meticulous manual work — listening to recordings, analyzing sonograms (visual representations of sound), and using the trained human ear to distinguish subtle differences. The process was labor-intensive and sometimes prone to error, as human analysis can vary widely from person to person.</p><p>As we entered the digital age, machine learning offered new possibilities. Early computational methods included techniques like signal processing and statistical analysis, where features from the audio, such as frequency and time characteristics, were extracted manually and then used to train models like Support Vector Machines (SVMs) or k-Nearest Neighbors (k-NN). While effective, these methods had their limitations, primarily because they relied heavily on handcrafted features, which required expert knowledge and often missed the nuances of complex bird calls.</p><p>Enter Transformers — a groundbreaking architecture first introduced in the paper “Attention is All You Need” by Vaswani et al. in 2017. Transformers revolutionized the field by utilizing self-attention mechanisms to process sequential data, such as text or, in our case, audio signals. This allows them to weigh the importance of different parts of the input data differently, making them particularly adept at handling varying sequences, such as the intricate patterns of bird songs.</p><p>So, why are transformers suitable for bird song classification? Their ability to handle sequential data makes them a natural fit. Bird songs are sequences of varying pitches and rhythms; transformers can analyze these sequences as a whole, capturing the context and the relationship between different sounds within a call. This ability to ‘understand’ the whole sequence, rather than just isolated parts, is what makes them superior for tasks like speech recognition — and by extension, for birdsong classification.</p><p>Additionally, transformers can be trained on large amounts of data, learning to pick up on the vast diversity of bird songs. Their scalable nature means they can handle complex models and large datasets, which is excellent for generalization when classifying sounds from numerous bird species.</p><p>In this guide, we’ll see how a scaled-down transformer can still harness some of the power of this powerful mechanism to classify bird songs effectively. By focusing on mel-spectrograms — a visual representation of the spectrum of frequencies of sound as they vary with time — we can convert bird songs into a format that transformers can process, gaining the benefits of their sophisticated attention mechanisms without the need for immense computational resources. We will build a similar structure like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*aeS2t9hLs_HsFAFcIgSsBw.png" /></figure><p>This structure proposed in <a href="https://ieeexplore.ieee.org/document/9596007">this</a> paper for environmental sound classification. For in depth reading, I highly suggest this paper for applying transformer architectures to the sound data. We will use <a href="https://www.kaggle.com/datasets/luisblanche/birdcall-singing-1">this</a> dataset from Kaggle.</p><p>Now, Let’s jump in by importing all necessary libraries</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/240184155783e1f0eaedc1598d94e5dd/href">https://medium.com/media/240184155783e1f0eaedc1598d94e5dd/href</a></iframe><p>After importing the libraries, we need to load our audio data with labels. This data is structured such that, every bird species sound is in a separate directory. We can use this information to create labels while looping through the directories. Also, we will produce constant length audio clips from these audio files. In order to select the parts where the bird is actually present, we will use onset detection feature of the librosa library. You can find more information about how onsets work in <a href="https://en.wikipedia.org/wiki/Onset_(audio)">here.</a> We will trim our clip to make exactly 3 second of audio for every sound recording starting from the first onset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e2bc78232e95d239d8147776e5fed8/href">https://medium.com/media/70e2bc78232e95d239d8147776e5fed8/href</a></iframe><p>Now, let’s get our data ready for the transformer models. Imagine turning the bird songs into pictures that show different frequencies — these are called mel spectrograms. Think of these pictures as puzzles; we’re going to break them down into smaller pieces, like puzzle pieces. Each piece is like a little clue for our transformer model — similar to how words form sentences. The transformer will look at how these pieces fit together to understand the full picture of the bird’s song.</p><p>Creating mel spectrograms in python is easy, librosa library has already built in functions for this task. If you have problems with memory, you can embed this function into load data function and create the features while loading the data. This will help you reduce the memory footprint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f577a4d83991c939bff21f95aa5d5e/href">https://medium.com/media/e2f577a4d83991c939bff21f95aa5d5e/href</a></iframe><p>In the next phase of our process, we dive into what might seem like a bit of wizardry. We’re going to create small segments, or ‘patches’, from our mel spectrogram ‘images’. These patches carry crucial frequency and time information about the birdsong, but on their own, they lack context — they don’t inherently know where they belong in the full image. That’s where we step in and give them some guidance.</p><p>Just as every piece of a jigsaw puzzle has a unique shape and place, each patch needs to know its position in the original image. So, we assign a special code to each patch — this is known as positional encoding. It’s like giving each patch a home address on the spectrogram grid.</p><p>The transformers we use are quite clever, but they don’t naturally understand the layout of images. They process data in sequences, much like reading text in a book. To communicate with them effectively, we must convert our 2-D patches into a string of 1-D data, like sentences made up of words. Each ‘word’, in our case, is a flattened patch combined with its positional code.</p><p>Let’s look closer at the code that brings this to life:</p><p>The create_image_patches_with_position function is a sophisticated way of breaking down our mel spectrogram images into manageable, meaningful pieces for the transformer to analyze. It works by:</p><ol><li>Defining a grid based on the desired patch size, essentially deciding how many pieces we’ll break our puzzle into.</li><li>Creating a map of positional encodings that correspond to each location on the grid.</li><li>Iterating through each mel spectrogram feature, slicing it into patches according to our grid.</li><li>Attaching the positional encodings to these patches, ensuring each piece carries information about its specific location.</li><li>Flattening the patches to make them 1-D while keeping the positional information tacked on.</li><li>If our sequence of patches is shorter than what the transformer expects which is the number of patches in a single mel spectogram, we pad it with zeros, ensuring consistency in the data we feed the model.</li></ol><p>In doing so, the transformer receives well-structured and context-rich input that it can use to discern patterns and ultimately classify bird songs more accurately.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d63e1dd8c1020e6507a5f04455c99b86/href">https://medium.com/media/d63e1dd8c1020e6507a5f04455c99b86/href</a></iframe><p>In the following stage, we are ready to build the tiny transformer model. The structure of this model is as follows:</p><p><strong>Input Layer</strong>: The model begins with an input layer that takes in sequences shaped according to the input_shape parameter.</p><p><strong>Linear Layer and Batch Normalization</strong>: The first layer is a linear Dense layer with ReLU activation. This layer is responsible for projecting the input data into a higher-dimensional space to prepare for the transformer blocks. The dimensions of this space are defined by the units parameter of the Dense layer. This is followed by batch normalization, which stabilizes learning by normalizing the layer’s outputs. Batch normalization also helps in accelerating the training process.</p><p><strong>Transformer Encoder Blocks</strong>: Each transformer block contains two main components:</p><ul><li><strong>Multi-head Self-Attention</strong>: The MultiHeadAttention layer allows the model to focus on different positions of the input sequence simultaneously, which is crucial for understanding the complex structure of birdsong. The num_heads parameter determines how many different sets of attention weights the model will use. Dropout is included within the attention to prevent overfitting.</li><li><strong>Feed-Forward Network</strong>: This is composed of two dense layers that provide the capacity to learn more complex representations. It follows the self-attention layer in each transformer block.</li></ul><p>Each of these two components has a corresponding residual connection, followed by layer normalization. The residual connections help in avoiding the vanishing gradient problem by allowing gradients to flow through the network more easily.</p><p><strong>Global Average Pooling</strong>: After the data has passed through the transformer encoder blocks, a GlobalAveragePooling1D layer is applied. This operation averages over the sequence dimension, allowing the model to condense the information from all the sequence elements. It&#39;s an effective way to decrease the dimensionality and to prepare the data for the classification layer.</p><p><strong>Classification Head</strong>: The final output is a Dense layer with a number of units equal to the number of classes. This layer is responsible for the final classification.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d21c206e6808e4d80bd055d4b223d759/href">https://medium.com/media/d21c206e6808e4d80bd055d4b223d759/href</a></iframe><p>Finally, we will combine all the functions to work together and make classifications. This workflow will be similar to all other machine learning tasks. We will load data, encode labels, apply a train test split, create features from the data, build and compile the model and finally train the model. You can play with the parameters of the model make it bigger or smaller depending on your needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e13e860d2afe9b4806cb40b5f2a63c70/href">https://medium.com/media/e13e860d2afe9b4806cb40b5f2a63c70/href</a></iframe><p>After training the model, you can evaluate the results with other machine learning or deep learning models for better comparison. Remember, since the transformer models require lots and lots of data get good results, you may see worse results than the other methods.</p><p>To improve the model performance, you can extract more 3 second spectograms from the sound recordings, you may try different feature extraction methods other than the mel spectograms, you can pre-train the transformer with environmental audio data and fine tune it on bird sounds (I will cover this on other articles) etc. There are much more room for improvement on this implementation but you can use this as a baseline. Moreover, change the hard coded dimensions in the code blocks to fit your needs.</p><p>Since this model implementation is around 8k parameters, you can use Tensorflow Lite to convert into usable formats inside the edge devices such as Raspberry Pi or create mobile application with it.</p><p>If you have questions about this implementation you can drop a comment, or if you want to connect with me to discuss AI related advancements, <a href="https://www.linkedin.com/in/fatih-k%C4%B1r/">here is my profile</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6d291b5a3c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>