<?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 Murat Gölyeri on Medium]]></title>
        <description><![CDATA[Stories by Murat Gölyeri on Medium]]></description>
        <link>https://medium.com/@muratglyr33?source=rss-5696de7bf0b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6P0Ed_sRTEAWpSLLi7FDhg@2x.jpeg</url>
            <title>Stories by Murat Gölyeri on Medium</title>
            <link>https://medium.com/@muratglyr33?source=rss-5696de7bf0b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:48:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muratglyr33/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[Your LLM Is Quietly Changing Who Said What]]></title>
            <link>https://medium.com/@muratglyr33/your-llm-is-quietly-changing-who-said-what-53708eb9dea5?source=rss-5696de7bf0b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/53708eb9dea5</guid>
            <category><![CDATA[speech-recognition]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Murat Gölyeri]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 14:57:40 GMT</pubDate>
            <atom:updated>2026-11-24T14:57:40.874Z</atom:updated>
            <content:encoded><![CDATA[<p>A copy-edit can look perfect and still put one person’s words in another person’s mouth. This is how I ran into it, and the small check my pipeline now runs after every LLM edit.</p><figure><img alt="Diagram of three steps: align edited turns with raw turns, vote on the majority label per speaker, flag the turn that deviates." src="https://cdn-images-1.medium.com/max/1024/1*n5qAGQXfrp9LMaq2KkEk6g.png" /><figcaption>Align each edited turn with its source, vote on the label mapping, flag what disagrees.</figcaption></figure><h3>The bug that doesn’t throw</h3><p>I was building <a href="https://github.com/Muratglyr/voicescribe">voicescribe</a>, a speech-to-text pipeline. It transcribes a recording, labels the speakers, and then asks an LLM to fix punctuation and paragraphs. The LLM output was clean and readable, and the labels were consistent. Every sentence was there.</p><p>One of them was attributed to the wrong person.</p><p>In a long conversation between two people, the model had moved a single turn from one speaker to the other. Nothing crashed and no text was missing. Skimming the result, you wouldn’t notice, because the sentence sounded plausible coming from either of them.</p><p>That’s what makes it nasty. The output is well-formed and fluent, so nothing tells you to look closer, yet the meaning has changed. In a meeting transcript it can credit a decision to the wrong person. In a medical or legal record it’s an error that actually matters.</p><p>I’ll start with why it happens, because the cause shapes the fix.</p><h3>Why it happens</h3><p>Looking back, my own pipeline set the model up for it.</p><ol><li>A long transcript doesn’t fit in one request, so it gets split into chunks that are edited one at a time. A chunk that starts mid-conversation gives the model no memory of who has been talking. My first chunker split on sentence boundaries, so a chunk could even start halfway through someone’s turn.</li><li>I let the model replace SPEAKER_00 with a role like &quot;Host&quot; when the role was obvious. Every chunk makes that call on its own, and if one chunk guesses differently, a turn ends up under the other name.</li><li>Fixing punctuation across a turn boundary is a short step from merging two short turns or splitting a long one. Once the turns move, the labels can move with them.</li></ol><p>None of this raises an error, which is exactly why it slips through.</p><h3>Why the obvious checks fail</h3><p>The raw transcript is the ground truth for <em>who</em> spoke, so the check is to compare it with the edited one. The naive ways of comparing them break on edits you actually want.</p><ul><li>Comparing turn <em>i</em> with turn <em>i</em> breaks as soon as the model merges or splits a turn, because every index after it shifts.</li><li>Requiring identical labels breaks on a consistent rename (SPEAKER_00 becomes &quot;Host&quot;), which I had allowed.</li><li>Matching turns by exact text breaks because punctuation, casing and filler words changed, which was the whole point of editing.</li><li>Counting turns per speaker breaks when two turns of the same speaker are merged, even though nothing went wrong.</li></ul><p>Whatever the check does, it can’t rely on positions, exact text or label names.</p><h3>Align, vote, flag</h3><p>The idea fits in three steps.</p><ol><li><strong>Align by content.</strong> For every edited turn, find the raw turn whose text is most similar to it. That raw turn’s speaker is who actually said it. Positions don’t matter, so merges and splits don’t break the pairing.</li><li><strong>Vote on the mapping.</strong> For each raw speaker, count which edited label their turns received. The most common label is the intended one. A consistent rename (SPEAKER_00 becomes &quot;Host&quot; everywhere) wins the vote and is accepted.</li><li><strong>Flag the deviations.</strong> Any turn whose edited label differs from its speaker’s majority label is a likely mix-up.</li></ol><p>Similarity comes from difflib.SequenceMatcher in the standard library. Copy-editing changes punctuation and casing but keeps most characters in place, so an edited turn still scores far higher against its own raw turn than against anyone else&#39;s. In my test transcript every edited turn scored 0.95 to 0.97 against its own raw turn.</p><p>The vote and the flag are the interesting part, and they’re only a few lines once the turns are aligned:</p><pre># pairs: (raw_speaker, edited_label, text) for every edited turn, after alignment<br>votes: dict[str, Counter[str]] = {}<br>for raw_speaker, label, _ in pairs:<br>    votes.setdefault(raw_speaker, Counter())[label] += 1<br>expected = {speaker: counter.most_common(1)[0][0] for speaker, counter in votes.items()}</pre><pre>mixups = [(text, raw, label, expected[raw]) for raw, label, text in pairs if label != expected[raw]]</pre><p>The complete function, including the alignment step and a runnable example, is about 70 lines of standard-library Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8d10a85c32413cbba7709861dae069/href">https://medium.com/media/3c8d10a85c32413cbba7709861dae069/href</a></iframe><p>The full version has three parameters. min_length skips very short turns (&quot;Yeah.&quot;, &quot;Right.&quot;) that would match anything. min_ratio refuses weak pairings instead of forcing a guess. compare_chars caps the cost of each comparison.</p><h3>Seeing it work</h3><p>To show it without publishing anyone’s real conversation, I reproduced the failure on a synthetic podcast about composting. The raw transcript is unpunctuated, as speech-to-text output usually is:</p><pre>SPEAKER_00: and the smell because that is the number one thing people ask me about every single time<br>SPEAKER_01: if it smells bad it is almost always too wet or not enough air so you add more browns and you turn it</pre><p>The “edited” version renames the speakers to Host and Guest, which is fine. It also gives the guest’s last answer to the host, which is not:</p><pre>Host: And the smell, because that is the number one thing people ask me about, every single time.<br>Host: If it smells bad, it is almost always too wet or not enough air. So you add more browns, and you turn it.</pre><p>Running the check on all six turns flags exactly that one:</p><pre>Mixup(text=&#39;If it smells bad, it is almost always too wet or not enough air. So you add more browns, and you turn it.&#39;,<br>      raw_speaker=&#39;SPEAKER_01&#39;, edited_speaker=&#39;Host&#39;, expected_speaker=&#39;Guest&#39;)</pre><p>With the last label corrected to “Guest”, the same check returns an empty list. The rename alone is never reported, because it is consistent.</p><h3>Making it happen less often</h3><p>The check catches mix-ups after the fact. I also changed three things in the pipeline, one for each cause above.</p><p>First, the chunker now splits only between turns. It breaks a turn into sentences only when that one turn is longer than the size limit, so a chunk never opens with half of someone’s turn.</p><p>Second, the system prompt spells out the rule the check enforces. “Fix punctuation” on its own wasn’t enough:</p><pre>NEVER change which sentence belongs to which label: the original grouping and turn<br>boundaries must stay exactly as they are. If you replace the labels with role names,<br>use ONE AND THE SAME name for each label FROM START TO FINISH.</pre><p>Third, the request uses temperature = 0. Copy-editing has one right answer anyway, and a reproducible run is much easier to debug when a mix-up does show up.</p><p>None of this is a guarantee, which is why the check still runs after every edit. It prints the text of the flagged turn, so someone only has to review that turn instead of rereading the whole transcript.</p><h3>Where it falls short</h3><p>The check is deliberately simple, and it has gaps. These are the ones I ran into while testing it.</p><p>Ties are the first one. The vote needs a majority, so if a speaker has only two long turns and one is mislabeled, it’s 1 to 1 and Counter picks whichever label it saw first. In my test, swapping the speaker&#39;s first turn instead of the second made the check flag the correct turn. You still learn that something is off for that speaker, just not which turn. With short recordings, treat every flag as &quot;look here&quot; rather than a verdict.</p><p>Very short turns are skipped. “Yeah.” and “Exactly.” would match half the transcript, so min_length leaves them out, and a mislabeled one-word reply goes unreported. I&#39;m fine with that, since it rarely changes the meaning.</p><p>Near-duplicates can fool the alignment. If both speakers say almost the same thing (“Let’s move on to the next question”), it can pair a turn with the wrong raw turn. min_ratio filters out weak matches, but it can&#39;t choose between two strong ones.</p><p>It gets slow on long recordings. Every edited turn is compared with every raw turn, so the work grows with the square of the length: a synthetic 300-turn transcript took about 8 seconds. Editing only nudges turns around, so comparing each turn with raw turns near the same position would be enough.</p><p>And it assumes the editor keeps the words. SequenceMatcher compares characters, which works for copy-editing. If your LLM paraphrases or translates, character similarity falls apart. In that case swap best_match for embedding similarity and keep the vote and the flagging as they are.</p><h3>The pattern beyond transcripts</h3><p>The same failure can appear whenever an LLM edits content that carries structure the model is not supposed to touch:</p><ul><li>rewording table rows, where a value drifts into the neighboring row</li><li>cleaning up a list of quotes, where a quote moves to another source</li><li>summarizing per-customer notes, where one customer’s issue lands under another</li></ul><p>The same three steps work there too: align each output unit with its source by content, vote on the mapping so a deliberate change is accepted, and flag whatever disagrees. All it needs is the original input. There’s no second model and no extra API call, so it’s cheap enough to run after every edit.</p><p>What I took away from this: a prompt tells the model what you want, but only a check tells you whether you got it. When “looks right” and “is right” can drift apart, it’s worth deciding on the check before polishing the prompt.</p><p>The full implementation, with tests and configuration, is in <a href="https://github.com/Muratglyr/voicescribe">voicescribe on GitHub</a> under src/voicescribe/core/consistency.py.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53708eb9dea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prefect vs Apache Airflow — Which One Should You Choose?]]></title>
            <link>https://medium.com/@muratglyr33/prefect-vs-apache-airflow-which-one-should-you-choose-3c1d837a2117?source=rss-5696de7bf0b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c1d837a2117</guid>
            <dc:creator><![CDATA[Murat Gölyeri]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 12:21:39 GMT</pubDate>
            <atom:updated>2026-01-07T12:21:39.402Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prefect vs Apache Airflow — Which One Should You Choose?</h3><h3>Introduction</h3><p>Data pipelines are the backbone of modern data processing. These systems are used to process, transform, and move large amounts of data, and when managed with the right tools, they offer both reliability and efficiency. But which tool is the right choice for you?</p><p>Prefect and Apache Airflow are two of the most popular options for managing data pipelines. While Apache Airflow has been the industry standard for years, Prefect stands out as a strong alternative with its modern approach to usability and flexibility. In this article, we will compare these two frameworks across various criteria to help you decide which one fits your needs best.</p><h3>Prefect and Apache Airflow</h3><p><strong>Apache Airflow</strong><br>Apache Airflow is a leading framework for data processing and task orchestration, developed by Airbnb in 2014. Using Directed Acyclic Graphs (DAGs), it allows you to define and manage workflows efficiently. Over the years, it has become the industry standard, widely adopted by data engineering teams due to its robust feature set and large community support.</p><p>Key features of Airflow:</p><ul><li>Defining task dependencies via DAGs.</li><li>Workflow scheduling and automation.</li><li>A rich library of integrations (e.g., SQL, AWS, GCP).</li><li>Visual management and monitoring of tasks.</li></ul><p><strong>Prefect</strong><br>Prefect is a modern framework for task orchestration that was introduced in 2018. It aims to simplify task and flow management in data processing while offering a user-friendly experience. Designed with a code-first approach, Prefect allows users to define their workflows directly in Python. It also stands out with its innovative solutions for error handling and monitoring.</p><p>Key features of Prefect:</p><ul><li>Python-native structure for task and flow definitions.</li><li>Real-time monitoring and error handling with Prefect UI.</li><li>Automated task retry mechanisms.</li><li>Distributed computing support via Dask integration.</li></ul><h3>Comparison Criteria</h3><p>Prefect and Apache Airflow will be compared based on the following criteria:</p><ol><li>Ease of Use</li><li>Coding Approach</li><li>Error Handling and Monitoring</li><li>Distributed Processing and Performance</li><li>Community and Support</li><li>Cloud Integration</li></ol><h4><strong>1. Ease of Use</strong></h4><p><strong>Apache Airflow:</strong><br>Airflow has a steep learning curve. Defining task dependencies through DAGs can be challenging, particularly for new users. For example, when designing a workflow, you need to manually configure the sequence of tasks. While the Airflow UI allows you to visualize task flows, detailed configuration often requires extensive effort.</p><p><strong>Prefect:</strong><br>Prefect is Python-native, making it much easier to learn and use. Tasks and flows can be created with simple decorators in just a few lines of code. For instance:</p><pre>from prefect import task, flow<br><br>@task<br>def say_hello(name):<br>    return f&quot;Hello, {name}!&quot;<br><br>@flow<br>def hello_world_flow():<br>    greeting = say_hello(&quot;World&quot;)<br>    print(greeting)<br><br>hello_world_flow()</pre><p>This code creates a simple “Hello World” workflow, showcasing how intuitive workflow creation is with Prefect.</p><h4><strong>2. Coding Approach</strong></h4><p><strong>Apache Airflow:</strong><br>Airflow relies on DAGs (Directed Acyclic Graphs) to define workflows. This structure is powerful for visualizing task dependencies but can feel rigid at times. For example, task dependencies must be explicitly defined like this:</p><pre>task1 &gt;&gt; task2 &gt;&gt; task3</pre><p>This setup specifies that “task2 should run after task1, and task3 should run after task2.” However, managing these dependencies manually can be time-consuming.</p><p><strong>Prefect:</strong><br>Prefect allows workflows to be defined entirely in Python, making the process more flexible and intuitive. Tasks’ dependencies are automatically resolved based on data flow. With Prefect, defining workflows feels more like working with Python functions. Additionally, any task’s output is automatically passed to the next dependent task.</p><h4><strong>3. Error Handling and Monitoring</strong></h4><p><strong>Apache Airflow:</strong><br>Airflow provides task retry mechanisms, but debugging and monitoring workflows can be complex. For instance, when a task fails, analyzing logs is often necessary to identify the root cause. Although Airflow’s UI offers visual tracking of tasks, it lacks detailed error analysis tools.</p><p><strong>Prefect:</strong><br>Prefect excels in error handling and monitoring. The Prefect UI allows real-time tracking of tasks and flows, making debugging much more efficient. For example, if a task fails, you can examine its inputs, outputs, and error messages directly within the UI. Prefect also automates retry mechanisms:</p><pre>@task(retries=3, retry_delay_seconds=10)<br>def fetch_data():<br>    # Simulating API call<br>    raise Exception(&quot;API connection failed&quot;)</pre><p>This code automatically retries the task three times with a 10-second pause between each attempt.</p><h4><strong>4. Distributed Processing and Performance</strong></h4><p><strong>Apache Airflow:</strong><br>Airflow supports distributed processing and is suitable for handling large-scale data. However, setting up distributed workflows requires complex configurations. For instance, implementing distributed execution involves configuring Executors like Celery or Kubernetes.</p><p><strong>Prefect:</strong><br>Prefect integrates seamlessly with Dask for distributed processing, simplifying the management of large-scale workflows. For example:</p><pre>from prefect import flow, task<br>from prefect_dask import DaskTaskRunner<br><br>@task<br>def process_data(data):<br>    return [x**2 for x in data]<br><br>@flow(task_runner=DaskTaskRunner())<br>def distributed_flow():<br>    data = range(1000)<br>    processed = process_data.map(data)<br>    print(processed)<br><br>distributed_flow()</pre><p>This code runs 1,000 tasks in parallel using Dask, showcasing Prefect’s ability to handle distributed workflows efficiently.</p><h4><strong>5. Community and Support</strong></h4><p><strong>Apache Airflow:</strong><br>Airflow has a large and mature user base, with thousands of resources available on platforms like Stack Overflow and GitHub. Its long-standing presence ensures extensive community support for troubleshooting and learning.</p><p><strong>Prefect:</strong><br>Despite being a newer framework, Prefect has a rapidly growing community. Its modern architecture attracts users looking for innovative solutions. Additionally, Prefect offers direct support through its official Slack channel, allowing users to engage with the community and developers.</p><h4><strong>6. Cloud Integration</strong></h4><p><strong>Apache Airflow:</strong><br>Airflow offers cloud integration through services like AWS MWAA (Managed Workflows for Apache Airflow) or Google Cloud Composer. However, these integrations often involve complex configurations and are harder to set up.</p><p><strong>Prefect:</strong><br>Prefect provides seamless integration with Prefect Cloud, a SaaS solution for real-time workflow monitoring. Prefect Cloud requires minimal setup and offers Private Cloud options for organizations that prefer to manage infrastructure themselves.</p><h3>Use Cases</h3><h4><strong>When Prefect Excels</strong></h4><p><strong>1.Small and Medium-Sized Projects:</strong><br>Prefect is ideal for less complex data pipelines. For example, a data scientist who wants to automate the training process for a machine learning model can easily use Prefect.<br>Example:<br>Processing e-commerce sales data for predictive analysis:</p><pre>   from prefect import task, flow<br><br>   @task<br>   def fetch_data():<br>       return {&quot;sales&quot;: [100, 200, 300]}<br><br>   @task<br>   def clean_data(data):<br>       return [x for x in data[&quot;sales&quot;] if x &gt; 0]<br><br>   @task<br>   def analyze_data(cleaned_data):<br>       return sum(cleaned_data) / len(cleaned_data)<br><br>   @flow<br>   def sales_pipeline():<br>       raw_data = fetch_data()<br>       cleaned_data = clean_data(raw_data)<br>       result = analyze_data(cleaned_data)<br>       print(f&quot;Average sales: {result}&quot;)<br><br>   sales_pipeline()</pre><p><strong>2.Quick Debugging and Monitoring:</strong><br>Prefect simplifies error management and monitoring. Its task retry mechanisms and Prefect UI are perfect for projects that require rapid issue resolution.</p><p><strong>3.Distributed Processing Scenarios:</strong><br>Prefect integrates smoothly with distributed processing frameworks like Dask, making it a strong choice for large-scale data projects. For instance, engineering teams processing massive datasets in parallel will benefit greatly from Prefect.</p><h4>When Apache Airflow Excels</h4><p><strong>1.Large and Complex Data Pipelines:</strong><br>Airflow is built for managing complex task dependencies. For example, a media company aggregating daily content reports from multiple data sources can utilize Airflow’s DAG structures.</p><p><strong>Example:</strong><br>Defining task dependencies in a DAG:</p><pre>   from airflow import DAG<br>   from airflow.operators.python_operator import PythonOperator<br>   from datetime import datetime<br><br>   def fetch_data():<br>       print(&quot;Fetching data...&quot;)<br><br>   def process_data():<br>       print(&quot;Processing data...&quot;)<br><br>   def save_results():<br>       print(&quot;Saving results...&quot;)<br><br>   with DAG(<br>       dag_id=&quot;etl_pipeline&quot;,<br>       start_date=datetime(2023, 1, 1),<br>       schedule_interval=&quot;@daily&quot;,<br>   ) as dag:<br>       task1 = PythonOperator(task_id=&quot;fetch_data&quot;, python_callable=fetch_data)<br>       task2 = PythonOperator(task_id=&quot;process_data&quot;, python_callable=process_data)<br>       task3 = PythonOperator(task_id=&quot;save_results&quot;, python_callable=save_results)<br><br>       task1 &gt;&gt; task2 &gt;&gt; task3</pre><p><strong>2.Broad Community and Resource Needs:</strong><br>Airflow has been around longer, so it has a larger community. This provides extensive learning resources and examples for users.</p><p><strong>3.Companies with Existing Airflow Infrastructure:</strong><br>If your organization already uses Airflow and has built extensive DAG-based workflows, optimizing the current setup might be a better option than switching to Prefect.</p><h3>Conclusion and Recommendations</h3><p>Prefect and Apache Airflow are both powerful tools for managing data pipelines. Each framework shines in its own domain. Choosing the right tool depends on your project requirements and your team’s technical expertise.</p><h4><strong>When Should You Choose Prefect?</strong></h4><ul><li>If you want a quicker start, Prefect’s Python-native architecture and user-friendly features are ideal.</li><li>For small or medium-sized projects, Prefect allows you to quickly build and manage workflows.</li><li>Prefect is a strong choice for large-scale data projects requiring distributed processing, thanks to its seamless integration with Dask.</li><li>If you prefer fast and easy debugging and monitoring, Prefect UI will simplify your workflow management.</li></ul><h4><strong>When Should You Choose Apache Airflow?</strong></h4><ul><li>For managing large and complex data pipelines, Airflow’s DAG structures effectively handle intricate task dependencies.</li><li>If you are looking for broader community support and learning resources, Airflow’s long-standing presence in the industry is a significant advantage.</li><li>If your organization already uses Airflow and has an established infrastructure, optimizing the current system is a more practical choice than switching to another framework.</li></ul><h4><strong>Final Recommendation:</strong></h4><p>Prefect offers a modern, innovative solution with a fast learning curve, making it a great choice for data scientists. On the other hand, Airflow remains a robust tool for managing complex processes at an enterprise scale. By evaluating your project’s scale and requirements, you can determine which framework is the best fit for your needs.</p><p>So, Prefect or Apache Airflow? I hope this post has helped you better understand which framework might be the right fit for your needs. If you’re still undecided, no worries — choosing the right technology often involves a bit of trial and error. Learning the differences between Prefect and Airflow is a crucial first step to narrowing down your decision.</p><p>So, what’s next? Let’s say you’re leaning toward Prefect because of its modern architecture and user-friendly features. Great! Then you’re ready for the next step: learning how to actually use Prefect. In the next post of this series, I’ll walk you through <strong>how to build your first workflow with Prefect</strong>. I’ll show you how easy it is to define “Flows” and “Tasks” and provide a hands-on guide to set up a simple data pipeline.</p><p>Before you leave, don’t forget to share your thoughts and feedback. Which framework are you choosing? Why? I’d love to hear your decision and experiences!</p><p>Make sure to follow me, and I’ll see you in the next post! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c1d837a2117" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threads in Python: Efficient Multithreading Programming]]></title>
            <link>https://medium.com/@muratglyr33/threads-in-python-efficient-multithreading-programming-cc7c64aa4048?source=rss-5696de7bf0b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7c64aa4048</guid>
            <dc:creator><![CDATA[Murat Gölyeri]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 09:42:19 GMT</pubDate>
            <atom:updated>2025-03-04T09:42:19.311Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Are Threads and How Do They Work?</h3><p>In Python, the concept of <strong>threads</strong> refers to multithreading, a mechanism that allows multiple tasks to run concurrently. The threading module enables running a specific process in an independent thread, making programs more efficient.</p><p>Using multiple threads is particularly beneficial in I/O-intensive tasks. For instance, operations such as reading/writing files, making API requests, or retrieving data from message queues like Kafka can be performed independently of the main program flow.</p><h3>Why Use Threads?</h3><p>The primary reasons for using multiple threads include:</p><ol><li><strong>Preventing the main program from freezing</strong>: When working with large datasets or retrieving data from external services, threading prevents the main execution flow from becoming blocked.</li><li><strong>Faster data processing</strong>: Parallel execution of different tasks speeds up large-scale data analysis.</li><li><strong>Enhancing user experience</strong>: In graphical user interfaces (GUIs), threading ensures the interface remains responsive.</li><li><strong>Real-time data streaming</strong>: It allows processing real-time data from sources like sensors, financial markets, or Kafka.</li></ol><h3>Advantages of Using Threads</h3><ul><li><strong>Independent execution</strong>: Specific tasks can run without blocking others.</li><li><strong>Asynchronous processing</strong>: Fetching and processing data becomes more efficient.</li><li><strong>Ideal for I/O-intensive tasks</strong>, such as database queries, API calls, and file operations.</li></ul><h3>Disadvantages of Using Threads</h3><ul><li><strong>Global Interpreter Lock (GIL) limitation</strong>: Due to Python’s GIL, multithreading does not always improve CPU-intensive task performance.</li><li><strong>Synchronization challenges</strong>: Shared resource synchronization can be complex and may lead to data inconsistencies.</li><li><strong>Debugging difficulties</strong>: Tracking the execution of multiple threads can be challenging, making debugging more complex.</li></ul><h3>Use Case: Real-Time Data Processing from Kafka Using Threads</h3><p>One of the best use cases for <strong>threads</strong> is retrieving data from a Kafka queue. In this scenario, a thread is used to continuously fetch data from Kafka while allowing other tasks to run simultaneously.</p><h3>Code Explanation:</h3><ul><li>The KafkaConsumerThread class extends threading.Thread, making it runnable as a separate thread.</li><li>The __init__ method sets up Kafka connection parameters and subscribes to the specified topic.</li><li>The run method fetches messages from Kafka continuously.</li><li>The thread is started with consumer_thread.start().</li></ul><pre>import threading<br>from confluent_kafka import Consumer<br><br>class KafkaConsumerThread(threading.Thread):<br>    def __init__(self, topic):<br>        &quot;&quot;&quot;Extending the Thread class to fetch data from Kafka.&quot;&quot;&quot;<br>        super().__init__()<br>        self.topic = topic<br>        self.consumer = Consumer({<br>            &quot;bootstrap.servers&quot;: &quot;localhost:9092&quot;,  # Kafka server address<br>            &quot;group.id&quot;: &quot;my_consumer_group&quot;,  # Consumer group ID<br>            &quot;auto.offset.reset&quot;: &quot;latest&quot;  # Start consuming from the latest message<br>        })<br>        self.consumer.subscribe([self.topic])  # Subscribe to the specified topic<br><br>    def run(self):<br>        &quot;&quot;&quot;Fetches messages from Kafka when the thread starts.&quot;&quot;&quot;<br>        while True:<br>            msg = self.consumer.poll(1.0)  # Poll Kafka messages every 1 second<br>            if msg:<br>                print(f&quot;Kafka Message: {msg.value().decode(&#39;utf-8&#39;)}&quot;)  # Print the received message<br><br># Start the thread<br>consumer_thread = KafkaConsumerThread(&quot;my_topic&quot;)<br>consumer_thread.start()</pre><p><strong>Why Use Threads in This Scenario?</strong></p><ul><li>If Kafka data retrieval were executed in the main thread, all other tasks would be blocked.</li><li>By using threading.Thread, data can be fetched from Kafka while performing other operations.</li><li>In real-time data processing systems, threads are crucial for maintaining continuous data flow.</li></ul><p><strong>What Happens Without Threads?</strong> If threading is not used, the following code must be executed:</p><pre>from confluent_kafka import Consumer<br><br>consumer = Consumer({<br>    &quot;bootstrap.servers&quot;: &quot;localhost:9092&quot;,<br>    &quot;group.id&quot;: &quot;my_consumer_group&quot;,<br>    &quot;auto.offset.reset&quot;: &quot;earliest&quot;<br>})<br>consumer.subscribe([&quot;my_topic&quot;])<br><br>while True:<br>    msg = consumer.poll(1.0)<br>    if msg:<br>        print(f&quot;Kafka Message: {msg.value().decode(&#39;utf-8&#39;)}&quot;)</pre><p>In this case, no other tasks can be performed while fetching data from Kafka. For example, in a data science pipeline, if the retrieved data needs to be analyzed, stored, or used for machine learning predictions, all these operations would be delayed until the Kafka message is received.</p><h3>Why Are Threads Important for Data Science?</h3><p>In data science, <strong>threads</strong> play a crucial role, especially in big data and real-time data processing scenarios. Key applications include:</p><ol><li><strong>Real-time data streaming</strong>: Processing data from sensors, financial markets, or social media in real-time.</li><li><strong>Data preprocessing and analysis</strong>: Splitting large datasets and processing them across multiple threads improves efficiency.</li><li><strong>Machine learning model predictions</strong>: Multithreading enables handling multiple user requests simultaneously in web-based ML applications.</li><li><strong>Database operations</strong>: Enhancing efficiency by asynchronously retrieving and storing data from multiple sources.</li></ol><h3>Conclusion</h3><p><strong>Threads</strong> are particularly beneficial for I/O-intensive tasks and are a fundamental aspect of multithreading programming in Python. In data science, they are crucial for managing large data streams, performing real-time analysis, and processing data concurrently. Depending on the use case, choosing between <strong>threads or multiprocessing</strong> should be carefully evaluated.</p><p>The use cases, objectives, and advantages of <strong>threading</strong> can be expanded even further. In this blog post, I have shared my personal experiences and insights based on past projects where I have used this approach.</p><p>If you found this article helpful and want to explore more about Python, threading, and data science, feel free to follow me for more insights and practical guides. Stay connected for more technical content! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7c64aa4048" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PREFECT — 1. What is Prefect and Why is it Important for Data Scientists?]]></title>
            <link>https://medium.com/@muratglyr33/prefect-1-what-is-prefect-and-why-is-it-important-for-data-scientists-5a5124a77e9f?source=rss-5696de7bf0b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a5124a77e9f</guid>
            <dc:creator><![CDATA[Murat Gölyeri]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 13:02:38 GMT</pubDate>
            <atom:updated>2025-02-12T13:02:38.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>PREFECT — 1. What is Prefect and Why is it Important for Data Scientists?</h3><h3>Introduction</h3><p>Nowadays, managing workflows and processes, automating them, and scaling them for analysis have become essential for many data scientists and engineers, including myself. Ensuring that all these processes run in an organized, reliable and sustainable manner plays a critical role in the success of projects. At this point, <strong>Prefect</strong> emerges as one of the modern workflow management solutions.</p><p>I have planned this article as the beginning of a series because Prefect includes many topics that need to be addressed. I intend to cover this subject across multiple articles. As the first part of the series, this article will explore <strong>what Prefect is, why it is important, and what advantages it offers for data scientists</strong> in detail. Let’s go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLErVsPYtJqGvUWIaYI3Yg.jpeg" /><figcaption>Logo of Prefect</figcaption></figure><h3>What is Prefect?</h3><p><strong>Prefect</strong> is a modern, flexible, and open-source <strong>workflow management tool</strong> designed to handle workflows and pipelines. Built on <strong>Python</strong>, Prefect stands out with its <strong>user-friendly APIs</strong> and <strong>dynamic workflow management capabilities</strong>.</p><p>The primary goal of Prefect is to allow workflows and data pipelines to be <strong>planned, executed, managed, and monitored in a more reliable and flexible way</strong>. With Prefect, it becomes possible to <strong>define complex workflows, manage dependencies, and handle potential errors seamlessly</strong>.</p><h3>Key Features of Prefect:</h3><ul><li><strong>Easy Python Integration:</strong> Being fully Python-based, it integrates seamlessly with existing codebases.</li><li><strong>Dynamic Workflow Management:</strong> Prefect allows workflow changes at runtime.</li><li><strong>Simple Installation and Configuration:</strong> Setting up and configuring Prefect is straightforward.</li><li><strong>Fault Tolerance and Error Handling:</strong> Built-in error handling mechanisms enhance workflow robustness.</li><li><strong>Cloud and Local Server Options:</strong> Prefect offers both cloud-based and on-premise deployment choices.</li><li><strong>Rich Visualization Tools:</strong> The Prefect UI makes workflow monitoring and management intuitive.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tflIz1IIZ9rszC24gw5fNA.png" /><figcaption>Sample image from Prefect</figcaption></figure><h3>Why is Prefect Important for Data Scientists?</h3><p>The importance or advantages of Prefect will increase much more depending on the purpose of use. However, based on my personal experience, I would like to share with you the points that I find much more important from my point of view. Of course, more advantages can be mentioned in addition to the ones I have mentioned. This is also mentioned in different sources, but my aim is to reinforce the narrative with personal experience. For this reason, I would like to examine the subject from my own point of view.</p><h3>1. Automation for Data Processing and Model Training</h3><p>In data science projects, processes such as <strong>data collection, preprocessing, model training, and evaluation</strong> are repetitive tasks. Sometimes, due to various reasons, we need to revisit earlier steps in a project. This is where Prefect helps by automating these processes and making them structured.</p><p>For example:</p><ul><li>You can create a pipeline that collects data daily.</li><li>You can automate the triggering of model training processes.</li><li>You can monitor and report model performance at regular intervals.</li></ul><h3>2. Error Management and Robustness</h3><p>One of the biggest challenges for data scientists is handling errors that arise at different points in large data workflows. These errors can significantly disrupt ongoing processes. Thanks to Prefect’s <strong>“fail-safe” mechanism</strong>, failed tasks can be <strong>re-executed automatically</strong>, and error management strategies can be applied to minimize disruptions.</p><h3>3. Flexible and Modular Workflow Management</h3><p>Compared to traditional workflow management tools, <strong>Prefect offers a more flexible and modular structure</strong>. Its <strong>dynamic workflow management</strong> allows processes to be <strong>adapted based on conditions</strong>.</p><p>For example:</p><ul><li>If a dataset falls below a certain threshold, the workflow can be halted.</li><li>If a model’s performance drops below a defined level, a new training process can be automatically initiated.</li></ul><h3>4. Cloud and Local Deployment Options</h3><p>Prefect can run <strong>both locally and in the cloud</strong>. In some cases, local execution is preferable for <strong>quick iterations and debugging</strong>, while cloud environments are better suited for <strong>large-scale data processing operations</strong>.</p><p>With its flexible deployment options, Prefect allows data scientists to take advantage of distributed computing regardless of the environment.</p><h3>Conclusion</h3><p>Prefect is a <strong>powerful tool for modern workflow management</strong> and offers <strong>significant advantages for data scientists</strong>. With its <strong>Python-friendly architecture, dynamic workflow management, and error tolerance features</strong>, it is an ideal solution for building reliable data pipelines.</p><p>In this article, I aimed to explain <strong>what Prefect is and why it is beneficial for data scientists</strong>. I hope my combination of <strong>personal experience and research</strong> makes this content valuable for you.</p><p>📌 <strong>In my next article, I will discuss ‘Prefect vs Apache Airflow — Which One Should You Choose?’ based on my own experience.</strong> 📌 <strong>Follow me on Medium to stay updated with the series!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a5124a77e9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>