<?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 Shubham Pandey on Medium]]></title>
        <description><![CDATA[Stories by Shubham Pandey on Medium]]></description>
        <link>https://medium.com/@the-shubham-pandey?source=rss-839cba4253a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-8rQGzo5KmOjY_5hGc8ubw.jpeg</url>
            <title>Stories by Shubham Pandey on Medium</title>
            <link>https://medium.com/@the-shubham-pandey?source=rss-839cba4253a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:59:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@the-shubham-pandey/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[I Built pipsentinel Because “pip install” Shouldn’t Be a Security Gamble]]></title>
            <link>https://the-shubham-pandey.medium.com/i-built-pipsentinel-because-pip-install-shouldnt-be-a-security-gamble-09c766feacb0?source=rss-839cba4253a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/09c766feacb0</guid>
            <category><![CDATA[litellm]]></category>
            <category><![CDATA[venaai]]></category>
            <category><![CDATA[python-package-management]]></category>
            <category><![CDATA[open-source-security]]></category>
            <dc:creator><![CDATA[Shubham Pandey]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 06:05:30 GMT</pubDate>
            <atom:updated>2026-03-28T06:05:30.914Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>How a single malicious PyPI upload made me rethink everything about Python package installation and what I built to fix it.</em></strong></p><h3><strong>The Day “pip install litellm” Became a Credential Stealer</strong></h3><p>The payload harvested everything: AWS credentials, SSH private keys, GCP tokens, Kubernetes configs, database passwords, environment variables and exfiltrated them to models.litellm.cloud, a domain that looked close enough to the real thing that nobody blinked.</p><p>The window was approximately three to five hours. In that time, every developer, CI runner, and production server that ran pip install litellm or pip install --upgrade litellm was compromised. The recommended response? <strong>Rotate every secret on every affected machine. Rebuild from scratch.</strong></p><p>This wasn’t a typosquatting attack on some obscure package. This was a hijack of a legitimate, trusted library with 20M+ downloads executed by compromising a GitHub Actions workflow via a Trivy security scanner vulnerability in the project’s own CI/CD pipeline.</p><p>I watched it unfold in real time. And I thought: <em>why does </em><em>pip still just... trust everything?</em></p><h3>The Problem Is Bigger Than One Package</h3><p>LiteLLM wasn’t an anomaly. It was part of a pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yBbKsqlkAuJmQuyM-_UBg.png" /></figure><p>And behind the headlines, the numbers paint a grim picture:</p><ul><li><strong>PyPI published 3.9 million new files</strong> and hosted <strong>130,000+ new projects</strong> in 2025 alone</li><li>While crude typosquatting dropped ~85% in 2024 (thanks to PyPI’s 2FA mandate), <strong>sophisticated, targeted attacks surged</strong></li><li>Attackers shifted from mass-uploading fake packages to <strong>hijacking legitimate ones</strong> via compromised maintainer accounts and CI/CD pipelines</li><li>The new playbook: steal a credential, push one poisoned version, wait a few hours, delete it and let the damage propagate through lockfiles and CI caches</li></ul><p>The common thread? <strong>Zero pre-install verification.</strong> pip install trusts the registry. It doesn&#39;t check whether the version has a corresponding git tag. It doesn&#39;t scan the wheel for .pth files with import statements. It doesn&#39;t verify that the hash from PyPI&#39;s JSON API matches the Simple API. It just downloads, extracts, and runs.</p><h3>What pipsentinel Does</h3><p><a href="https://pypi.org/project/pipsentinel/"><strong>pipsentinel</strong></a> intercepts the install flow and runs a full security suite <em>before</em> anything touches disk. It’s a drop-in replacement for pip install that adds <strong>~487ms of checking per package</strong> on average (metadata ~140ms, wheel download ~50ms, static checks ~130ms, sandbox ~160ms) and blocks anything suspicious.</p><pre># Instead of: pip install requests<br>pipsentinel install requests<br><br># Scan all packages in a requirements file<br>pipsentinel install -r requirements.txt<br><br># Audit a uv.lock before running uv sync<br>pipsentinel sync --lockfile uv.lock<br><br># Check without installing<br>pipsentinel check somepackage==1.0.0 --json</pre><h3>The Check Suite</h3><p>Every package goes through <strong>10 independent security checks</strong> before installation is allowed:</p><h4>1. Multi-Source Hash Consensus</h4><p>Fetches the wheel’s SHA-256 from PyPI’s JSON API <em>and</em> the Simple API (PEP 503) independently. Both must agree. A compromised CDN or MITM attack would serve different hashes through different paths this catches that.</p><h4>2. RECORD Manifest Integrity</h4><p>Wheels are zip files with a RECORD file listing every contained file and its SHA-256. pipsentinel verifies every entry. A tampered wheel where someone swapped a .py file but forgot to update RECORD gets caught here.</p><h4>3. .pth File Scan</h4><p>This is the check that would have caught LiteLLM. Python’s site module executes any line starting with import in .pth files on every interpreter startup, not just when you import the package. pipsentinel scans every .pth file in the wheel for import statements and flags them as <strong>critical</strong>.</p><p>A small allowlist (like distutils-precedence.pth from setuptools) prevents false positives on known-safe patterns.</p><h4>4. Obfuscated Code Detection</h4><p>Scans every .py and .pth file using both regex and Python&#39;s ast module:</p><ul><li>exec(base64.b64decode(...)) the classic payload dropper</li><li>Double-encoded base64 blobs</li><li>Large embedded base64 strings (&gt;256 chars)</li><li>subprocess calls inside .pth files</li><li>exec() with computed (non-literal) arguments</li></ul><p>Intentionally does <em>not</em> flag eval() (too common in template engines) or exec(compile(...)) (used by Flask/Werkzeug for config loading).</p><h4>5. Git Tag Divergence</h4><p>Queries the GitHub Tags API for the package’s source repository. A version published to PyPI without a corresponding git tag (1.2.3, v1.2.3, release-1.2.3) is a strong signal of a credential-stolen push no legitimate release process skips tagging.</p><h4>6. Release Timestamp Delta</h4><p>Compares the git tag creation time against the PyPI upload time. Upload <em>before</em> the tag? <strong>Critical.</strong> Upload within 1 minute of tagging? <strong>Warning -</strong>legitimate CI takes 2–5 minutes. This catches the scenario where an attacker pushes to PyPI before the maintainer even tags the release.</p><h4>7. Import Sandbox</h4><p>Runs import &lt;pkg&gt; in an isolated subprocess with:</p><ul><li>All credential environment variables stripped</li><li>A fake HOME directory (populated with honeypot bait)</li><li>sys.addaudithook monitoring all socket, subprocess, and file operations</li><li>Python started with -S (skip site initialization), then site.addpackage() called <em>after</em> the hook installs so .pth payloads fire inside the hook&#39;s scope</li><li>Hard-kill safety ceiling of 10s (typical clean imports complete in ~160ms)</li></ul><h4>8. Honeypot Credentials</h4><p>The sandbox’s fake HOME is seeded with realistic-looking credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-N5moId6NoXm9lR4jcuMA.png" /></figure><p>All cryptographically useless. If the package reads one of these files <em>and then</em> makes a network call within 5 seconds, pipsentinel flags the read-then-exfiltrate sequence. This catches the exact attack pattern that LiteLLM used and defeats the class of malware that only activates when it detects real credentials in the environment.</p><h4>9. PyPI Provenance (OIDC Attestation)</h4><p>Checks whether the package was published via a reproducible, auditable GitHub Actions pipeline with OIDC attestation. Most packages lack this (it’s a newer feature), but its absence is a risk signal.</p><h4>10. Lockfile Verification</h4><p>First install stores the wheel’s SHA-256 and per-file RECORD in ~/.pipsentinel/pipsentinel.lock. Repeat installs verify locally <strong>zero network calls for hash checks.</strong> If the wheel has changed since locking, installation is blocked.</p><h3>How It’s Built</h3><h3>Architecture</h3><pre>cli.py<br>                 (install/check/audit/sync)<br>                       │<br>                       ▼<br>                  installer.py<br>               (safe_install orchestrator)<br>                ┌──────┼──────────┐<br>                │      │          │<br>                ▼      ▼          ▼<br>           checks.py  lockfile.py  sandbox.py<br>           (all checks) (lock I/O) (subprocess)<br>                │                    │<br>          ┌─────┴─────┐             ▼<br>          ▼           ▼         honeypot.py<br>        PyPI       GitHub      (fake creds)<br>      (JSON API,  (Tags API,<br>    Simple API,  timestamps)<br>    wheel DL)<br>                │<br>                ▼<br>             report.py<br>          (SecurityReport,<br>          human + JSON output)</pre><h3>Design Decisions</h3><p><strong>Zero dependencies.</strong> pipsentinel uses only the Python standard library urllib.request, hashlib, zipfile, subprocess, ast, site, json, re, tempfile, pathlib. This isn&#39;t a compromise; it&#39;s a feature. A security tool with dependencies has a supply chain of its own to attack. pipsentinel has none. The entire codebase is ~2,600 lines auditable in an afternoon.</p><p><strong>Pure functions.</strong> Every check is a standalone function returning CheckResult(name, passed, severity, message, detail). No global state, no side effects. You can import and call any check independently from the Python API:</p><pre>from pipsentinel import (<br>    fetch_package_metadata,<br>    check_git_tag_divergence,<br>    check_pth_files_in_wheel,<br>    check_obfuscated_code,<br>    check_sandbox_import,<br>    SecurityReport,<br>)<br><br>meta = fetch_package_metadata(&quot;requests&quot;, &quot;2.31.0&quot;)<br>report = SecurityReport(meta.name, meta.version)<br>report.results = [<br>    check_git_tag_divergence(meta),<br>    check_pth_files_in_wheel(meta),<br>]<br>print(report.to_json())  # machine-readable for CI</pre><p><strong>Process-level isolation.</strong> The sandbox doesn’t run in-process. It spawns a fresh Python subprocess with a sanitized environment. This means a package that tries to manipulate sys.modules, monkey-patch the audit hook, or corrupt memory can&#39;t escape the sandbox boundary.</p><h3>Real-World Use Cases</h3><h3>Drop-in replacement for pip install</h3><pre># Before<br>pip install -r requirements.txt</pre><pre># After<br>pipsentinel install -r requirements.txt</pre><p>Every package in the requirements file is scanned, reported, and only installed if it passes. A critical failure on any package blocks the entire batch.</p><h3>Pre-sync auditing for uv workspaces</h3><pre># Audit all packages in uv.lock before running uv sync<br>pipsentinel sync<br>pipsentinel sync --lockfile path/to/uv.lock<br>pipsentinel sync --force  # run uv sync even if checks fail</pre><p>pipsentinel parses the uv.lock TOML format, extracts all packages with a PyPI registry source, runs the metadata-level checks (hash consensus, git tag, provenance, .pth scan), and only proceeds to uv sync if everything passes.</p><h3>CI/CD gate</h3><pre># .github/workflows/deps.yml<br>- name: Secure install<br>  run: |<br>    pip install pipsentinel<br>    pipsentinel install -r requirements.txt<br>    pipsentinel audit  # exits 1 on critical failure</pre><p>The --json flag produces machine-readable output for pipeline integration. The audit command scans every installed .pth and .py file for post-install compromise signals.</p><h3>Security audit of existing environments</h3><pre># Scan all installed packages for suspicious .pth files and obfuscated code<br>pipsentinel audit</pre><p>This runs a full post-install audit: scans every .pth file in site-packages for import statements, and every .py file for obfuscation patterns. In my testing, it scanned 3,315 .py files in under a second.</p><h3>What It Doesn’t Catch (Honest Limitations)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoJTBEK7q7e7Kk2E-qzhVg.png" /></figure><h3>What’s Next</h3><p>The #1 priority is <strong>transitive dependency scanning</strong>. Today, if you run pipsentinel install requests, it checks requests but not certifi, urllib3, idna, or charset-normalizer. If any of those transitive deps are compromised, the attack lands unchecked.</p><p>The fix: run pip install --dry-run &lt;package&gt; to enumerate the full dependency closure, then run the check suite on every package in the graph before installing anything. This closes the attack class where a clean top-level package silently pulls in a backdoored transitive dependency.</p><p>Beyond that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GOy1mcxkOb1aFDCPBnw4nA.png" /></figure><h3>The Bigger Picture</h3><p>The Python ecosystem publishes <strong>3.9 million new files</strong> and <strong>130,000+ new projects</strong> per year. PyPI’s 2FA mandate cut crude typosquatting by 85%, but the attacks didn’t stop they evolved. Attackers now target CI/CD pipelines, steal maintainer tokens, and push single poisoned versions of <em>trusted</em> packages for a few hours before anyone notices.</p><p>pip install was designed for a world where package registries were trustworthy by default. That world no longer exists. Every pip install is an implicit statement of trust in the maintainer, the build pipeline, the registry CDN, and every intermediate system between PyPI and your machine.</p><p>pipsentinel doesn’t eliminate that trust. It <em>verifies</em> it before anything touches your disk.</p><pre>pip install pipsentinel</pre><p><strong><em>pipsentinel is open-source under the MIT license. </em></strong><a href="https://github.com/Shubham-253/pipsentinel"><strong><em>GitHub →</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09c766feacb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Types: From Overflow to Overblown]]></title>
            <link>https://the-shubham-pandey.medium.com/data-types-from-overflow-to-overblown-2ea5f2e38ebc?source=rss-839cba4253a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea5f2e38ebc</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-type]]></category>
            <dc:creator><![CDATA[Shubham Pandey]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 17:09:26 GMT</pubDate>
            <atom:updated>2025-03-16T15:55:20.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*7vdI0EmDqF4AAn_bhA_LFA.jpeg" /></figure><p>In programming, data types are too often dismissed as mere technical details. Reflecting on my almost five-year journey as an ML engineer, I now see how negligent I was in truly understanding them — and it’s high time to remedy that oversight. Motivated after reading about a fascinating event that piqued my curiosity — The Ariane 5, I set out to explore the true nature of these minions of the programming world.</p><p>In this article, we’ll cut through the fluff and dive into the essence of data types — focusing on the commonly used numerical ones. We’ll explore why they matter, unpack some infamous failures caused by overlooking them, and zoom into their growing relevance in my world of AI/ML. Let’s get started.</p><h3><strong>The Basics: A Quick Refresher</strong></h3><p>We all know the drill — data types define what kind of values a variable can hold, how much memory it takes, and what operations it can handle. For simplicity, we’ll stick to numerical data types here, as they’re the stars of many a programming horror story. Here’s a quick reference table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2pkJwYvl1jTnh9SbWR_EQ.png" /></figure><p>These ranges dictate what a variable can store. Exceed them, and you’re flirting with disaster like overflows, underflows, or precision loss. It’s simple on paper, but <em>when the stakes are high, “close enough” doesn’t cut it</em>.</p><h3><strong>The Tale of Ariane 5 (1996): A $500 Million Lesson</strong></h3><p>Let’s start with the Ariane 5 rocket , a European Space Agency marvel that launched on June 4, 1996, only to self-destruct 37 seconds later. The culprit? A data type conversion gone wrong. Engineers had repurposed code from the Ariane 4, assuming it’d work fine for the beefier, faster Ariane 5. They were wrong.</p><p>The issue boiled down to a 64-bit floating-point number (representing horizontal velocity) being converted into a 16-bit signed integer (int16). On Ariane 4, the velocity values stayed within int16 range (-32,768 to 32,767). But Ariane 5’s new flight path meant higher speeds — and a value that exceeded 32,767. This triggered an <strong>overflow</strong>. In the Ada programming language used for the rocket, an unhandled overflow doesn’t quietly outputs a garbage value instead it throws an <strong>exception</strong>. That exception crashed the guidance system, which interpreted the error as a signal that the rocket was moving off course. The system fired corrective boosters, overcorrected, and tore the rocket apart, triggering its self-destruct sequence due to system failure.</p><h3><strong>Key Terms:</strong></h3><p><strong>Overflow:</strong> When a value exceeds a data type’s maximum, either wrapping around (e.g., 65,536 becomes 0 in uint16) or crashing (as in Ada). <br><strong>Underflow:</strong> When a value dips below the minimum, often resetting to the max (integers) or losing precision (floating-point).</p><p>The fix? A proper range check or a larger data type. The cost of skipping that? Half a billion dollars and a stark reminder: <strong>data types aren’t optional</strong>.</p><h3><strong>The Patriot Missile Failure (1991): Precision Matters</strong></h3><p>February 25, 1991, during the Gulf War. A Patriot missile system failed to intercept an Iraqi Scud missile, allowing it to strike a U.S. Army barracks and kill 28 soldiers. The root cause? A floating-point rounding error.</p><p>The Patriot tracked time in tenths of a second using a 24-bit fixed-point register. Over time, small rounding errors accumulated. After 100 hours of operation, the system’s internal clock had drifted by 0.34 seconds — enough to miscalculate the Scud’s position. The missile was just outside the Patriot’s intercept range, and the system didn’t fire.</p><p>This wasn’t an overflow but a <strong>precision issue</strong>— a subtle data type flaw magnified by continuous operation. A software patch existed but hadn’t been deployed in time. Lesson learned: even tiny discrepancies in data types can turn deadly.</p><h3><strong>More Infamous Mishaps</strong></h3><p>The Y2K Bug (1999–2000): Two-digit year storage (e.g., “99” for 1999) risked rolling over to “00” in 2000, potentially breaking systems. Billions were spent fixing this data type shortcut before it became a global catastrophe.</p><p>The Excel Gene Name Disaster (2016):** Excel auto-converted gene names like “SEPT2” into dates (e.g., September 2), corrupting genomic data in research papers. A data type mismatch turned science into chaos.</p><p>These stories hammer home a truth: neglecting data types doesn’t just break code — it breaks rockets, defences, and trust.</p><h3><strong>Data Types in AI/ML: Where Precision Meets Scale</strong></h3><p>As an AI/ML practitioner, I can’t ignore how data types shape my domain. From training neural networks to deploying LLMs, they always play important role for good reason. Let’s break it down.</p><h3><strong>Common Data Types in AI/ML</strong></h3><p><strong>Float32</strong>: The workhorse of deep learning. It balances precision and memory, making it ideal for training models like CNNs or transformers. <br><strong>Float16/Bfloat16</strong>: Half-precision types for faster computation and lower memory use, common in inference on GPUs/TPUs. Google’s Bfloat16 tweaks Float16 to retain more range, sacrificing some precision. <br><strong>Int8</strong>: Used in quantization — shrinking models for edge devices like phones. Less precision, but lightning-fast and tiny. <br><strong>Float64</strong>: Rare in ML due to its memory hogging, but handy for high-precision scientific computing.</p><p>more mentioned below -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bp2zCgwvqcAA59aMKHPcBQ.jpeg" /></figure><h3>Why Choosing the Right Data Type Matters</h3><h4>Understanding GPU Processing for Matrix Multiplication</h4><p>Broadly, a GPU has two main components:</p><ol><li><strong>VRAM (Video RAM)</strong> — Stores matrices and other data before computation.</li><li><strong>SRAM (On-Chip Memory)</strong> — A high-speed cache near the compute cores that temporarily holds data for active processing.</li></ol><p>The key factor that makes GPUs fast is <strong>memory bandwidth</strong> — how efficiently data moves between VRAM and SRAM. This bandwidth bottleneck plays a critical role in performance, as even the most powerful compute cores can be stalled if data isn’t transferred quickly enough.</p><p>Now, let’s consider performing matrix multiplication using different data types: <strong>FP32, FP16, and FP8</strong>. Intuitively, lower-bit data types should compute faster because they require less memory and can be processed in parallel more efficiently. <br>To evaluate we use three main factors:-</p><p><strong>Memory Usage: FP32 &gt; FP16 &gt; FP8</strong><br> Higher bit data types like FP32 consume more memory. This means fewer matrix elements can be stored, and more data must be transferred, slowing down computation.</p><p><strong>Transfer Speed: FP32 &lt; FP16 &lt; FP8</strong><br> With lower bit-widths, each data transfer moves more elements. Thus, FP8 allows for the fastest data movement, reducing the time spent shuttling data between VRAM and SRAM.</p><p><strong>Computational Throughput (TFLOPs): FP32 &lt; FP16 &lt; FP8</strong><br> GPUs can perform more operations per second when working with lower precision data, resulting in higher TFLOPs for FP8 compared to FP16 and FP32.</p><p>However, there’s a trade-off. While FP8 excels in speed and memory efficiency, it sacrifices precision. Additionally, older GPUs may lack native FP8 computation support, even if they can store FP8 data in memory.</p><p>To mitigate precision loss while leveraging the efficiency of FP8, a technique called <strong>“dequantization”</strong> can be used. This involves converting FP8 data into a higher precision format (e.g., FP16) when loading it into SRAM, performing computations at higher precision, and then converting it back to FP8 before storing results. This allows for a balance between speed, memory efficiency, and numerical stability — more on this later.</p><h3><strong>Impact in AI/ML</strong></h3><p><strong>1. Training:</strong> Neural networks uses billions of parameters. Using float32 keeps gradients precise enough to converge, but float16 can speed things up, sometimes at the cost of stability. Overflow or underflow in gradients? Your model’s is as good as dead. <br><strong>2. Inference:</strong> On resource-constrained devices, int8 quantization slashes latency and power use. But if you quantize too aggressively, accuracy tanks. <br><strong>3. LLMs:</strong> The rise of massive language models (think GPTs) has spotlighted mixed-precision training. Combining float16 and float32 optimizes speed and scale without sacrificing quality. <br><strong>4. Data Pre-processing:</strong> Feed a model misaligned types (e.g., int where float is expected), and you’ll get garbage outputs or failed model.</p><p>In ML, data type choices ripple through memory usage, speed, and accuracy. Get them wrong, and your model’s either a sluggish beast or a useless toy.</p><h3><strong>Wrapping Up: Respect the Minions</strong></h3><p>Data types might seem like the unsung grunts of programming, but they’re the guardrails keeping systems sane. The Ariane 5 explosion, the Patriot failure, and even Excel’s gene fiasco show what happens when we ignore them. In AI/ML, they’re the difference between a model that scales and one that flops.</p><p>So next time you declare a variable, pause. Ask: Does this type fit my range? My precision? My hardware? It’s not just code, it’s a decision with consequences. Let’s stop treating data types as an afterthought and start seeing them for what they are: the foundation of everything we build.</p><p>What’s your take? Ever had a data type mishap bite you in a project? Drop a comment — I’d love to hear your war stories. And if this resonated, share it with someone who might need a wake-up call about the minions of programming i.e. data types.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea5f2e38ebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI revolutionizing Air Travel: Lessons for Every Industry]]></title>
            <link>https://the-shubham-pandey.medium.com/ai-revolutionizing-air-travel-lessons-for-every-industry-795da4b682cb?source=rss-839cba4253a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/795da4b682cb</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[ai-ml-services]]></category>
            <category><![CDATA[airlines-reservations]]></category>
            <category><![CDATA[chatbots-for-business]]></category>
            <dc:creator><![CDATA[Shubham Pandey]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 20:48:26 GMT</pubDate>
            <atom:updated>2025-03-10T20:48:26.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfAWSgtWE-mzUZ5mfvuUbA.jpeg" /></figure><p>I was standing in an airport lounge last month when I overheard something fascinating. A traveller next to me was speaking to their phone: “I need a flight from Delhi to Singapore next Thursday, returning the following Tuesday. Business class if possible.” Seconds later, they were reviewing options, selecting seats, and completing their booking — all through a conversation with an AI assistant.</p><p>This moment crystallized what I’ve been seeing in my work implementing generative AI solutions: we’ve entered a new era of customer experience in travel. But the implications extend far beyond just airlines.</p><h3>The Quiet Revolution in Customer Experience</h3><p>Remember when booking a flight meant clicking through 6–8 screens, repeatedly entering the same information, and fighting with calendar widgets? That experience is rapidly becoming as outdated as removing your shoes at security.</p><p>Generative AI is completely transforming how we interact with airlines — and the change couldn’t come soon enough. In an industry with razor-thin margins and intense competition, creating frictionless customer experiences isn’t just good service; it’s survival.</p><p>The benefits from the implementations are staggering:</p><ul><li>Better user experience in conversational booking over traditional forms</li><li>Average booking completion times have dropped from 8+ minutes to under 3</li><li>Booking abandonment rates could plummet in AI-first channels</li><li>Increase in Customer satisfaction scores</li></ul><p>But the revolution runs deeper than convenience. What’s happening in air travel offers crucial lessons for every customer-facing industry.</p><h3>Beyond Chatbots: The Generative AI Difference</h3><p>Let me be clear: we’re not talking about the frustrating rule-based chatbots of yesterday. Traditional chatbots follow predefined conversation paths and break the moment a user deviates from the script. Generative AI systems fundamentally differ in three critical ways:</p><h3>1. They Think Like Humans, Not Computers</h3><p>When a customer says, “I need to fly to London next month for about a week, maybe around the 15th,” they’re expressing uncertainty and flexibility. Traditional systems would force them to provide exact dates.</p><p>Generative AI recognizes this human flexibility, offering responses like: “I can help with that. Looking at flights to London around June 15th with approximately one-week stays, I’m seeing some good options. Would you prefer to leave midweek or on a weekend?”</p><p>This ability to handle ambiguity creates conversations that feel natural rather than mechanical.</p><h3>2. They Extract Multi-Dimensional Intent</h3><p>In my work implementing these systems, one capability consistently amazes clients: the ability to extract multiple pieces of information from a single statement.</p><p>When a traveler says: “I’d like to change my January flight to Dubai to February instead, and upgrade to business class,” the AI simultaneously:</p><ul><li>Identifies this as a rebooking request</li><li>Captures the original destination (Dubai)</li><li>Recognizes the desired change (January → February)</li><li>Notes the class upgrade request (business class)</li></ul><p>This multi-dimensional understanding eliminates the tedious back-and-forth of traditional interfaces, reducing a 10-question process to a single conversation turn.</p><h3>3. They Remember Everything (But Forget When Asked)</h3><p>Modern generative AI systems maintain persistent memory throughout customer journeys. If you mentioned your seating preference two weeks ago, the system remembers.</p><p>When a frequent flyer says, “Book me the usual to San Francisco,” the system understands their typical preferences — window seat, early morning departure, vegetarian meal — without asking repetitive questions.</p><p>This contextual awareness represents a quantum leap beyond the stateless interactions of traditional interfaces.</p><h3>The Technology Driving the Transformation</h3><p>While the technical architecture can be complex, the core technologies enabling this revolution are worth understanding:</p><h3>Large Language Models: The Conversation Engine</h3><p>At the heart of these systems are large language models (LLMs) that power natural language understanding and generation. However, raw LLMs alone aren’t enough. The most successful implementations:</p><ul><li>Fine-tune models on domain-specific data (airline terminology, booking patterns)</li><li>Implement sophisticated prompt engineering techniques</li><li>Create guardrails to prevent hallucinations and ensure accuracy</li></ul><h3>Conversational Workflow Architecture</h3><p>The magic happens in the conversational workflow layer that:</p><ul><li>Maintains state across the entire customer journey</li><li>Adapts dynamically to user inputs</li><li>Handles exceptions gracefully</li><li>Integrates with backend systems</li></ul><p>In one implementation I worked on, we created a workflow engine capable of managing 15 + distinct conversation paths simultaneously, switching between them based on user needs without losing context.</p><h3>Integration Layer</h3><p>Perhaps the most challenging aspect is connecting these sophisticated conversational systems with decades-old airline reservation systems that were never designed for this type of interaction.</p><p>Modern implementations use a middle-tier orchestration layer that:</p><ul><li>Normalizes data formats</li><li>Manages API rate limiting</li><li>Handles caching for performance</li><li>Provides fallback mechanisms during outages</li></ul><h3>Real-World Impact: More Than Just Convenience</h3><p>A major international airline recently shared their results after implementing a generative AI booking assistant:</p><p>Metric Before After Change Booking completion rate 61% to 72%, average booking time 7.8 min to 2.9 min, call center volume 12,000/day to 4,800/day customer satisfaction 3.5/5 to 4.5/5, agent job satisfaction 68% to 85%.</p><p>That last metric might be surprising, but it highlights a crucial point: by automating routine transactions, human agents now focus on complex issues where they can truly add value. This doesn’t eliminate jobs — it transforms them into more rewarding roles.</p><h3>Lessons for Every Industry</h3><p>While air travel might be leading this transformation, the principles apply universally. Here’s what other industries should take away:</p><h3>1. Start With High-Value Conversations</h3><p>The most successful implementations begin by identifying high-volume, high-value conversation types. For airlines, booking and rebooking were obvious targets. For retail, it might be product discovery and returns. For healthcare, appointment scheduling and prescription refills.</p><p><strong>Key question:</strong> What conversations represent 80% of your customer interactions?</p><h3>2. Design for Conversation, Not Completion</h3><p>Traditional digital experiences focus on “completion rates” — driving users through a predefined funnel. Conversational experiences require thinking in terms of dialogue flows, with branches, loops, and graceful interruptions.</p><p>In one airline implementation, we mapped 50 + potential dialogue branches for a “simple” booking flow — because that’s how human conversations naturally evolve.</p><p><strong>Key question:</strong> Are you designing for how people actually communicate, or forcing them into linear paths?</p><h3>3. Balance Automation With Human Oversight</h3><p>The most successful implementations maintain what I call “supervision asymmetry” — high human oversight initially, gradually reducing as the system proves reliability in specific conversation types.</p><p>For this airline, we started with 100% human review of AI-assisted bookings. Three months later, human review was needed for only 7% of transactions, focusing on edge cases that improved the system’s overall capabilities.</p><p><strong>Key question:</strong> How will you transition from high to low supervision as your system matures?</p><h3>4. Measure What Matters</h3><p>Forget vanity metrics like “containment rate” (keeping users in automated channels). Focus instead on:</p><ul><li>Conversation efficiency (turns to completion)</li><li>Resolution accuracy (getting it right the first time)</li><li>Customer effort score (perceived ease of interaction)</li><li>Escalation quality (when human handoff occurs, is the context preserved?)</li></ul><p><strong>Key question:</strong> Are your metrics encouraging the right behavior in your AI system?</p><h3>Beyond Booking: The Next Frontier</h3><p>The current generation of AI travel assistants excel at structured transactions like bookings, but the next horizon is even more exciting:</p><h3>Proactive Journey Management</h3><p>Imagine your travel assistant texting you: “Your flight to Chicago might be affected by tomorrow’s forecasted snowstorm. I’ve put hold reservations on three alternative flights. Would you like to review options now or wait until the airline makes an announcement?”</p><p>This proactive approach, combining real-time data with predictive analytics, represents the future of travel assistance.</p><h3>Cross-Service Integration</h3><p>The most sophisticated systems are beginning to bridge previously siloed travel services:</p><p>“I see your flight to Boston lands at 9pm. Would you like me to reserve a rideshare to meet you at baggage claim, or would you prefer to see hotel options with late check-in near your Thursday morning meeting location?”</p><h3>Emotion-Aware Responses</h3><p>Next-generation systems are developing the ability to detect customer frustration, anxiety, and other emotions, adjusting their tone and response strategies accordingly.</p><p>For a delayed traveler who types “This is ridiculous, I’m going to miss my connection!” the system might respond with empathy first, solution second — mirroring how skilled human agents handle emotional situations.</p><h3>The Journey Ahead</h3><p>As generative AI continues transforming customer experience in travel, other industries face a choice: lead or follow. Those who embrace these technologies early will define the new standard for customer interaction in their sectors.</p><p>The most surprising insight from my work in this space? Customers who use AI-powered conversational interfaces don’t just report higher satisfaction; they show significantly higher brand loyalty and spend more over time. It turns out that when you remove friction from the customer journey, people not only buy more — they come back more frequently.</p><p>For executives in any customer-facing industry, the writing is on the wall: The conversational AI revolution isn’t coming. It’s already here. The only question is whether you’re part of it.</p><p><em>What’s your experience with AI-powered booking bot? Have you seen similar technologies transforming other industries? Share your thoughts in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=795da4b682cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GANs: Demystifying Loss Function]]></title>
            <link>https://the-shubham-pandey.medium.com/gans-demystifying-loss-functions-318bf9ec1380?source=rss-839cba4253a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/318bf9ec1380</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Shubham Pandey]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 15:21:57 GMT</pubDate>
            <atom:updated>2024-01-18T16:18:55.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A city with Red ground and purple skies, the skies have dark purple clouds inside it, there is a big white shining Palace far in distance. The rest of the image seems like a hellish new york city. Victorian lampposts line the streets." src="https://cdn-images-1.medium.com/max/512/1*LIe74s1_cMNndN_QVeaQLA.png" /><figcaption><strong>Prompt</strong> : A city with Red ground and purple skies, the skies have dark purple clouds inside it, there is a big white shining Palace far in distance. The rest of the image seems like a hellish new york city. Victorian lampposts line the streets.</figcaption></figure><p>GANs, what a fresh topic, yup, may be not, and definitely not when Generative AI has taken the world by storm, Look at the above <a href="https://hotpot.ai/s/art-generator/8-z4RawXunLVuE14E?share=1&amp;title=A%20city%20with%20Red%20ground%20and%20purple%20skies%2C%20the%20skies%20have%20dark%20purple%20clouds%20inside%20it%2C%20there%20is%20a%20big%20white%20shining%20Palace%20far%20in%20distance.%20The%20rest%20of%20the%20image%20seems%20like%20a%20hellish%20new%20york%20city.%20Victorian%20lampposts%20line%20the%20streets."><em>example</em></a><em> </em>generated using a <strong>Diffusion Model</strong>.</p><p>Any pro-artist will take hours, if not days, to create such art, and AI does that in few seconds. The point is, Generative Models are hotcake, one must eat , especially if you are an AI engineer.</p><p>But before we move to Diffusion Models, we need to take some baby steps and understand GANs and how they work.</p><p>GANs stand for Generative Adversarial Network, that comprises of two neural networks that pitch against each other and gradually improve each other. First network is called Generative network and second is called Discriminator network. So hoping you are still with me, let’s dive deeper.</p><p><strong>Discriminator model</strong> — If you have worked with image classification model, it is exactly that, the network takes an image as input and outputs if its a ‘fake’ or ‘real’. And trust me that’s it, and nothing else.</p><p><strong>Generator model</strong> — This is the interesting part of the network, a generator model basically works by taking a noise vector as an input and tries to generate an image out of it, <strong>whaaat?</strong>, So consider this, you have a 2D Matrix(i.e. 2D image) and you have flattened it as a Dense Layer( we do that often when using fully connected layer). So if the Image was of size 32*32 so the flattened layer will be of length 1024, now suppose that image was nothing but a random noise of pixels, if we flatten it, we get a noise-vector of 1024 length. If that’s clear let’s move forward, now the Generator performs exactly what we just discussed, but in a reverse order, i.e. it receives a noise vector converts it into a 2D Matrix and then up-sample it, to the desired input size image that the Discriminator model is expecting(as it will accept the generated image and classify it, remember!!).</p><h3><strong>Understanding The Rivalry</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xWqbymPLh-zrn1SDVOTEw.gif" /><figcaption>The MinMax Game</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaZfVWrLV7LVL8mcIVFE8w.png" /></figure><p>Woah!! that’s a long expression … yeah it is, but its not as scary as it looks.<br>Let’s break it down theoretically, by understanding what is going on. The Discriminator being a classification model, is given real images i.e. x in the expression, from the original distribution, as well as the <strong>fakes </strong>i.e. G(z),<strong> </strong>generated by Generator where z is noise vector.</p><p>So now we can see that the expression is basically made up of two terms. In case of real images D(x) calculates the probability of confidence of Discriminator to identify <strong>real image as</strong> <strong>real</strong>, which the Discriminator would want to <strong>maximize</strong>( cause obviously it wants to be good at being right). And D(G(x)) calculates the probability of how much discriminator is confident at stating <strong>fake image as real</strong>. So Discriminator would want to <strong>minimize it</strong> cause it <em>wouldn’t want to be good at </em><strong><em>not classifying</em></strong><em> it correctly</em>😏.</p><p>But that puts the whole expression at tight spot, because putting both the terms together, first term is something Discriminator want to minimize while the second term is something it wants to maximize. Therefore <strong>we use (1- D(G(x))) </strong>instead of just <strong>D(G(x)), </strong>to convert it from something, <strong>to</strong> <strong>minimize -&gt; to maximize</strong>. The <strong>log</strong> around the terms is just to scale the values, simple fun mathematics.</p><p>Now looking at the value function again the whole expression becomes an optimization function, to find a D(Discriminator) that would Maximize the function and to find a G(Generator) that would want to Minimize it. Because Generator wants to fool Discriminator into thinking the fake image it generated is actually the real, not fake. This sets-up the adversarial behavior.</p><h3><strong>Finale: With Some Math&#39;s Theory</strong></h3><p>Now if you remember the old-mathematical-nemesis <strong><em>calculus</em></strong>, to find minima or maxima we differentiate the function wrt the variable we want to optimize it for, and equate it to 0. I will leave the calculations up to you(its not difficult), but the conclusion is very intuitive, That is, <strong>the minimum of cost function is achieved when probability distribution of G is equal to that of Real data</strong>, which is intuitive because, we want our Generator to be so good, that it can generate image just like the real ones.<br>And in that case the value(cost) function becomes a constant:</p><p><strong>V(D,G) = -log(4)</strong></p><p>So there goes the explanation of<strong> minmax game</strong>.</p><p>In next blog we will jump into, How GAN’s are trained. <strong>CIAO!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=318bf9ec1380" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Processing -Edge detection: Part 1]]></title>
            <link>https://the-shubham-pandey.medium.com/image-processing-edge-detection-part-1-d93b30f63a64?source=rss-839cba4253a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d93b30f63a64</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shubham Pandey]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 07:05:49 GMT</pubDate>
            <atom:updated>2022-06-13T07:05:49.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAiA0615F6cIxqLRRXMyDA.jpeg" /></figure><p>In an interview, I was being questioned about Image processing and there, I was asked questions on edges, at that time I was not much into the theoretical aspect of things but more of a ‘let’s implement and see’ kind of person. And needless to say, I failed terribly when they started going deep and deep into this simple concept itself. And after that failure, I realised, man! there is so much left before I can even consider myself a computer vision engineer. So if you hit an almost similar roadblock or got a guilty conscience that yeah I can use <strong><em>it</em></strong> but I don’t know what <strong><em>it</em></strong> is, join my journey.</p><p>So what is an edge? In our 3D world, Edges are the intersection of two (sur)faces or simply the lines that separate surfaces from one another. OKAY, but how can we identify them in a 2D image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGuyC2I8LvATQiR4d4jqZg.jpeg" /><figcaption>The blue line represents an edge</figcaption></figure><p>Here you can see 3 faces labelled as 1,2,3 and a blue line representing an edge. And if you have not guessed it, it’s an image of a 3D object <strong>:)</strong>. Now to the question, how do we identify an edge in an image? It is actually pretty simple. <em>The area where there is a sudden change in pixel intensity(see the area represented by little arrows on faces 2&amp;3 in the image)defines the edge and the group of pixels that provide you with that information makes up edges</em>, Wow!! that wasn’t so hard.</p><p>The bottom line is if we are out for edge-hunting we need to get pixels that separate two discontinuous regions represented in terms of pixel intensity.</p><p>And now that, we have fully established what an edge is, let’s go on to how to detect these edges.</p><p>But first, there is something you should know<strong><em>,</em></strong></p><blockquote><strong><em>Linear filtering </em></strong><em>is the filtering method in which the value of the output pixel is a linear combination of the neighbouring input pixels. it can be done with convolution. For example, mean/average filters or Gaussian filtering.</em></blockquote><blockquote><strong><em>Non-linear filtering</em></strong><em> cannot be done with convolution or Fourier multiplication. A sliding median filter is a simple example of a non-linear filter.</em></blockquote><h3>How does edge detection work? (A non-mathematical explanation)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Rtw71Vck__iJ3l6vs7oAg.jpeg" /></figure><p>Focus on two boxes the orange one and the black one, the black one is a little bit off from the edge whereas the orange one looks like it lies on the edge, now that’s a visual result but how does a computer identify an edge? It does that by using something called <strong>the kernel</strong>(or filter), which is a matrix when convolved with the image in a sliding window fashion gives <strong>a feature map. </strong>The values on the feature map will tell if a certain pixel is on an edge or not. For example, after applying the above filter shown in blue( a Prewitt filter — X direction), it provides us with the difference between right pixels(intensity) and left pixels(remember the definition?), so in the case where the difference is large the target pixel is said to lie on edge, like in our case we get 125(black) and 260(orange) clearly orange has a much higher value hence it lies on the edge.</p><h3>Methods of Edge Detection</h3><p>Here are some of the masks for edge detection that we will discuss in the upcoming tutorials. These are all linear filters(the ones that are used by convolving them with a given image, as explained in the quote section).</p><ul><li>Prewitt Operator</li><li>Sobel Operator</li><li>Farid Operator</li><li>Scharr Operator.</li></ul><p>Now to not make this blog too lengthy, we will start part 2 directly with the filters and explain them one by one, and possibly do some code too <strong>:)</strong></p><p>But before ending let&#39;s see the result Prewitt kernel returns on the example we used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*e1TuRHm9HlwImS-tOs83jA.png" /></figure><p>Thank you for reading, see you in <strong>Part 2.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d93b30f63a64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping using Python and Selenium(XPATH)]]></title>
            <link>https://medium.com/analytics-vidhya/web-scraping-using-python-and-selenium-xpath-f315f63ac229?source=rss-839cba4253a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f315f63ac229</guid>
            <category><![CDATA[ellen-degeneres]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Shubham Pandey]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 22:40:40 GMT</pubDate>
            <atom:updated>2021-07-12T06:25:25.656Z</atom:updated>
            <content:encoded><![CDATA[<p>The website used in this article is <a href="https://www.thetvdb.com/series/the-ellen-degeneres-show"><strong><em>Ellen_show</em></strong></a>, This article is for educational purposes and it is a project to learn web scraping using selenium. I chose the above-mentioned website because I love the <strong>Ellen DeGeneres show… so!! </strong>and the data extracted here belongs to the owners of the show. This article is a let’s do it, for theory please read <a href="https://www.javatpoint.com/selenium-tutorial"><strong>here</strong></a>.</p><p>Now let’s start, first <strong>install selenium</strong> using <strong>pip</strong> and import the following libraries in your notebook.</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>from</strong> <strong>selenium</strong> <strong>import</strong> webdriver<br><strong>from</strong> <strong>selenium.common.exceptions</strong> <strong>import</strong> NoSuchElementException<br><br><strong>from</strong> <strong>selenium.webdriver.support</strong> <strong>import</strong> expected_conditions <strong>as</strong> EC<br><strong>from</strong> <strong>selenium.webdriver.support.ui</strong> <strong>import</strong> WebDriverWait<br><strong>from</strong> <strong>selenium.webdriver.common.by</strong> <strong>import</strong> By<br><strong>from</strong> <strong>IPython.display</strong> <strong>import</strong> Image<br><strong>import</strong> <strong>datetime</strong></pre><p>Add Chrome Driver path but before that download, the latest version(or check the version of your chrome browser)of <strong>chrome driver</strong> from this <a href="https://sites.google.com/a/chromium.org/chromedriver/downloads"><strong>link</strong></a> and <strong>PATH</strong> is where the downloaded .exe file is located)</p><pre>PATH =&quot;C:\Program Files\chromedriver.exe&quot;</pre><p>Code below will open chrome browser</p><pre>driver = webdriver.Chrome(PATH)</pre><p>Adding Link of the website we want to scrape from</p><pre>driver.get(&#39;https://www.thetvdb.com/series/the-ellen-degeneres-show&#39;)</pre><p><strong>Note</strong>: if you are here just for the code, scroll down to the <strong>Final scrapper code </strong>or else follow with me<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRGUXJvdGhe3VT5eZVnbqA.png" /><figcaption>source: <a href="https://www.thetvdb.com/series/the-ellen-degeneres-show">https://www.thetvdb.com/series/the-ellen-degeneres-show</a></figcaption></figure><p>Scroll down on the website, and you will see this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwzROyS0uQ3QlbQdJrG-Lw.png" /><figcaption>source: <a href="https://www.thetvdb.com/series/the-ellen-degeneres-show">https://www.thetvdb.com/series/the-ellen-degeneres-show</a></figcaption></figure><p><strong>See the little arrow</strong> that is a link for season 1 data and then there is a list of 18 seasons in total.</p><blockquote>I want my scraper code to automatically go into each link of the season&#39;s list and then scrape data(all the episodes) for each season and append the data in one single table. So by this, we will have one dataset of all seasons with their episodes. Sounds fun right!!!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfveOgckhhhrAecFEekYUg.png" /></figure><p><strong>Right click -&gt; inspect -&gt; on RHS top bar click on arrow on right of Elements tab -&gt; then select season 1 -&gt; you will see a portion highlighted in blue -&gt; right click on it -&gt; COPY -&gt; copy XPATH -&gt; you will get below mentioned path, </strong>copy it in one cell and do not touch it for now.</p><p><strong>Season 1 XPATH</strong> : //*[@id=”page-series”]/div[3]/div[2]/div[2]/div[6]/div[1]/ul/li[3]/ h4/a</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xayZK4BNJcPjKjYOXqM7Gw.png" /></figure><p>Do exactly what we did before for <strong>season 18</strong> this time. You will get following</p><p><strong>Season 18 XPATH</strong> : //*[@id=”page-series”]/div[3]/div[2]/div[2]/div[6]/div[1]/ul/li[20]/h4/a</p><p>So we want to iterate from <strong>Season_1&#39;s XPATH</strong> to <strong>Season_18’s XPATH</strong></p><p><strong>Now, what is XPATH?</strong> : XPath is a query language for selecting nodes from an XML document. So Selenium uses this and many other ways to navigate through HTML or XML documents, XPATH is one of them. The other ways to select a node are using id, classes, etc. but I find XPATH <strong>headache-free</strong> if that’s a word.</p><p>Now let’s get back to the task, can you spot the difference between Season1_XPATH and Season18_XPATH?</p><p>if no, here’s the answer - in the XPATH, till <strong>ul/</strong>,<strong> </strong>everything is the same and then after li<strong>, h4/a</strong> is also common in both of them.</p><p>The main game here is in <strong>li[3]</strong> to <strong>li[20]</strong>, difference= 20–3+1 =18, which is equal to the total no. of seasons. So our loop will go from <strong>3 to 21</strong>(the end of the range is excluded in python) and we will get each season.</p><p>Okay, so we can access each of these seasons&#39; links great!!, but now what?</p><p>Now our code should be able to visit each season’s link and click on it to open the page containing all the data of that season</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qArOcPvwAC5ZepiLSNfG5g.png" /><figcaption>Code snippet to click on the web-page elements using its XPATH</figcaption></figure><p>The code above can click on elements of the webpage( and the path to those elements is given using the XPATH we saw before). So this can open each link one by one.</p><p><strong>Can it?</strong></p><p>No, it can’t, because after visiting a link, you should get back to the main page again only then it will be able to select the next link of the Season list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_raEaoRNiOUey4PgNz7zdA.png" /><figcaption>Code snippet for looping through seasons</figcaption></figure><h3>Do Something useful</h3><p>Now, just like before, click on the row of episode 1 and collect XPATH for <strong>S01E01, Name, First Aired</strong>, just like we did for Seasons and copy them in a separate cell for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1zS57ndzM1AdNZHk8rCJA.png" /></figure><p>episode 1:</p><ul><li><strong>Season index</strong> : //*[@id=”page-season”]/div[4]/div[2]/div[1]/table/tbody/tr[1]/td[1]</li><li><strong>Guests(Name)</strong>: //*[@id=”page-season”]/div[4]/div[2]/div[1]/table/tbody/tr[1]/td[2]/a</li><li><strong>Date(First aired)</strong>: //*[@id=”page-season”]/div[4]/div[2]/div[1]/table/tbody/tr[1]/td[3]/div</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrL4YG6dw3ddyPbybcrEog.png" /></figure><p>episode 166:</p><ul><li><strong>Season index</strong>: //*[@id=”page-season”]/div[4]/div[2]/div[1]/table/tbody/tr[166]/td[1]</li><li><strong>Guests(Name)</strong>: //*[@id=”page-season”]/div[4]/div[2]/div[1]/table/tbody/tr[166]/td[2]/a</li><li><strong>Date(First aired)</strong>: //*[@id=”page-season”]/div[4]/div[2]/div[1]/table/tbody/tr[166]/td[3]/div</li></ul><p>Now let’s spot the difference between the first episode’s and the last episode’s -(<strong>Season_index, Guests, Date</strong> XPATH)</p><ul><li>Season_index XPATH changes from tr[1] to tr[166] rest everything is the same</li><li>Guest(Name) XPATH changes from tr[1] to tr[166] rest everything is the same</li><li>Date(First aired) XPATH changes from tr[1] to tr[166] rest everything is same</li></ul><p>Not all seasons have 166 episodes, so we can take 1 to 200 to be on the safe side for each season. Now you might be thinking that code will give an error if we go beyond the limit of no. of episodes in any season. <strong>Yes!!, it will give </strong>NoSuchElementException<strong> but we will handle it using try-except,</strong> so if an exception occurs we <strong>continue(</strong>python keyword<strong>)</strong> from the next iteration of the same loop till it finishes all the iterations(without giving any error). You will understand more when you see the code.</p><p>Okay, so we can access each data column of each episode, now what’s next?</p><p>Now our code should be able to read the text associated with each XPATH so we can store them. Let’s work on that too</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbppERCEL7e4xKcSyti3WA.png" /><figcaption>code snippet to loop through all the episodes and read the associated text</figcaption></figure><h3>Final scrapper code:</h3><pre>Date = [] #to store date data<br>Season_ep = [] #to store season data<br>Guests = [] #to store Guests list<br><br><br><strong>for</strong> i <strong>in</strong> range(3,21):<br>    <br>    element=WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH ,&#39;//*[@id=&quot;page-series&quot;]/div[3]/div[2]/div[2]/div[6]/div[1]/ul/li[&#39;+str(i)+&#39;]/h4/a&#39;)))<br>    element.click()<br>    <br>    <strong>for</strong> j <strong>in</strong> range(1,200):<br>        <strong>try</strong>:<br>            <br>            Season_ep.append(driver.find_element_by_xpath(&#39;//*[@id=&quot;page-season&quot;]/div[4]/div[2]/div[1]/table/tbody/tr[&#39;+str(j)+&#39;]/td[1]&#39;).text)<br>            Guests.append(driver.find_element_by_xpath(&#39;//*[@id=&quot;page-season&quot;]/div[4]/div[2]/div[1]/table/tbody/tr[&#39;+str(j)+&#39;]/td[2]/a&#39;).text)<br>            Date.append(driver.find_element_by_xpath(&#39;//*[@id=&quot;page-season&quot;]/div[4]/div[2]/div[1]/table/tbody/tr[&#39;+str(j)+&#39;]/td[3]/div&#39;).text)<br>        <br>        <strong>except</strong> NoSuchElementException:<br>            <br>            <strong>continue</strong>  <br>    print(&#39;Season:&#39;+str(i-2)+&#39; done&#39;) <br>    <br>    element=WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH ,&#39;//*[@id=&quot;page-season&quot;]/div[3]/div/a[3]&#39;)))<br>    element.click()</pre><p>Keep the chrome browser launched by this notebook open, in front of you, you will see the magic of selenium and python.</p><p><strong>Combining everything together and making a final dataframe</strong></p><pre>d = zip(Season_ep,Date,Guests)<br>mapped = list(d)<br>df = pd.DataFrame(mapped, columns =[&#39;Season&#39;, &#39;Date&#39;,&#39;Guests&#39;])</pre><p><strong>Let’s verify the dataset and see if it is accurate or not</strong></p><p>So I remember <strong>Deepika Padukone</strong> went to Ellen&#39;s show. If this is a complete database as I believe. It should contain that entry. Let&#39;s also see who were <strong>other guests that day</strong>.</p><pre>df[df[&#39;Guests&#39;].str.contains(&#39;Deepika Padukone&#39;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*cYi5afafe-1FkwMUr46YVA.png" /><figcaption>Season 14 Episode 84, on January 18, 2017, was around the release of her Hollywood debut movie <strong>XXX: Return of Xander Cage</strong> with Vin Diesel.</figcaption></figure><pre><em>#Converting date to a much favourable format</em><br><br>df[&#39;Date&#39;] = df[&#39;Date&#39;].apply(<strong>lambda</strong> x: datetime.datetime.strptime(x, &#39;%B <strong>%d</strong>, %Y&#39;).date())<br>df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;])<br>df.tail(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*Wl5q1pSwlBsLvtCEIIkxjg.png" /></figure><p><strong>Github Link </strong>: <a href="https://github.com/Shubham-253/Web-Scraping/tree/main/Ellen%20Show%20(2013-2021)%20web%20scraping%20using%20Selenium">Code_and_Extracted_Dataset</a></p><p><strong>As the case with almost everything, the above results can be obtained in multiple ways this is one of those ways. In the end, I just hope you learned something, it was my first article and I am happy to be able to contribute to this community. Please do give your valuable feedback, I will surely improve on my mistakes.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f315f63ac229" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/web-scraping-using-python-and-selenium-xpath-f315f63ac229">Web Scraping using Python and Selenium(XPATH)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>