<?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 Benjamin Dornel on Medium]]></title>
        <description><![CDATA[Stories by Benjamin Dornel on Medium]]></description>
        <link>https://medium.com/@benjamindornel?source=rss-351e34669aba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9oAYaaxAtUpWpvw9_2d6Yw.jpeg</url>
            <title>Stories by Benjamin Dornel on Medium</title>
            <link>https://medium.com/@benjamindornel?source=rss-351e34669aba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:48:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benjamindornel/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[Building an Offline Streamlit Application with Tauri]]></title>
            <link>https://levelup.gitconnected.com/building-an-offline-streamlit-application-with-tauri-b1121ae6b646?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1121ae6b646</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[tauri]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 18:08:49 GMT</pubDate>
            <atom:updated>2024-07-07T09:31:49.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>Turn your web app into a versatile desktop application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ7IKr9T3Kn3UwvNn8QPAQ.png" /><figcaption><a href="https://statementsensei.streamlit.app/">Statement Sensei</a>: Image by Author</figcaption></figure><h3>Introduction</h3><p>So, imagine that you have a <a href="https://streamlit.io/">Streamlit</a> application. It’s nice, sleek and works well online. There’s only one small problem — for some reason or other, you need to run it offline.</p><p>There are several good reasons for this. For example, your application might be a <a href="https://levelup.gitconnected.com/creating-a-bank-statement-parser-with-python-9223b895ebae">bank statement parser</a>, which deals with sensitive financial information.</p><p>At this point, you might feel like there’s no other solution but to re-write your application from scratch with Javascript and React (which is tough unless you have frontend experience). Luckily, there’s another path forward.</p><p>In this article, I’m going to cover:</p><ol><li>How to turn your Streamlit into an executable using PyInstaller.</li><li>How to use Tauri with your PyInstaller executable to create an offline, desktop application.</li></ol><h3>Creating an Executable</h3><p>The first step is to create an executable file from your Streamlit application. This process is the equivalent of creating a Python virtual environment, installing your dependencies, and then running:</p><pre>streamlit run app.py</pre><p>Which will then launch a local Streamlit server at <a href="http://localhost:8501.">http://localhost:8501.</a></p><p>Sounds simple enough, but this step can be deceptively tricky.</p><p>I’ll go ahead and cover some approaches that you might commonly find online.</p><h4>The Nativefier/Pake Approach</h4><p>If you’re unfamiliar with <a href="https://github.com/nativefier/nativefier">Nativefier</a>, it’s a command-line tool that allows you to easily create a “desktop app” for any website.</p><p>Usage is fairly straightforward:</p><pre>npm install -g nativefier<br>nativefier --name &#39;&lt;app name&gt;&#39; &#39;https://&lt;app name&gt;.streamlit.app/&#39;</pre><p>However, this still requires an internet connection, and is simply a wrapper for a Chromium browser that accesses your application online.</p><p>It’s also deprecated — a good drop in replacement is <a href="https://github.com/tw93/Pake">Pake</a> which has the same functionality but uses Rust + Tauri (more on this later) instead of Javascript + Electron which leads to vastly a decreased executable size.</p><p>TLDR; this approach gives an “online” desktop app</p><h4>The Stlite Approach</h4><p><a href="https://github.com/whitphx/stlite">Stlite</a> is a version of Streamlit that can run directly in your web browser thanks to WebAssembly (a technology that allows code to run in the browser at near-native speed) and Pyodide (a tool that brings Python to the browser).</p><p>This approach uses npm and electron under the hood and allows you to add both system dependencies and Python dependencies. You can find the guide to do this <a href="https://github.com/whitphx/stlite/blob/main/packages/desktop/README.md">here</a>.</p><p>I think it’s a good solution that I would recommend to users. There’s quite a bit of customizability built in, and a focus on security which I like (although this means that you can’t link to <a href="https://github.com/whitphx/stlite/blob/main/packages/desktop/README.md#limitations">external resources </a>outside your app).</p><p>However, this approach might not work if you have Python dependencies that are not “pure” Python.</p><p>For example, my application uses <a href="https://github.com/pymupdf/PyMuPDF">PyMuPDF</a><a href="#e4c4">¹</a> and <a href="https://github.com/jalan/pdftotext">pdftotext</a>, which are Python wrappers for C++ applications. To get this to work with Pyodide, these dependencies need to be manually compiled to get a wheel that is compatible with WASM (more details <a href="https://pyodide.org/en/stable/development/building-and-testing-packages.html#building-and-testing-packages-out-of-tree">here</a>).</p><h4>Other “Python to X” approaches (Pyoxidizer, Nuitka, etc)</h4><p>There are several other projects out there that attempt to convert your Python code into a compiled language like Rust (<a href="https://github.com/indygreg/PyOxidizer">Pyoxidizer</a>) and C++ (<a href="https://github.com/Nuitka/Nuitka/">Nuitka</a>).</p><p>This theoretically should lead to performance improvements, especially for Nuitka which focuses heavily on areas like statically inferring types, constant folding and propagation (calculating constant expressions at compile time and replacing variables with their constant values), and removing dead code (anti-bloat).</p><p>I’d recommend Nuitka over Pyoxidizer, since Pyoxidizer appears to be inactive. If you don’t have complex dependencies to manage, this might be a sound approach. Unfortunately, this didn’t work for me, since the compiler kept timing out during the compilation process.</p><h4>The PyInstaller Approach</h4><p>PyInstaller is similar to projects like Nuitka and Pyoxidizer, but doesn’t try to convert your Python code to any other language. It simply analyzes your application to determine all dependencies and recursively identifies all modules and packages used. It then “freezes” these dependencies, and converts them to Python byte code (.pyc files), which are accessed at runtime.</p><p>This approach is great since beyond a frozen copy of a Python interpreter, it also includes your Python scripts and modules, as well as third-party libraries that require external binaries.</p><p>To create an executable for your Streamlit application, you’ll need to follow these steps.</p><p>First, you’ll need to create an entry point for PyInstaller:</p><pre>import os<br>import sys<br>from pathlib import Path<br><br>import streamlit.web.cli as stcli<br><br><br>def resolve_path(path: str) -&gt; str:<br>    base_path = getattr(sys, &quot;_MEIPASS&quot;, os.getcwd())<br>    return str(Path(base_path) / path)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    sys.argv = [<br>        &quot;streamlit&quot;,<br>        &quot;run&quot;,<br>        resolve_path(&quot;app.py&quot;),<br>        &quot;--global.developmentMode=false&quot;,<br>        &quot;--server.headless=true&quot;,<br>    ]<br>    sys.exit(stcli.main())</pre><p>This entrypoint allows you to run Streamlit programmatically and pass arguments that do things like turning off Streamlit’s development mode. This is important, because when running your executable, Streamlit will <a href="https://github.com/streamlit/streamlit/blob/173bfb82f6fdf95107b39716dc231a6ca0ba3063/lib/streamlit/config.py#L316">automatically default</a> to development mode since PyInstaller doesn’t create regular Python directories like site-packages, dist-packages, or __pypackages__. If development mode is enabled, Streamlit will not launch a webserver for your application.</p><p>You’ll also want to enable headless mode, to prevent message like this from blocking your application during startup:</p><pre>  Welcome to Streamlit!<br><br>  If you are one of our development partners or are interested in<br>  getting personal technical support, please enter your email address<br>  below. Otherwise, you may leave the field blank.<br><br>  Email:</pre><p>Using PyInstaller means that your bundled files will not be stored at their usual paths meaning that a path would normally be: &lt;venv&gt;/site-packages/streamlit/runtime/... instead exists at sys._MEIPATH, which stores the location of unpacked files at runtime.</p><p>With the entry point out of the way, you’ll then need to create a PyInstaller <a href="https://pyinstaller.org/en/stable/hooks.html">hook</a> for Streamlit:</p><pre># hooks/hook-streamlit.py<br><br>import site<br><br>from PyInstaller.utils.hooks import (<br>    collect_data_files,<br>    collect_submodules,<br>    copy_metadata,<br>)<br><br>site_packages_dir = site.getsitepackages()[0]<br>datas = [(f&quot;{site_packages_dir}/streamlit/runtime&quot;, &quot;./streamlit/runtime&quot;)]<br>datas = copy_metadata(&quot;streamlit&quot;)<br>datas += collect_data_files(&quot;streamlit&quot;)<br>hiddenimports = collect_submodules(&quot;streamlit&quot;)</pre><p>This tells PyInstaller to add Streamlit to the executable, and also ensures that static files that Streamlit needs to run like streamlit/static/index.html are copied over. This should also deal with strange errors like ModuleNotFoundError: No module named ‘streamlit.runtime.scriptrunner.magic_funcs’ that might otherwise appear.</p><p>With that done, you can then generate the PyInstaller .spec file:</p><pre>pyinstaller --additional-hooks-dir=./hooks --clean entrypoint.py</pre><p>The .spec file tells PyInstaller how to process your script. You might have to add additional hiddenimports if PyInstaller isn’t able to find certain dependencies, or otherwise import extra files/metadata for certain dependencies.</p><p>You can generate a single executable by removing the col1 = COLLECT(...) block.</p><p>For reference, my .spec file looks something like this:</p><pre># -*- mode: python ; coding: utf-8 -*-<br>from PyInstaller.utils.hooks import collect_submodules<br><br>hiddenimports = []<br>hiddenimports += collect_submodules(&quot;webapp&quot;)<br>hiddenimports += collect_submodules(&quot;pybadges&quot;)<br><br>a = Analysis(<br>    [&#39;entrypoint.py&#39;],<br>    pathex=[],<br>    binaries=[],<br>    datas=[],<br>    hiddenimports=hiddenimports,<br>    hookspath=[&#39;./hooks&#39;],<br>    hooksconfig={},<br>    runtime_hooks=[],<br>    excludes=[],<br>    noarchive=False,<br>    optimize=0,<br>)<br>pyz = PYZ(a.pure)<br><br>exe = EXE(<br>    pyz,<br>    a.scripts,<br>    [],<br>    exclude_binaries=True,<br>    name=&#39;entrypoint&#39;,<br>    debug=False,<br>    bootloader_ignore_signals=False,<br>    strip=False,<br>    upx=True,<br>    console=True,<br>    disable_windowed_traceback=False,<br>    argv_emulation=False,<br>    target_arch=None,<br>    codesign_identity=None,<br>    entitlements_file=None,<br>)<br>coll = COLLECT(<br>    exe,<br>    a.binaries,<br>    a.datas,<br>    strip=False,<br>    upx=True,<br>    upx_exclude=[],<br>    name=&#39;entrypoint&#39;,<br>)</pre><p>You can then run build a single executable with:</p><pre>pyinstaller entrypoint.spec</pre><p>Then run your application by running this into your terminal:</p><pre>chmod +x dist/entrypoint<br>./dist/entrypoint</pre><p>An important caveat to note is that this executable is actually a self-extracting archive, which writes files to a temporary directory to disk at runtime. This means that it’s slower compared to launch compared to PyInstaller’s --onedir mode<a href="#be1a">²</a>.</p><p>This executable will also only work on the distribution that it was created with. For example, assuming you created the executable on Windows, it will only run on Windows and not on MacOS or Linux.</p><p>You should now have an executable that launches a Streamlit webserver on port 8501. However, this is not ideal since your user will need to open their browser, and navigate to <a href="http://localhost:8501/">http://localhost:8501</a> which may not be intuitive for someone not tech-savvy.</p><p>But what if you want the application to automatically open in a browser window?</p><h3>Enter Tauri</h3><p>Tauri is a framework used for building cross-platform desktop applications that is written in Rust. Compared to Electron, it uses the system’s native web renderer (WebView2 on Windows, WebKit on macOS and Linux). This allows for more efficient memory &amp; CPU usage since it uses native web renderers, and also results in smaller application sizes as it doesn’t include a browser engine.</p><p>If you tried out Nativefier earlier, you’ll see that the executable easily goes up to 100–200 megabytes — and this is before any external binaries or dependencies are bundled.</p><p>To get started, you’ll need to install pnpm:</p><pre>curl -fsSL https://get.pnpm.io/install.sh | sh -</pre><p>You can then create a tauri project where your Streamlit project is located with:</p><pre>pnpm create tauri-app --beta</pre><p>To run the example application:</p><pre>  cd tauri-app<br>  pnpm install<br>  pnpm tauri dev</pre><p>If you’ve done these steps correctly, you should see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*cLCz2tGq9n0eBW5_h-vOjQ.png" /><figcaption>Running the example Tauri application</figcaption></figure><p>To give a quick breakdown of the files you’ll now see in the project:</p><p><strong>index.html:</strong> Entry point for your web application; initializes rendering of web content.</p><p><strong>node_modules</strong>: Directory containing Node.js packages and dependencies.</p><p><strong>package.json</strong>: Project manifest with metadata, scripts, and dependencies.</p><p><strong>pnpm-lock.yaml</strong>: pnpm lock file that ensures consistent dependency versions across environments.</p><p><strong>src:</strong> Stores the source code for the front-end application (JavaScript/TypeScript, CSS etc.)</p><p><strong>src-tauri</strong>: Tauri-specific source code, configurations, and Rust backend.</p><p><strong>tsconfig.json</strong>: TypeScript configuration file; sets compiler options.</p><p><strong>vite.config.ts</strong>: Config file for <a href="https://vitejs.dev/">Vite</a>, which is a frontend bundler and build tool that provides various quality-of-life features like hot reloading, and also converts your source code into optimized HTML, CSS and JavaScript when building for production.</p><p>If you’re coming from Python and aren’t familiar with Rust, don’t worry. The backend code itself isn’t very complex. If you look at the code powering the example application at tauri-app/src-tauri/main.rs, it’s actually fairly simple:</p><pre>#[tauri::command]<br>fn greet(name: &amp;str) -&gt; String {<br>    format!(&quot;Hello, {}! You&#39;ve been greeted from Rust!&quot;, name)<br>}<br><br>fn main() {<br>    tauri::Builder::default()<br>        .plugin(tauri_plugin_shell::init())<br>        .invoke_handler(tauri::generate_handler![greet])<br>        .run(tauri::generate_context!())<br>        .expect(&quot;error while running tauri application&quot;);<br>}</pre><p>The above code simply defines a greet function, then spins up Tauri and then registers the greet() command to handle frontend invocations.</p><p>The rest of the greet() logic is stored in a TypeScript file at tauri-app/src-tauri/main.ts. I’ll skip explaining this in detail since we don’t need this functionality to launch our Streamlit app. Basically, this file contains TypeScript code that links the frontend to the Rust backend, and invokes the greet() command in the backend when the greet button is clicked.</p><p>So, you’re probably wondering where Streamlit fits into this picture.</p><p>It turns out that Tauri has a feature that allows you to embed external binaries or a “<a href="https://tauri.app/v1/guides/building/sidecar/">sidecar</a>”. This allows us to use Tauri’s Rust backend to call the executable we created earlier, which essentially spins up a webserver. Neat, huh?</p><p>You’ll need to add an externalBin array to the bundle key in your tauri.conf.json file which tells Tauri where to find your executable.</p><p>For reference, my configuration file looks something like this:</p><pre>{<br>  &quot;productName&quot;: &quot;StatementSensei&quot;,<br>  &quot;version&quot;: &quot;0.3.4&quot;,<br>  ...  <br>  &quot;bundle&quot;: {<br>    &quot;active&quot;: true,<br>    &quot;targets&quot;: &quot;all&quot;,<br>    &quot;icon&quot;: [<br>      &quot;icons/32x32.png&quot;,<br>      &quot;icons/128x128.png&quot;,<br>      &quot;icons/128x128@2x.png&quot;,<br>      &quot;icons/icon.icns&quot;,<br>      &quot;icons/icon.ico&quot;<br>    ],<br>    &quot;externalBin&quot;: [<br>      &quot;binaries/statementsensei&quot;<br>    ]<br>  }<br>}</pre><p>It then expects a binary with your host triplet appended as a suffix to be stored in this folder.</p><p>To find your host triplet:</p><pre># install rust<br>curl --proto &#39;=https&#39; --tlsv1.2 -sSf https://sh.rustup.rs | sh<br><br># find host triplet<br>export HOST_TRIPLET=$(rustc -Vv | grep host | cut -f2 -d&#39; &#39;)</pre><p>Then copy your executable from earlier:</p><pre>export APP_NAME=&lt;this should be whatever your app is called&gt;<br>mkdir tauri-app/src-tauri/binaries<br>cp dist/entrypoint tauri-app/src-tauri/binaries/$APP_NAME-$HOST_TRIPLET</pre><p>This should result in a file tree like this:</p><pre>├── src-tauri<br>│   ├── binaries<br>│   │   └── monopoly-x86_64-unknown-linux-gnu</pre><p>You can then invoke the binary in your code, and get the Tauri browser window to access your Streamlit application:</p><pre>// src-tauri/src/main.rs<br><br>use std::env;<br>use std::time::Duration;<br>use tauri::Manager;<br>use tauri_plugin_shell::ShellExt;<br>use tokio::time::sleep;<br><br>pub fn run() {<br>    tauri::Builder::default()<br>        .plugin(tauri_plugin_shell::init())<br>        .setup(|app| {<br>            let main_window = app.get_webview_window(&quot;main&quot;).unwrap();<br>            let sidecar = app.shell().sidecar(&quot;statementsensei&quot;).unwrap();<br><br>            tauri::async_runtime::spawn(async move {<br>                let (mut _rx, mut _child) = sidecar.spawn().expect(&quot;Failed to spawn sidecar&quot;);<br><br>                // wait for the streamlit server to start<br>                sleep(Duration::from_secs(5)).await;<br>                main_window<br>                  .eval(&quot;window.location.replace(&#39;http://localhost:8501&#39;);&quot;)<br>                  .expect(&quot;Failed to load the URL in the main window&quot;);<br>              });<br><br>            Ok(())<br>        })<br>        .run(tauri::generate_context!())<br>        .expect(&quot;error while running tauri application&quot;);<br>}</pre><p>This is pretty similar to the example code, except that we’re loading in our external binary as a sidecar. Tauri is smart enough to look for the correct binary, so when you call app.shell().sidecar(“statementsensei”), it detects that my host triplet is x86_64-unknown-linux-gnu and looks for statementsensei-x86_64-unknown-linux-gnu in the binaries folder.</p><p>To avoid a pre-mature HTTP 404 error, we wait 5 seconds for the server to spin up, then tell the browser window to navigate to <a href="http://localhost:8501/">http://localhost:8501</a>.</p><p>Great! We’re done. You can then build your project with pnpm tauri build, and then run your application at src-tauri/target/release/bundle/&lt;target&gt;/&lt;app&gt;.</p><p>Naturally, there are further improvements that could be made to the above code. Instead of waiting for a pre-determined amount of time, you could also poll localhost to check for a response, and then load the server when ready.</p><p>You’ll also want to build a way to clean up the sidecar process. Theoretically, this should be handled by Tauri already, but it is <a href="https://github.com/tauri-apps/tauri/discussions/3273#discussioncomment-3426351">common</a> for the sidecar process to exist even after closing the app. Assuming your user opens and closes their application several times, they would end up with multiple processes, which iterate over ports (8501, 8502, 8503 etc.) since Vite uses the next available port if the current one is taken.</p><p>You could also add a loading splash screen, which is slightly involved and therefore something I won’t get into in this article.</p><p>If you’re interested in the polling, automated process cleanup, or splash screen, I have something <a href="https://github.com/benjamin-awd/monopoly-app/blob/779e9bec34157e3430c09e4f171c0e71b58d4a36/tauri/src-tauri/src/lib.rs">here</a> that you can refer to.</p><p>Here’s what a complete iteration of a Streamlit + Tauri application might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zMoVdaAoq27UCW9-qS6h6A.gif" /><figcaption>Streamlit + Tauri App (with splash screen)</figcaption></figure><h3>Cross-Platform Compilation</h3><p>Unfortunately, cross-platform compilation isn’t possible with PyInstaller and Tauri.</p><p>A simple way around this is to use a CICD pipeline like Github Actions that gives you access to runners with different operating systems.</p><p>Specifically, Github Actions has a matrix strategy that lets you use variables in a single job definition to automatically create multiple job runs that are based on the combinations of the variables.</p><p>This could look something like the following:</p><pre>name: Build App &amp; Release<br><br>on:<br>  push:<br>    tags:<br>      - &quot;v*.*.*&quot;<br>  workflow_dispatch:<br><br>defaults:<br>  run:<br>    shell: bash<br><br>jobs:<br>  build:<br>    runs-on: ${{ matrix.os-target.os }}<br>    strategy:<br>      matrix:<br>        os-target:<br>          - os: ubuntu-latest<br>            target: x86_64-unknown-linux-gnu<br>          - os: windows-latest<br>            target: x86_64-pc-windows-msvc<br>          - os: macos-latest<br>            target: x86_64-apple-darwin<br>          - os: macos-latest<br>            target: aarch64-apple-darwin<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v4<br><br>      - name: Setup Conda (windows)<br>        if: matrix.os-target.os == &#39;windows-latest&#39;<br>        uses: s-weigand/setup-conda@v1<br>        with:<br>          activate-conda: false<br><br>      - name: Install pdftotext dependencies (windows)<br>        if: matrix.os-target.os == &#39;windows-latest&#39;<br>        run: |<br>          conda install -c conda-forge poppler<br><br>      - name: Setup brew (mac)<br>        if: matrix.os-target.os == &#39;macos-latest&#39;<br>        uses: Homebrew/actions/setup-homebrew@master<br><br>      - name: Install pdftotext dependencies (mac)<br>        if: matrix.os-target.os == &#39;macos-latest&#39;<br>        run: brew install poppler<br><br>      - name: Install pdftotext dependencies (ubuntu)<br>        if: matrix.os-target.os == &#39;ubuntu-latest&#39;<br>        uses: daaku/gh-action-apt-install@v4<br>        with:<br>          packages: build-essential libpoppler-cpp-dev pkg-config<br><br>      - name: Install Rust<br>        uses: dtolnay/rust-toolchain@stable<br>        with:<br>          toolchain: stable<br>          target: ${{ matrix.os-target.target }}<br><br>      - name: Install Statement Sensei dependencies<br>        uses: ./.github/actions/setup-python-poetry<br>        with:<br>          python-version: &quot;3.11&quot;<br>          poetry-version: &quot;1.8.3&quot;<br><br>      - name: Create executable with pyinstaller<br>        run: poetry run pyinstaller entrypoint.spec<br><br>      - name: Copy executable to tauri binaries<br>        run: cp ./dist/entrypoint ./tauri/src-tauri/binaries/statementsensei-${{ matrix.os-target.target }}<br><br>      - uses: Swatinem/rust-cache@v2<br>        with:<br>          cache-on-failure: true<br>          workspaces: tauri/src-tauri<br><br>      - name: Install tauri dependencies (ubuntu)<br>        if: matrix.os-target.os == &#39;ubuntu-latest&#39;<br>        run: |<br>          sudo apt-get update<br>          sudo apt-get install -y javascriptcoregtk-4.1 libsoup-3.0 webkit2gtk-4.1<br><br>      - name: Install pnpm<br>        uses: pnpm/action-setup@v4<br>        with:<br>          version: 9.0.6<br>          run_install: false<br><br>      - name: Install tauri<br>        working-directory: tauri<br>        run: pnpm install<br><br>      - name: Build tauri app<br>        working-directory: tauri/src-tauri/<br>        run: pnpm tauri build -t ${{ matrix.os-target.target }}<br><br>      - name: Upload tauri app<br>        id: artifact_upload<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: monopoly-${{ matrix.os-target.target }}<br>          path: |<br>            tauri/src-tauri/target/${{ matrix.os-target.target }}/release/bundle/appimage/*.AppImage<br>            tauri/src-tauri/target/${{ matrix.os-target.target }}/release/bundle/nsis/<br>            tauri/src-tauri/target/${{ matrix.os-target.target }}/release/bundle/dmg/<br>          compression-level: 9</pre><p>That’s it for this article! I hope it was helpful for you. If you have any feedback or questions, feel free to reach out to me on <a href="https://www.linkedin.com/in/benjamindornel/">LinkedIn</a>. Otherwise, if you’re looking for my Streamlit + Tauri app, you can find it <a href="https://github.com/benjamin-awd/monopoly-app">here</a>.</p><h3>Notes</h3><p>1: <a href="#c617"><strong>˄</strong></a><strong> </strong>PyMuPDF does have some <a href="https://pymupdf.readthedocs.io/en/latest/pyodide.html">support</a> for Pyodide, but you still need to build it yourself. Unfortunately, micropip.install() doesn’t work because PyMuPDF also uses Emscripten. This means that at any point in time, the versions ofEmscripten used by Pyodide and PyMuPDF will most likely differ, leading to build-time errors when you try to compile the wheel.</p><p>2: <a href="#2a8e"><strong>˄</strong></a><strong> </strong>You can also use PyInstaller’s — onedir mode with Tauri, but you’ll need to embed the internal files and the executable, which is doable but not as straightforward as using a single binary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1121ae6b646" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-an-offline-streamlit-application-with-tauri-b1121ae6b646">Building an Offline Streamlit Application with Tauri</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Bank Statement Parser with Python]]></title>
            <link>https://levelup.gitconnected.com/creating-a-bank-statement-parser-with-python-9223b895ebae?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9223b895ebae</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 16:11:26 GMT</pubDate>
            <atom:updated>2024-07-07T09:33:02.644Z</atom:updated>
            <content:encoded><![CDATA[<h4>Seize control of your finances from those pesky PDF files</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfH1VtcI_RXOy2vV0F7MSg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@theshuttervision">Jonathan Cooper</a> on <a href="https://unsplash.com/photos/blue-and-white-unks-coffee-shop-signage-0O2Pp6-mOkY">Unsplash</a></figcaption></figure><h3>Why do I need a bank statement parser?</h3><p>Managing multiple bank accounts can be a hassle, especially when each bank provides statements in different formats.</p><p>If you’re tired of manually sifting through these statements every month, a bank statement parser could be what you need, saving you time and effort.</p><p>Enter the “bank statement parser” — a software that extracts and organizes unstructured text data from statements. It can identify transaction details, dates, and amounts, and convert them into a structured format for better readability.</p><p>If you’re lucky, your bank provides a way to download your statement as a CSV file. If you’re incredibly lucky, your bank might even support Open Banking with some kind of API (but if you’re like me, you’re probably not that lucky).</p><p>So instead of copy-pasting from a PDF every month, why not create your own bank statement parser instead? In this post, I’ll go through how to use Python to convert your PDF to text, extract the transactions, and ultimately create a parser you can use across different bank statements.</p><h3>Converting your PDF to text</h3><p>The first and most obvious route is to use an open-source Python package, similar to the likes of <a href="https://github.com/py-pdf/pypdf">PyPDF</a>, <a href="https://github.com/pymupdf/PyMuPDF">PyMuPDF</a>, <a href="https://github.com/jalan/pdftotext">pdftotext</a>, or <a href="https://github.com/pdfminer/pdfminer.six">pdfminer</a>. I’m not going to get into the nitty-gritty details of how they differ — there’s a great <a href="https://medium.com/@thibaultmonsel_4024/extract-text-from-pdf-with-python-python-pdf-processing-part-1-be875d76234b">article</a> that already covers that.</p><p>To briefly summarize the article, pdftotext is a really good option since it faithfully represents the layout of each page. This means that your transactions will remain on the same line, and won’t be broken up.</p><p><em>Caveat: You can also use an optical character recognition (OCR) library like PyTesseract or OpenOCR, but this is only necessary if your PDF doesn’t come with embedded text (i.e. it isn’t searchable). There’s a relatively high-performance overhead that comes with higher levels of accuracy. Otherwise, training your own model could also be a feasible approach if you have enough time, bank statements and compute.</em></p><p>For example — let’s say you have this bank statement:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*yhWSLkL1VOqygQILW01rmg.png" /><figcaption><a href="https://github.com/benjamin-awd/monopoly/blob/main/src/monopoly/examples/example_statement.pdf">Example bank statement</a> from <a href="https://medium.com/@benjamindornel">author</a></figcaption></figure><p>If you use pdftotext and print the results:</p><pre>pdftotext -layout .../example_statement.pdf out.txt<br>cat out.txt</pre><p>You’ll get back something like this, with transactions neatly separated per line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKoqtLpSNvmTstv075PMlQ.png" /><figcaption>Raw output from pdftext</figcaption></figure><p>If you open this file with Python, you’ll see that lines are neatly demarcated by newline \n characters, which means you can easily split the text and process it line by line, which is really useful for parsing.</p><h4>So, how do we do this with Python?</h4><p>There’s a nice Python <a href="https://github.com/jalan/pdftotext">wrapper</a> of Poppler’s <a href="https://manpages.debian.org/experimental/poppler-utils/pdftotext.1.en.html">pdftotext</a> that you can use for this:</p><pre>import pdftotext<br><br>with open(&quot;.../example_statement.pdf&quot;, &quot;rb&quot;) as file:<br>    pdf = pdftotext.PDF(file, physical=True)\<br>    first_page = pdf[0]<br>    lines = first_page.split(&quot;\n&quot;)<br>    for line in lines:<br>        print(line.lstrip())</pre><p>We’re using the physical argument to make sure that the original physical layout of the text is maintained, so that transactions are not split up by column or page.</p><p>You can then iterate over the PDF, while stripping away any redundant whitespaces.</p><h3>Extracting Transactions from Text</h3><p>So at this point, hopefully you have your transactions ready for extraction.</p><p>Let’s say our first page looks something like this:</p><pre>example_first_page = [<br>    &quot;random text, foo bar baz                                         &quot;,<br>    &quot;01-07-2023 statement date                   random date 23-07-2023&quot;,<br>    &quot;06/07         URBAN TRANSIT CO.       SINGAPORE      SG      1.38&quot;,<br>    &quot;07/07         MORNING BITES CAFE      SINGAPORE      SG      4.20&quot;,<br>    &quot;13/07         SUNRISE TOAST HAVEN     SINGAPORE      SG      3.20&quot;<br>]</pre><p>Annoyingly, there seems to be a bunch of redundant text and dates that we don’t want. Since transactions may not always appear on the same line, and may start at different positions on each page, it isn’t possible to simply filter them out with something like transactions = example_first_page[2:]</p><p>To get the transactions, we can instead use <strong>regular expressions</strong> i.e. regex.</p><pre>import re<br><br>transactions = []<br>transaction_pattern = (<br>        r&quot;(?P&lt;transaction_date&gt;\d+/\d+)\s*&quot;<br>        r&quot;(?P&lt;description&gt;.*?)\s*&quot;<br>        r&quot;(?P&lt;amount&gt;[\d.,]+)$&quot;<br>)<br><br>for line in example_first_page:<br>    match = re.search(pattern=transaction_pattern, string=line)<br>    if match:<br>        transactions.append(match.groupdict())</pre><p>Here’s a a brief explanation of the transaction pattern if you’re not familiar with regex:</p><p>1. (?P&lt;transaction_date&gt;\d/\d+): Captures the transaction date in the format dd/dd e.g. 06/07<br>2. \s*: Matches zero or more whitespace characters.<br>3. (?P&lt;description&gt;.*?): Captures the transaction description.<br>4. \s*: Matches zero or more whitespace characters.<br>5. (?P&lt;amount&gt;[\d.,]+$: Captures the transaction amount, allowing digits, commas, and periods, ensuring it’s at the end of the line.</p><p>This becomes a lot easier to see and understand with <a href="https://regex101.com/r/ipETUO/1">regex101</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*ljJExz3O3AYIC1YirjT9lQ.png" /></figure><p>The rest of the code is relatively simple — if the pattern matches the string, print the combined text as output, and append a dictionary representation of the match to a list.</p><p>The dictionary should look something like this:</p><pre>{<br>   &#39;transaction_date&#39;: &#39;13/07&#39;,<br>   &#39;description&#39;: &#39;SUNRISE TOAST HAVEN SINGAPORE SG&#39;,<br>   &#39;amount&#39;: &#39;3.20&#39;<br>}</pre><p>You’ve now effectively created a list of dictionary objects, which can be used by something like Pandas.</p><pre>import pandas as pd<br><br>df = pd.DataFrame(transactions)</pre><pre>&gt;&gt;&gt; | transaction_date  | description                      | amount |<br>    |-------------------|----------------------------------|--------|<br>    | 06/07             | URBAN TRANSIT CO. SINGAPORE SG   | 1.38   |<br>    | 07/07             | MORNING BITES CAFE SINGAPORE SG  | 4.20   |<br>    | 13/07             | SUNRISE TOAST HAVEN SINGAPORE SG | 3.20   |</pre><p>Since regex doesn’t handle type coercion, the date and amount columns need to be manually converted to their appropriate types.</p><pre>df[&quot;transaction_date&quot;] = pd.to_datetime(df[&quot;transaction_date&quot;], format=&quot;%d/%m&quot;)<br>df[&quot;amount&quot;] = df[&quot;amount&quot;].astype(float)<br>df.to_csv(&quot;processed_statement.csv&quot;)</pre><p>Once this is done, you can save your processed statement as a CSV file, or combine multiple DataFrames together for a more comprehensive view of your spending.</p><h4>But wait, why are the dates wrong?</h4><p>At this point, if you’ve taken a closer look at your DataFrame, you’ll notice that the transaction dates are inaccurate. This is an obvious no-go for data cleanliness and accuracy.</p><p>The reason for this is because of the short-form date (e.g. 06/07). Pandas doesn’t have any information about what year it is, and so the date defaults to 1900–07–06.</p><p>To fix this, you’ll need to figure out the statement date. If you take a look at the example data, you’ll see something that suspiciously looks like a statement date.</p><pre>... <br><br>&quot;01-07-2023 statement date                   random date 23-07-2023&quot;,<br><br>...</pre><p>Using regex once again:</p><pre>statement_date_pattern = r&quot;\d{2}\-\d{2}\-\d{4}&quot;<br>statement_date = None<br><br>for line in example_first_page:<br>    if not statement_date:<br>        match = re.findall(pattern=statement_date_pattern, string=line)<br>        if match:<br>            statement_date = match[0]<br>            print(statement_date)</pre><p>You can then convert the dates with a lambda function, and some neat f-string manipulation:</p><pre>from datetime import datetime<br><br><br>def convert_date(row, statement_date: str):<br>    statement_date = datetime.strptime(statement_date, &quot;%d-%m-%Y&quot;)<br>    row_year = statement_date.year<br>    row_date = datetime.strptime(row[&quot;transaction_date&quot;], &quot;%d/%m&quot;)<br>    row_day, row_month = row_date.day, row_date.month<br><br>    return f&quot;{statement_date.year}-{row_month:02d}-{row_day:02d}&quot;<br><br>df[&quot;transaction_date&quot;] = df.apply(convert_date, statement_date=statement_date, axis=1)</pre><p>To avoid cross-year datetime issues, you’ll also need the following condition within the function:</p><pre>if statement_date.month == 1 and row_month == 12:<br>    row_year = statement_date.year - 1<br>else:<br>    row_year = statement_date.year</pre><p>And that’s it — you should now have a simple script you can use to process your bank statements each month.</p><h3>Creating a parser</h3><p>A script is great, but a single script isn&#39;t ideal if you have multiple cards/statements.</p><p>Instead, why not create something with a bit more reusability and modularity? If you think about it, you’ll notice a lot is going on — you’re reading the statement, parsing it, and transforming it.</p><p>To make things easier, you can take an object-oriented approach, which means treating each component as a unique class, with different properties and methods.</p><p>Let’s start simple, with a neat way to store all your configuration data.</p><pre>from dataclasses import dataclass<br><br>@dataclass<br>class BankConfig:<br>    bank_name: str<br>    statement_date_pattern: str<br>    statement_date_format: str<br>    transaction_pattern: str<br>    transaction_date_format: str</pre><p>You can then pass in the same regex/date patterns from earlier:</p><pre>example_bank_config = BankConfig(<br>    bank_name=&quot;example-bank&quot;,<br>    statement_date_pattern=r&quot;\d{2}-\d{2}-\d{4}&quot;,<br>    statement_date_format=r&quot;%d-%m-%Y&quot;,<br>    transaction_pattern=(<br>        r&quot;(?P&lt;transaction_date&gt;\d+/\d+)\s*&quot;<br>        r&quot;(?P&lt;description&gt;.*?)\s*&quot;<br>        r&quot;(?P&lt;amount&gt;[\d.,]+)$&quot;<br>    ),<br>    transaction_date_format=r&quot;%d/%m&quot;,<br>)</pre><p>Next, you’ll need to create the parser i.e. the part of your code that reads the PDF and extracts transactions.</p><pre>from datetime import datetime<br>from functools import cached_property<br><br><br>class PdfParser:<br>    &quot;&quot;&quot;Parses a bank statement PDF and extracts transactions and the <br>    statement date<br>    &quot;&quot;&quot;<br>    def __init__(self, file_path: str, bank_config: BankConfig):<br>        self.file_path = file_path<br>        self.bank_config = bank_config<br><br><br>    @cached_property<br>    def pdf(self) -&gt; list[str]:<br>        with open(self.file_path, &quot;rb&quot;) as f:<br>            pdf = pdftotext.PDF(f, physical=True)<br>        return pdf<br><br><br>    @cached_property<br>    def transactions(self) -&gt; list[dict]:<br>        transactions = []<br>        for page in self.pdf:<br>            for line in page.split(&quot;\n&quot;):<br>                pattern = self.bank_config.transaction_pattern<br>                if match := re.search(pattern, line):<br>                    transactions.append(match.groupdict())<br>        return transactions<br><br><br>    @cached_property<br>    def statement_date(self) -&gt; datetime:<br>        first_page = self.pdf[0]<br>        for line in first_page.split(&quot;\n&quot;):<br>            date_format = self.bank_config.statement_date_format<br>            pattern = self.bank_config.statement_date_pattern<br>            if match := re.search(pattern, line):<br>                statement_date = datetime.strptime(<br>                    match.group(),<br>                    date_format<br>                )<br>                return statement_date</pre><p>This is the same code from before, albeit with some slight adjustments. We’re accepting the BankConfig class as an argument along with a file path, and defining several properties to store statement-specific information like the statement date.</p><p>Cached properties are also now being used instead of functions (or regular properties), since they provide lazy evaluation, and will help us avoid performance issues if they are called more than once. They also provide a consistent interface, which will come in handy when we begin to transform our data.</p><h3>Extracting transactions to a DataFrame</h3><p>With the “parser” completed, it’s now time to create the statement “processor” which is responsible for cleaning and transforming the transactions.</p><p>One way to do this is by treating the “processor” as a child class, and the “parser” as a parent class.</p><p>To do this, we’ll tap on Python inheritance by calling the super() method, which grants the “processor” class access to the properties and methods in the “parser” class.</p><p>Here’s what that might look like:</p><pre>import pandas as pd<br><br><br>class StatementProcessor(PdfParser):<br>    def __init__(self, file_path: str, bank_config: BankConfig):<br>        self.file_path = file_path<br>        self.bank_config = bank_config        <br>        super().__init__(file_path, bank_config)<br><br><br>    def extract(self) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Extracts transactions from a PDF, and represents<br>        them in a Pandas DataFrame<br>        &quot;&quot;&quot;<br>        return pd.DataFrame(self.transactions)<br><br><br>    def transform(self, df: pd.DataFrame) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;<br>        Transforms the column types of a Pandas DataFrame<br>        &quot;&quot;&quot;<br>        date_format = self.bank_config.transaction_date_format<br>        df[&quot;transaction_date&quot;] = df.apply(<br>            self._convert_date, <br>            statement_date=self.statement_date, <br>            transaction_date_format=date_format, <br>            axis=1<br>        )<br>        df[&quot;transaction_date&quot;] = pd.to_datetime(df[&quot;transaction_date&quot;])<br>        df[&quot;amount&quot;] = df[&quot;amount&quot;].astype(float)<br>        return df<br><br><br>    @staticmethod<br>    def _convert_date(row, statement_date: datetime, transaction_date_format: str) -&gt; str:<br>        row_year = statement_date.year<br><br>        if statement_date.month == 1 and row_month == 12:<br>            row_year = statement_date.year - 1<br><br>        row_date = datetime.strptime(row[&quot;transaction_date&quot;], transaction_date_format)<br>        row_day, row_month = row_date.day, row_date.month<br><br>        return f&quot;{row_year}-{row_month:02d}-{row_day:02d}&quot;<br><br><br>    def load(self, df: pd.DataFrame):<br>        &quot;&quot;&quot;<br>        Writes the input DataFrame to a CSV file<br>        &quot;&quot;&quot;<br>        df.to_csv(<br>            f&quot;{self.bank_config.bank_name}-&quot;<br>            f&quot;{self.statement_date.month:02d}.csv&quot;, <br>            index=False<br>        )</pre><p>This class takes the same arguments as the parser, and passes these arguments to the constructor of the parser itself. Besides that, this class contains the extract, transform and load (ETL) logic for the bank statement.</p><p>You can try tweaking the configuration and running the processor on your own statement, or you can use this sample <a href="https://github.com/benjamin-awd/monopoly/blob/c33605b/src/monopoly/examples/example_statement.pdf">statement</a>.</p><pre>pdf_file_path = &quot;.../example_statement.pdf&quot;<br>processor = StatementProcessor(<br>    pdf_file_path,<br>    example_bank_config<br>)<br>df = processor.extract()<br>transformed_df = processor.transform(df)<br>processor.load(transformed_df)</pre><p>Putting it all together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8236f697bb035b244783f39492cbd616/href">https://medium.com/media/8236f697bb035b244783f39492cbd616/href</a></iframe><p>To test this out, you can save this script, and run it with python3 statement_parser.py (if you’re using your own statement, you’ll need to update the pdf_file_path and various regex/date patterns).</p><p>There’s a lot further you can go with in terms of abstracting the code and config, or making it more performant, though unless you’re parsing thousands of PDFs you probably won’t need to worry about speed.</p><p>To make this truly interchangeable between banks will also take a bit more work, since you’ll need to deal with different transaction formats, and types of debit/credit syntax (e.g. cashback and refunds).</p><p>If you’re wondering what a more fleshed-out version of this looks like, you can visit my <a href="https://github.com/benjamin-awd/monopoly">repository</a>, which implements the parser as a command-line tool called <a href="https://pypi.org/project/monopoly-sg/">Monopoly</a> (there’s also an app version <a href="https://github.com/benjamin-awd/StatementSensei">here</a>, if you’re interested).</p><h3>Taking to the Cloud</h3><p>If having a local parser isn’t enough, you can also try to implement it in the cloud. In an ideal world, as soon as your statement hits your email, you can process it and send yourself the raw transactions.</p><p>This enters a bit into the realm of data engineering, where you need to set up a type of “data pipeline”. This might entail setting up auto-forwarding rules from your primary email address to a service email account, or by getting your bank to send the statements to your address.</p><p>Here’s an example of what that might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4bGe3iCGE-Y8qaFwWIGxrA.png" /></figure><p>This is pretty tough, since you’ll need to set up the infrastructure and containerized version of the parser. Terraform + Docker works pretty well for this.</p><p>You’ll also need to work with the Gmail API, and handle permissions/secrets for any PDFs that might be password encrypted.</p><p>As a starting point, you can use this <a href="https://github.com/benjamin-awd/monopoly-cloud">repository</a>, which runs a containerized version of <a href="https://pypi.org/project/monopoly-sg/">Monopoly</a> as a Google Cloud Run job on a daily schedule.</p><p>That’s it for this article! I hope it was helpful for you. If you have any feedback or questions, feel free to hit me up on <a href="https://www.linkedin.com/in/benjamindornel/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9223b895ebae" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/creating-a-bank-statement-parser-with-python-9223b895ebae">Creating a Bank Statement Parser with Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Database Front End with Deepnote]]></title>
            <link>https://medium.com/data-science/creating-a-database-front-end-with-deepnote-3271b441a47d?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3271b441a47d</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[deepnote]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 08:49:56 GMT</pubDate>
            <atom:updated>2022-04-06T07:41:12.652Z</atom:updated>
            <content:encoded><![CDATA[<h4>DATA ENGINEERING</h4><h4>Here’s how I automated my reports with Python Notebooks in the cloud</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2X-B7taPwOPbgd1RuoT3VA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sebastiancoman?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sebastian Coman Photography</a> on <a href="https://unsplash.com/s/photos/chef?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Handling reporting as a data professional is like being a chef in a kitchen. You have an extremely large amount of raw material that needs to be sourced, delivered, and transformed into meals for customers.</p><p>Except in this case, the raw material is data and the output tends to be reports for business stakeholders. As you can imagine, doing this over and over with Excel and 3rd party platforms is repetitive, and not fun at all.</p><p>Fortunately, a lot of issues around repetitive and low value reporting can be resolved by a mixture of SQL and Python (e.g. pandas). We’re also seeing a massive push towards self-service reporting with products like Power BI and Tableau, with companies developing their data infrastructure to support this.</p><p>However, the main problem for a lot of these companies is that they fall flat in the crucial step of operationalizing their data.</p><p>Sure — they might have data sitting in a warehouse somewhere, but a flexible method is still needed for the end user to access data as they desire. If your users don’t have strong SQL skills and if dashboards aren’t enough, a database frontend could be what you need.</p><p>In this article, I’ll be covering Deepnote and how I used it to create a database front-end for my company.</p><h3><strong>Enter Deepnote</strong></h3><p>If you haven’t heard of it before, Deepnote is a free collaborative Python notebook that runs in your browser — it’s pretty similar to Jupyter Notebook but can be run in the cloud without needing to install Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*h9XjhGgqqNy6VL9AeyDrjg.gif" /><figcaption>Deepnote (<a href="https://deepnote.com/static/landing-new/video.mp4">Source</a>)</figcaption></figure><p>You can go beyond Deepnote’s basic SQL query functionality by using a Python client library which to connect directly to data warehouses like Google BigQuery, with a code snippet like this:</p><pre>import json<br>import os<br>from google.oauth2 import service_account<br>from google.cloud import bigquery</pre><pre>bq_credentials = service_account.Credentials.from_service_account_info(<br> json.loads(os.environ[‘INTEGRATION_NAME_SERVICE_ACCOUNT’]))<br>client = bigquery.Client(credentials=bq_credentials, <br> project=bq_credentials.project_id)</pre><p>Deepnote also has a GitHub integration, meaning that you can easily create and store functions that can be re-used within multiple notebooks. This makes it a lot easier to automate reporting processes for your users.</p><p>All of this put together allowed me to create a Python library (or “Ramsey” as I like to call it) to automate reporting by pulling data from our various marketing platforms.</p><p>No complicated SQL queries — just fill in the parameters, add in a few optional lambda expressions, then hit execute and download.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkhrzlQrbeg7QWu_M6rfMw.gif" /><figcaption>Automated data extraction &amp; transformation with Ramsey</figcaption></figure><p>For my particular use-case (basically the GIF above), data was being pulled from various platforms into a data warehouse, but wasn’t actually being used to help with reporting. I took the additional step of creating a front-end for my team to easily extract, transform and download data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAXTimeYSXG8s9WJyqURKw.jpeg" /><figcaption>Reporting process flowchart</figcaption></figure><h3><strong>Implementing the Front End</strong></h3><p>This front-end above looks deceptively simple, but there is in fact a lot going on under the hood.</p><p>The front-end is based around a parent class called Pipeline which holds a SQL query template with parameters that can be swapped out depending on the table that is being used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b6a4149f0973912413ec61c1d657134/href">https://medium.com/media/0b6a4149f0973912413ec61c1d657134/href</a></iframe><p>The Pipeline class also holds the function to generate the final SQL query which looks something like this —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca336e679096cc80f8942baa7747a792/href">https://medium.com/media/ca336e679096cc80f8942baa7747a792/href</a></iframe><p>If you’ve ever tried comparing data across platforms like Facebook and Twitter, you’ll realize that almost all the metrics and dimensions are named differently.</p><p>This necessitates quite a bit of cleaning and grouping of data. Accordingly, each marketing data provider (or table in BigQuery) is then represented by a child class, that contains various dictionaries that will be used to help rename or group dimensions and metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6f8942e39bcd51efe2364244a63bac/href">https://medium.com/media/df6f8942e39bcd51efe2364244a63bac/href</a></iframe><p>In a nutshell, the FacebookAdsPipeline child class inherits the query template and generate_query() function from the Pipeline parent class. The user then creates a dictionary storing the necessary parameters, before creating and running the pipeline.</p><pre>import pandas as pd<br>from pipeline import Pipeline<br>from platforms import FacebookAdsPipeline</pre><pre># Creating a dictionary to pass into the pipeline<br>params = {<br>&quot;start_date&quot;: &quot;2021-10-01&quot;,<br>&quot;end_date&quot;: &quot;2021-12-24&quot;,<br>&quot;campaign_identifier&quot;: &quot;123123123&quot;,<br>&quot;campaign_name&quot;: &quot;2022_Q1_Campaign_Name&quot;,<br>&quot;output_file_type&quot;: &quot;csv&quot; # Options are .csv / .xlsx<br>}</pre><pre># Passing in parameters &amp; extracting data via BigQuery SQL<br>fb = FacebookAdsPipeline(**params)<br>df = fb.extract()<br>df.to_csv(&quot;output.csv&quot;)</pre><p>To avoid having to manually instantiate each child class, I created a grandparent class — Sandwich — that automatically detects and pulls data from each platform that was used by a marketing campaign.</p><p>This removed the need to keep track of which platform a marketing campaign was run on. Overall, this saved my team (well, honestly me), countless hours of either copy-pasting SQL code or pulling data directly from each marketing platform.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2dff3fc43dcfae1f5e3a10312a5d4a8/href">https://medium.com/media/f2dff3fc43dcfae1f5e3a10312a5d4a8/href</a></iframe><p>The data is extracted through the extract_all() function which is stored in the Sandwich class. The function queries an aggregated table of top-level campaign data across all marketing platforms and returns a list of platforms where a campaign is found to have run.</p><p>Pipelines for each provider are then instantiated, and the extract() method is individually run on each pipeline. Data is then grouped by marketing channel, and saved as a dictionary within the instantiated classes.</p><p>Lastly, the data is transformed with a transform_all() function and saved to a output directory as a CSV or XLSX file.</p><p>It’s all pretty complex, but this is a consequence of how I designed this front-end with the user’s preference in mind. I wanted to give users the option of using this as a low code or high code tool, depending on whether they want to use Excel or Python for data cleaning &amp; transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiM6hO8crOvDlaey-W0ucg.png" /><figcaption>Front-end options: low code &amp; high code</figcaption></figure><h3><strong>Preparing for the Future</strong></h3><p>To be honest, a lot of this could have been accomplished with SQL, but it goes back to the issue of SQL code complexity and having to join a massive number of tables in a single query. This also doesn’t take into account the size of a fully aggregated table (probably several terabytes) which would probably be slow/expensive to query.</p><p>Hosting individual notebooks and bite-sized functions for different reports &amp; projects is, in my opinion, more feasible compared to writing thousands of lines of SQL code.</p><p>I also wanted the option of real-time collaboration, with the option for users to create new functions on the go. Lastly, having a Python Notebook format paves the way for more advanced analytics with packages like scikit-learn, or more advanced visualizations with plotly /seaborn.</p><p>At the end of the day, there’s no single “right” way to automate reporting. Dashboards, Python Notebooks, and Excel/Google Sheet reports are all great to have. Having more options available benefits a wide-spectrum of end-users.</p><p>That’s it for this article! I hope it was insightful/helpful for you. If you have any feedback or thoughts, free to reach out through <a href="https://www.linkedin.com/in/benjamindornel/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3271b441a47d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-a-database-front-end-with-deepnote-3271b441a47d">Creating a Database Front End with Deepnote</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taking on a Data Science Bootcamp in 2021]]></title>
            <link>https://medium.com/data-science/taking-on-a-data-science-bootcamp-in-2021-af36b9f6613b?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/af36b9f6613b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 13:53:58 GMT</pubDate>
            <atom:updated>2021-02-26T13:53:58.227Z</atom:updated>
            <content:encoded><![CDATA[<h4>Things that I liked (and didn’t like) about my bootcamp experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wePoai4tV0ArGsrsN9Fwjg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wildlittlethingsphoto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Helena Lopes</a> on <a href="https://unsplash.com/s/photos/table-laptops-group?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Hi folks! This post is about my personal experience with a Data Science bootcamp, specifically General Assembly’s Data Science Immersive course in Singapore. I’ll be covering several areas, including why I decided to join and several things that I liked (and didn’t like) about it.</p><p>I’ve also included some Singapore-specific additional resources below to help anyone interested in making the transition into data science.</p><p>Without further ado, read on for details on my data science bootcamp experience in 2021.</p><h3>Why did I join?</h3><p>Like many fresh graduates, I had no clue what I wanted to do after university. I graduated with a degree in Global Studies (BA Hons. from NUS) in 2019 and ended up working in the field of technology public relations for about a year — it made for interesting work, but I knew it wasn’t the right career for me.</p><p>In July 2020, I quit my job and focused on transitioning to a career in data analytics. I chose General Assembly’s Data Science Immersive (DSI) mainly because it was eligible for a government subsidy under the <a href="https://www.imda.gov.sg/imtalent/programmes/tipp">TIPP scheme</a>. This reduced the course fees by quite a substantial amount. I also spoke to people that had taken the course previously and heard good things so far, so I decided to bite the bullet and sign up for the nearest intake in October 2020.</p><h3>Was it worth it?</h3><p>In a nutshell, yes — it was absolutely worth it for me. While I had already made some progress on my own before the bootcamp, having a structured environment really helped me to push myself and accomplish more than what I could have done on my own.</p><p>I feel that the portfolio I created during the bootcamp, together with the technical skills I gained, really helped give me a fighting chance in finding a job as a data analyst.</p><h3>Things I liked</h3><p>There were tons of things that I loved about the course. I think my batch was lucky as we got a very knowledgeable instructor who took the time to break down complicated concepts and explain them clearly and coherently. Our teaching assistants also provided crucial support for us throughout the course and were both friendly and approachable.</p><p>I really enjoyed the bootcamp because of my fellow coursemates. There’s something to be said about having a like-minded community of people to grow with and help you when you’re confused about a concept. This also translates into having a professional network after the course.</p><p>I also felt that the content of the course held up to my expectations. The course materials and notes were well written and explained most of the concepts extremely well. The instructions and requirements for our projects/labs were clear and supported our learning.</p><p>Surprisingly, the hybrid format of the bootcamp also worked out for me. Due to COVID-19, our classes had an offline-online structure, where classes were conducted in-person on campus for two days, and on Zoom for the remaining days. This allowed me to save on traveling time and gave me the chance to rest and recharge after a tiring day of lessons.</p><h3>Things I didn’t like</h3><p>My biggest issue with the bootcamp was actually with the projects that they gave us. The purpose of the projects is twofold — to give us a hands-on experience with real-world data and also act as portfolio pieces. However, these projects have been repeatedly shared between campuses over several years, so they’re not exactly unique.</p><p>Imagine that you’re going for an interview where the interviewer has seen the same projects (or similar iterations of the same project) from the same bootcamp again and again. Not exactly great. I really recommend putting in some extra effort to differentiate your projects from what’s already out there. From my experience, interviewers actually do take notice of this.</p><p>Unfortunately, our career coach also resigned halfway through our course. This was actually pretty disruptive as there was no replacement career coach lined up. However, this was something probably unique to my particular batch. The General Assembly team did their best to support us during that time, which is something I appreciated.</p><h3>Final takeaways</h3><p>If I could go back in time, I’d still pick General Assembly’s Data Science Immersive. I think I got a tremendous amount of value from the course and overall I really enjoyed the experience. I’d recommend it for anyone looking to go deeper into data analytics, or as a starting point for someone looking to break into data science.</p><p>An important caveat is that the bootcamp doesn’t necessarily guarantee you a job. You’ll have to put in the hours to internalize whatever you’re learning and demonstrate your capabilities to potential employers. On that note, I found that having a strong coding background before starting the bootcamp was extremely useful. It allowed me to dedicate more time to improving my projects (instead of worrying about nitty-gritty coding details) and do fun stuff like creating my own personal website.</p><h3>Additional resources</h3><p>Before ending this article, I’d like to share some Singapore-specific resources for anyone interested in transitioning to a career in data science or data analytics.</p><p>An extensive list of bootcamps that qualify under the IMDA’s Tech Immersion and Placement Programme (TIPP) can be found <a href="https://www.imda.gov.sg/imtalent/programmes/tipp#EligiblePartnersandCourses">here</a>.</p><p>Some other relevant programs that I’ve come across are <a href="https://rise.bcg.com/programme/">BCG’s Rise</a>, various SGUnited Skills Programs from <a href="https://www.ntuclearninghub.com/sgunited-skills-programme/">NTUC</a>, <a href="https://www.sutd.edu.sg/Education/Academy/SGUnited-Skills/">SUTD</a>, <a href="https://www.tp.edu.sg/content/dam/tp-web/files/sgunited-skills-programme/up-skill-in-data-science.pdf">Temasek Polytechnic</a>, and <a href="https://www.sp.edu.sg/pace/courses/sgus-programme/sgus-specialist-diploma-in-data-science-and-analytics">Singapore Polytechnic</a>. Some of these courses might have already started, but there’s a chance there might be similar courses in the future.</p><p>Lastly, I’d like to share some other articles from people who’ve been through a similar bootcamp experience:</p><ul><li><a href="https://medium.com/@jeremiahng23/general-assembly-dsi-data-science-immersive-sg-experience-and-advice-660fdd25cafa">General Assembly DSI (Data Science Immersive) SG Experience and Advice</a></li><li><a href="https://towardsdatascience.com/how-to-make-the-most-of-your-first-data-science-bootcamp-8c12653a7a48">How To Make The Most Of Your First Data Science Bootcamp</a></li><li><a href="https://towardsdatascience.com/things-i-wish-i-knew-before-joining-metis-singapore-data-science-bootcamp-8768b9e9fda2">Things I wish I knew before joining Metis Singapore Data Science Bootcamp</a></li></ul><p>I hope you enjoyed this article! If you have any feedback or thoughts, free to connect with me on <a href="https://www.linkedin.com/in/benjamindornel/">LinkedIn</a> or <a href="https://twitter.com/benjamindornel">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af36b9f6613b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/taking-on-a-data-science-bootcamp-in-2021-af36b9f6613b">Taking on a Data Science Bootcamp in 2021</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Online News Popularity (Part 1)]]></title>
            <link>https://medium.com/data-science/predicting-online-news-popularity-part-1-aae9a4f7f1a4?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/aae9a4f7f1a4</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[new-york-times]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Wed, 03 Feb 2021 15:01:23 GMT</pubDate>
            <atom:updated>2021-02-03T15:01:23.068Z</atom:updated>
            <content:encoded><![CDATA[<h4>An exploratory data analysis of 16K articles from the New York Times</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93xZ0Q_aq4nYqeo2YQ1UYg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@valentinsteph?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Stéphan Valentin</a> on <a href="https://unsplash.com/s/photos/new-york-times?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>News organizations have increasingly come to rely on media analytics as a way to attract and retain readers. This has become especially true with <a href="https://www.niemanlab.org/2020/05/the-new-york-times-success-with-digital-subscriptions-is-accelerating-not-slowing-down/">ad revenue falling drastically</a> this year due to COVID-19 and other pre-pandemic trends.</p><p>It’s become vital for media companies to know which news articles resonate with readers, and which articles don’t. With this in mind, I wanted to find out what makes a news article popular or unpopular. I decided to look at online news articles from the New York Times and <strong>predict news popularity</strong> based on various features including word count and headline &amp; abstract length.</p><p>In this post, I’ll focus mainly on exploratory data analysis, where I’ll pick out trends and patterns while figuring out what might be the most important predictors for a machine learning model.</p><h3>The Data</h3><p>For this project, I accessed the New York Times API and retrieved metadata for articles and comments between January 1 to December 31, 2020. You can follow the steps <a href="https://towardsdatascience.com/collecting-data-from-the-new-york-times-over-any-period-of-time-3e365504004">here</a> for a tutorial on how to do this.</p><p>In total, I managed to obtain over <strong>16,000 articles </strong>with <strong>11 features</strong> and nearly <strong>5,000,000 comments</strong> with <strong>23 features</strong>. I’ve uploaded the full dataset on <a href="https://www.kaggle.com/benjaminawd/new-york-times-articles-comments-2020">Kaggle</a> for anyone who wants to give it a spin.</p><p>Let’s take a look at our target variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyV_MASt8RbcpZsHAkj1nA.png" /><figcaption>Distribution of comments across all articles</figcaption></figure><p>Our comments are pretty unevenly distributed across our articles. In particular, 50% of our articles have less than 90 comments. Here, you could either go forward with this as a regression project or as a classification project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_11Lsozzauipfa2SLwQF5Q.png" /></figure><p>For my project, I created a binary classification variable, where I chose to classify articles with more than 90 comments as popular, and articles with less than 90 comments as unpopular. As you can see, our data is almost evenly split between our positive and negative classes.</p><h3>Exploratory Data Analysis</h3><p>So what are the most important factors when it comes to article popularity? Let’s find out.</p><h4>Word Count</h4><p>You might able to intuitively guess that one of the most important predictors for article popularity is word count, which actually has a decent positive correlation with our target class. The only problem here is that our word count variable is pretty skewed.</p><p>In general, machine learning algorithms tend to perform better when the distribution of variables is normal -- in other words, performance tends to improve for variables that have a standard distribution. Below, I tried various transformation methods to try and achieve a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*ur9KgFO5D8VlN3YZIogMCQ.png" /></figure><p>You’ll notice that a group of articles have a word count of 0. These are interactive articles that don’t contain words. This data isn’t exactly ‘missing at random’ (MAR) so I decided not to go for any kind of imputation here.</p><p>To demonstrate the positive correlation between the number of comments and word count, I made a scatterplot that shows compares word count versus the number of comments of articles from the top five newsdesks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dcaquvNJh1n7xXRmyOlWHQ.png" /></figure><p>Interestingly, the word count of articles from the OpEd news desk doesn’t have a positive correlation with the number of comments per article.</p><h4>News Desk</h4><p>Below are the biggest news desks from within my dataset. These news desks represent more than 50% of my dataset. Unsurprisingly, articles from the OpEd news desk have the highest average popularity, followed by Foreign and Business news desks. In 2017, the NYT implemented a <a href="https://www.nytimes.com/2017/06/13/insider/have-a-comment-leave-a-comment.html">new commenting system</a> that opened up OpEd articles and other selected news articles for 24 hours. This is likely part of the reason why OpEd articles seem to draw a higher frequency of comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*OR-a7mF5DZFsLBRDeylJMg.png" /></figure><h4>Headline &amp; Abstract Length</h4><p>The length of an article’s headline and abstract also has some bearing on popularity. Below, you can see that there’s a bit of a U-shaped distribution. Articles with less wordy headlines and abstracts tend to be more popular than articles with wordier headlines and abstracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtL6M393tgy7IRHtLTxqWA.png" /></figure><p>However, there’s also a bit of a reverse trend where articles with really long headlines and abstracts tend to do well. We see that at the extreme upper and lower ends, article popularity is pretty unpredictable and tends to fluctuate greatly.</p><h4>Type of Material</h4><p>We can see that Editorials and OpEd pieces tend to do tremendously well. News analysis and interactive features tend to be more popular, while regular news tends to be a bit less popular. Reviews, obituaries, and news briefings generally don’t do well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aB1OqFUikcCWWgb_cm8EQQ.png" /></figure><h4>Day of Week</h4><p>It turns out that articles posted on weekends actually do better — we can infer that is due to the inverse relationship between the number of articles published in a day and average popularity. In other words, articles tend to do better on the weekend as there is less ‘competition’ between articles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqMjsfARVjqt7O6gc0df9Q.png" /></figure><h4><strong>Time of Day</strong></h4><p>Lastly, time of day also has an impact on popularity. Articles published at night seem to have a greater tendency to be popular, as compared to articles that are published during the day — except at 9 am.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBiWjBwL_xTXPl9tKk1ONA.png" /></figure><h4>Keywords / Topics</h4><p>This isn’t going to be surprising to anyone, but certain topics do much better than other topics. Using our article keywords as a proxy for topics within our articles, we can compare the popularity of topics across time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbyKaHgMLdG_eUlOnXauyw.png" /></figure><p>I’ll start with the (orange) elephant in the room here — Donald Trump has been an extremely hot topic for the New York Times ever since 2016. This was no different in 2020, though we can see that the news cycle hit a climax in October and began to taper off slightly towards December with the end of the Presidential Election debacle.</p><p>Judging by the frequency of popular articles per month, we can clearly see that COVID-19 news pretty much hit its peak in April before tapering off towards the end of the year.</p><p>Race &amp; ethnicity became a hot topic this year with the George Floyd protests in May and June.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfFJtFVE52wQR7IVpmMjeA.png" /></figure><p>If we dig down a bit further and look at average popularity, there’s a stark contrast in popularity between topics. ~80% of articles mentioning Donald Trump were popular, while only ~30% of articles mentioning real estate were popular.</p><h3>Conclusion</h3><p>There are a few key trends here that are worth paying attention to:</p><ul><li>Longer articles tend to do better overall (except for OpEd articles)</li><li>Articles from the OpEd, Politics, Games, and Washington news desks are likely to be popular, while articles from the Sports, Culture, and Podcast news desks are likely to be unpopular.</li><li>Articles with shorter headlines &amp; abstracts (between 50–130 words)are more likely to be popular.</li><li>News analysis and interactive articles tend to more popular than obituaries and regular news reports.</li><li>The date &amp; time of publication can affect an article’s popularity — articles seem to do better when published during the weekend or at night between 11 pm to 2 am.</li><li>Certain topics do much better than other topics throughout the year (e.g. Donald Trump), while other topics only do well during certain points of the year.</li></ul><h3>Thanks for reading!</h3><p>That’s all for this post — hope you enjoyed it! I might make another post covering feature engineering &amp; modeling at a later point, but if you’re interested in seeing the source code for this project, you can find it <a href="https://github.com/benjamin-awd/NYT-Article-Popularity">here</a>. You can also find a slightly more technical write-up on my <a href="https://www.benjamindornel.com/nyt-article-popularity.html">website</a>.</p><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/benjamindornel/">LinkedIn</a> as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aae9a4f7f1a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/predicting-online-news-popularity-part-1-aae9a4f7f1a4">Predicting Online News Popularity (Part 1)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Email Parser with Python and SQL]]></title>
            <link>https://medium.com/data-science/creating-an-email-parser-with-python-and-sql-c79cb8771dac?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c79cb8771dac</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 04:15:40 GMT</pubDate>
            <atom:updated>2023-12-02T09:42:42.521Z</atom:updated>
            <content:encoded><![CDATA[<h4>Boost your productivity by automatically extracting data from your emails</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuheXKNPd97EDoTAWe5OMQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@solenfeyissa">Solen Feyissa</a> on <a href="https://unsplash.com/photos/LBNJi8qHIbA">Unsplash</a></figcaption></figure><h4><strong>Huh, what’s that? An email … parser?</strong></h4><p>You might be wondering what an email parser is, and why you might need one.</p><p>In short, an email parser is a software that looks for and extracts data from inbound emails and attachments. More importantly, an email parser uses conditional processing to pull the specific data that matters to you.</p><p>So why does this matter? If you’ve ever spent any time working a regular office job, you’ve probably become intimately familiar with reports, and by extension, copy-pasting lines of text from Microsoft Outlook to Excel or Word.</p><p>You might even end up doing the same report, week after week. Add in formatting and spellchecking, and this ends up as a huge time drain when you could be focusing on more important tasks.</p><p>The good news is that you can automate most of this process with Python and SQL.</p><p>In this post, I’ll cover how to open Outlook emails with Python and extract the body text as HTML. I’ll then cover how to parse this in Python and how to upload the final data to a SQL database. From there, you can write this data to Excel or transform it into a Pandas Dataframe.</p><h3>Getting started</h3><p>We’ll be using a few key Python libraries here, namely os, sqlite3 and pywin32.</p><p>To start off, we’ll first need to decide what we want to extract from our emails. For example, let’s say we have a bunch of emails that each contain a list of news articles like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*0DvUIIoPhigwYimwgLl_Rw.png" /></figure><p>Let’s then say that we want to extract the <strong>header </strong>of each bullet point, which includes the title, the publication, media platforms, and URL links. In short, we want to take the entire header of each bullet point, then break it down into four different parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*9cwwKgl6nNs5OA8_T8CxMg.png" /><figcaption>Sample header that we want to extract text from</figcaption></figure><p>Our pseudocode so far should look something like this:</p><pre>1. Create list of emails that we want to parse<br>2. Open first email<br>3. Iterate over each bullet point<br>4. Extract data from bullet point<br>5. Upload data from bullet point to a database<br>6. Repeat until all data is parsed, then move to next email</pre><h3><strong>Creating a SQL Database</strong></h3><p>Before parsing our emails, we’ll first want to set up a SQL database with Python. We’ll do this by establishing a connection to the SQLite database with a connection object that we’ll call db.</p><pre># Create &amp; connect to database<br>db = sqlite3.connect(&quot;emails.db&quot;)</pre><p>If it doesn’t already exist, a new database will be created as emails.db. We can then create tables in our database that our email parser can write to later on.</p><pre># Create empty tables<br>db.execute(&quot;&quot;&quot;<br>CREATE TABLE IF NOT EXISTS &quot;articles&quot; (<br>    &quot;id&quot; INTEGER,<br>    &quot;title&quot; TEXT UNIQUE,<br>    &quot;publication&quot; TEXT,<br>    PRIMARY KEY(&quot;id&quot; AUTOINCREMENT)<br>);<br>&quot;&quot;&quot;)<br><br>db.execute(&quot;&quot;&quot;<br>CREATE TABLE IF NOT EXISTS &quot;links&quot; (<br>    &quot;article_id&quot; INTEGER,<br>    &quot;link0&quot; TEXT,<br>    &quot;link1&quot; TEXT,<br>    &quot;link2&quot; TEXT,<br>    PRIMARY KEY(&quot;article_id&quot;)<br>);<br>&quot;&quot;&quot;)<br><br>db.execute(&quot;&quot;&quot;<br>CREATE TABLE IF NOT EXISTS &quot;platforms&quot; (<br>    &quot;article_id&quot; INTEGER,<br>    &quot;platform0&quot; TEXT,<br>    &quot;platform1&quot; TEXT,<br>    &quot;platform2&quot; TEXT,<br>    PRIMARY KEY(&quot;article_id&quot;)<br>);<br>&quot;&quot;&quot;)</pre><p>In essence, we’re creating three tables, where our main table is ‘articles’, which has a one-to-many relationship with ‘platforms’ and ‘links’. In other words, this reflects how one article can have many different platforms and links.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*iN3dawbDLg3m5b_nShHmtw.png" /><figcaption>Our database schema</figcaption></figure><h3>Accessing your Emails in Python</h3><p>You’ll want to move the emails that you want to parse from Outlook to a folder. The simplest method to do this is by dragging and dropping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCRWM0Z0awdApU-49sJR5Q.gif" /><figcaption>Demonstration of the drag-and-drop method</figcaption></figure><p>Next, create a variable storing the folder path of your emails. You can do this manually e.g. folder_path = r‘C:\Users\Username\EmailFolder’ or with tkinter and os, which will generate a file explorer prompt to select a folder.</p><pre># Create an folder input dialog with tkinter<br>folder_path = os.path.normpath(askdirectory(title=&#39;Select Folder&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*HvJTAiuAa7PlsBG2qHLlXQ.png" /><figcaption>Obtaining our folder path with tkinter</figcaption></figure><p>Here, we’re using a file input prompt created with tkinter to save our folder path, then normalizing the path with os to remove any redundant separators.</p><p>We’ll then want to obtain the path headings of each email. We can do this with os.listdir(), which gives a list of all files in the specified directory.</p><pre># Initialise &amp; populate list of emails<br>email_list = <br>[file for file in os.listdir(folder_path) if file.endswith(&quot;.msg&quot;)]</pre><p>This will save the file name of each email in list that we can access later.</p><h3>Connecting Outlook to Python</h3><p>Next, you’ll want to create an object that will allow us to control Outlook from Python. This is enabled through the pywin32 library that helps to connect Python to Outlook via the <strong>Microsoft</strong> <strong>Outlook Messaging API (MAPI)</strong>.</p><pre>outlook = win32com.client.Dispatch(&quot;Outlook.Application&quot;)<br>                  .GetNamespace(&quot;MAPI&quot;)</pre><p>With this, we can begin to open each item as a HTML object, and use <strong>regular expressions</strong> i.e. Regex to extract the body text of each email.</p><p>While conventional wisdom dictates that you shouldn’t use Regex to parse HTML, we’re not worried about this here, as we’re only looking to extract very specific text snippets out of a standard email format (Some commercial email parsers like <a href="https://parseur.com/blog/parsing-html-with-regular-expressions-for-fun-and-profit#top_post">Parseur</a> are heavily built around Regex).</p><p>From this point, Regex can be used to narrow down the specific data that you want to extract.</p><pre># Iterate through every email<br>for i, _ in enumerate(email_list):<br><br>   # Create variable storing info from current email being parsed<br>   msg = outlook.OpenSharedItem(os.path.join(folder_path,<br>   email_list[i]))<br><br>   # Search email HTML for body text<br>   regex = re.search(r&quot;&lt;body([\s\S]*)&lt;/body&gt;&quot;, msg.HTMLBody)<br>   body = regex.group()</pre><h3>Parsing Email HTML with Python</h3><p>This is how the first bullet point of our email might look as HTML:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbUhyCyqhHBpiQsvmbtaqw.png" /><figcaption>The HTML view of our email snippet</figcaption></figure><p>Okay — so we can see that there are several key characteristics here, namely that our data exists as a bulleted list or li class=MsoListParagraph. We can use Regex to extract each bullet point.</p><pre># Search email body text for unique entries<br>pattern = r&quot;li class=MsoListParagraph([\s\S]*?)&lt;/li&gt;&quot;<br>results = re.findall(pattern, body)</pre><p>Each bullet point is extracted as a string, and each string is stored in a list. Our first bullet point should look something like this with Regex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*eR63hnOLmTBdXFvosO2lLA.png" /><figcaption>Narrowing down our HTML body text with Regex (<a href="https://regex101.com/">Regex101.com</a>)</figcaption></figure><p>To retrieve our title and publication, we can use Regex again. This time, we’ll also use call html.unescape() on our text to help translate our HTML to string e.g. &amp;8211; → – (a unicode dash).</p><pre>regex = re.search(r&quot;[^&lt;&gt;]+(?=\(|sans-serif&#39;&gt;([\s\S]*?)&lt;/span&gt;)&quot;, header)<br><br># HTML unescape to get remove remaining HTML<br>title_pub = html.unescape(regex.group())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*9gPgWJBIPbI9Bq7WS4vE7w.png" /><figcaption>Our regex returns the highlighted text as the variable above</figcaption></figure><p>From here, it’s as simple as splitting our text. We can use split_list = title_pub.split(&quot;–&quot;) to give us a list: [&quot;New Arrival: Dell G Series Gaming Computers&quot;, &quot;Tech4tea&quot;].</p><p>We can then remove any redundant whitespaces and save each item as a variable.</p><pre>title = split_list[0].strip()<br>publication = split_list[1].strip()</pre><p>That’s two down!</p><p>To get our media platforms, we’ll use a more straightforward method.</p><pre># List of publications to check for<br>platform_list = [&quot;Online&quot;, &quot;Facebook&quot;, &quot;Instagram&quot;, &quot;Twitter&quot;, &quot;LinkedIn&quot;, &quot;Youtube&quot;]<br><br># Create empty list to store publications<br>platform = []<br><br># Iterate and check for each item in my first list<br>for p in platform_list:<br>   if p in header:<br>      platform.append(p)</pre><p>This will give us a list of publications: [&quot;Online&quot;, &quot;Facebook&quot;, &quot;LinkedIn&quot;]</p><p>Now for the URLs:</p><pre># Find all links using regex<br>links = re.findall(r&quot;&lt;a href=\&quot;([\s\S]*?)\&quot;&gt;&quot;, header)</pre><p>This will then give us the characters highlighted in green below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*kXMsVhvy94GqskPkUTIEhg.png" /><figcaption>Pretty neat, right?</figcaption></figure><p>Our data so far should look something like this:</p><pre>Title: New Arrival: Dell G Series Gaming Computers<br>Publication: Tech4tea<br>Platform: [‘Online’, ‘Facebook’, ‘LinkedIn’]<br>Links: [‘<a href="http://tech4tea.com/blog/2020/06/26/new-arrival-dell-g-series-gaming-computers-monitors-keyboards/&#39;">http://tech4tea.com/blog/2020/06/26/new-arrival-dell-g-series-gaming-computers-monitors-keyboards/&#39;</a>, ‘<a href="https://business.facebook.com/gotech4tea/posts/4598490146843826&#39;">https://business.facebook.com/gotech4tea/posts/4598490146843826&#39;</a>, ‘<a href="https://www.linkedin.com/feed/update/urn:li:activity:6682511823100542976/&#39;">https://www.linkedin.com/feed/update/urn:li:activity:6682511823100542976/&#39;</a>]</pre><h3>Uploading data to a SQL database</h3><p>The final step in this process is to upload each piece of data to our SQL database.</p><p>We’ll start by uploading our title and publication data. This can be accomplished with the following code:</p><pre># Insert title &amp; pub by substituting values into each ? placeholder<br>db.execute(&quot;INSERT INTO articles (title, publication) <br>VALUES (?, ?)&quot;, (title, publication))</pre><p>Uploading our links and platforms are a bit more tricky. First, we’ll copy over our primary id from our main table, then iterate over each platform and link individually.</p><pre># Get article id and copy to platforms &amp; links tables<br>article_id = db.execute(&quot;SELECT id FROM articles WHERE title = ?&quot;, (title,))<br><br>for item in article_id:<br>   _id = item[0]<br><br>for i, _ in enumerate(platform):<br>   db.execute(f&quot;UPDATE platforms SET platform{i} = ? WHERE    <br>   article_id = ?&quot;, (platform[i], _id))<br><br>for i, _ in enumerate(links):<br>   db.execute(f&quot;UPDATE links SET link{i} = ? WHERE article_id = ?&quot;, <br>   (links[i], _id))<br><br>db.commit()</pre><p>The last step here is to commit all these changes to the database. With that done, our email parser is complete! If you’d like, you can use something like <a href="https://sqlitebrowser.org/">DB Browser</a> to check that the contents of your database have been successfully updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6W49igJE7i6DxDNDePtVug.gif" /><figcaption>Viewing database with DB Browser</figcaption></figure><p>In case you need it, I’ve uploaded the full code for this on my <a href="https://www.benjamindornel.com/projects/email_parser.html">website</a> and <a href="https://github.com/benjamin-awd/OutlookParser50/blob/main/Demo/s_parser.py">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c79cb8771dac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-an-email-parser-with-python-and-sql-c79cb8771dac">Creating an Email Parser with Python and SQL</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Launch Jupyter Notebook Quickly]]></title>
            <link>https://medium.com/data-science/how-to-launch-jupyter-notebook-quickly-26e500ad4560?source=rss-351e34669aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/26e500ad4560</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[windows-10]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Benjamin Dornel]]></dc:creator>
            <pubDate>Thu, 10 Dec 2020 04:29:20 GMT</pubDate>
            <atom:updated>2020-12-10T04:29:20.332Z</atom:updated>
            <content:encoded><![CDATA[<h4>Speed up your workflow with File Explorer &amp; PowerShell aliases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vmh7EN4IkzkJ_l3V.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mattyfours">Matthew Fournier</a> on <a href="https://unsplash.com/photos/5NM32v14n6M">Unsplash</a></figcaption></figure><p>Jupyter Notebook is a great tool for data science but can be pretty slow if you constantly need to navigate through multiple directories before launching a notebook file, or if you’re using a clunky GUI like Anaconda Navigator to get to your files.</p><p>Today, I’ll be covering how to use Windows File Explorer, Command Prompt and PowerShell via Windows Terminal to quickly navigate to your directory of choice and launch Jupyter Notebook. (If you’re using MacOS, you can look into setting up an <a href="https://github.com/JunsW/FastJN">automator script</a> or <a href="https://medium.com/@messiest/making-life-easier-through-editing-your-bash-profile-746a85d9ea91">bash alias</a>).</p><p>Here are two ways that you can drastically cut down on time wasted navigating through folders and files.</p><h3>1. Windows File Explorer + Command Prompt</h3><p>Whenever you open a Windows Explorer folder, you’ll see an address bar similar to that in a web browser. By default, it shows the path of the current folder. In this address bar, you can enter in text and navigate to other directories manually.</p><p>Once you’ve entered your specific folder with Windows Explorer, you can simply press ALT + D, type in cmd and press Enter. You can then type jupyter notebook to launch Jupyter Notebook within that specific folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5l8imTsZnIvqFDk4.gif" /><figcaption>Launching Jupyter Notebook with File Explorer and Command Prompt</figcaption></figure><p>NOTE: If you’re using Anaconda, you may have to type activate conda to switch to Anaconda Prompt within Command Prompt. Additionally, if you receive an error involving zqm.h, you’ll need to add the following folders to your PATH environment variable:</p><ul><li>C:\Users\***\Anaconda3\Lib\site-packages\zmq</li><li>C:\Users\***\Anaconda3\Library\bin</li></ul><h3>2. Windows Terminal + PowerShell Aliases</h3><p>This method is slightly more complicated but is much faster and much more versatile. In this section, I’ll explain how to use Windows Terminal to access PowerShell and set up custom aliases.</p><p>Let me unpack that last sentence a bit:</p><ul><li><strong>Windows Terminal</strong> is basically a modern terminal application that allows us to use command-line tools and shells like Command Prompt. Some key features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to customize text, colors, backgrounds, and shortcuts. A guide to set this up with Anaconda Prompt can be found <a href="https://dev.to/azure/easily-add-anaconda-prompt-in-windows-terminal-to-make-life-better-3p6j">here</a>.</li><li><strong>PowerShell</strong> is a command-line tool like Command Prompt, except that it gives us the ability to do in-depth system management among several other handy abilities.</li><li>An <strong>alias</strong> is basically a console command shortcut. For example, instead of typing out Set-Location in PowerShell, you can type cd or chdir to change directories quickly.</li></ul><p>PowerShell allows you to create custom aliases, which is what we’ll do here. With a custom alias, you can launch Jupyter Notebook by simply typing jn instead of jupyter notebook. You can also navigate to directories with this. For example, I can type cdp3 instead of something like cd C:\Users\***\OneDrive\Desktop\General Assembly\Project3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*05AjECDQO0J49Oce.gif" /><figcaption>Launching Jupyter Notebook with Windows Terminal and PowerShell Aliases</figcaption></figure><p>To set this up, you’ll first need to install Windows Terminal. This step is optional, but I prefer using Windows Terminal over stand-alone PowerShell due to the functionality that it offers (Windows Terminal is also much better looking). A guide to set this up with Anaconda Prompt can be found <a href="https://dev.to/azure/easily-add-anaconda-prompt-in-windows-terminal-to-make-life-better-3p6j">here</a>.</p><p>Next, you’ll want to create a PowerShell profile. This is where we’ll be storing our shortcut commands, which are more formally known as ‘<strong>aliases</strong>’. To create a profile, launch PowerShell and enter the following command: New-Item -Type File -Force $PROFILE. This will create a profile within your UserProfile\Documents folder. You can check the path of your profile by typing $PROFILE in PowerShell.</p><p>You can then open this file with PowerShell by typing ise $PROFILE or by manually opening this file with your preferred code editor.</p><p>You’ll first want to create a shortcut to your most frequently used directory such as:</p><pre>function Get-GeneralAssemblyProjects<br>{ &amp; cd ‘~\OneDrive\Desktop\General Assembly\Project3’ }<br>New-Alias -Name cdp3 -Value Get-GeneralAssemblyProjects</pre><p>From there, you’ll want to add something like the following to your PowerShell profile:</p><pre>function Start-JupyterNotebook { &amp; $ENV:UserProfile\Anaconda3\python.exe $ENV:UserProfile\Anaconda3\cwp.py <br>$ENV:UserProfile\Anaconda3 $ENV:UserProfile\Anaconda3\python.exe <br>$ENV:UserProfile\Anaconda3\Scripts\jupyter-notebook-script.py $pwd}<br>New-Alias -Name jn -Value Start-JupyterNotebook</pre><p>This will allow you to start Jupyter Notebook by typing jn. You can change this alias to anything else, like &gt;j and so on.</p><p>To launch Windows Terminal, you can use Win + R and type wt.</p><p>There are tons more you can do with aliases, such as setting custom Git commands like the following:</p><pre>function Get-GitStatus { &amp; git status $args }<br>New-Alias -Name gs -Value Get-GitStatus</pre><p>The possibilities are pretty endless with aliases.</p><p>Hope this helps you out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26e500ad4560" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-launch-jupyter-notebook-quickly-26e500ad4560">How to Launch Jupyter Notebook Quickly</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>