<?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 Ioannis Petrousov on Medium]]></title>
        <description><![CDATA[Stories by Ioannis Petrousov on Medium]]></description>
        <link>https://medium.com/@petrousoft?source=rss-ec18b2815c05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vIZRXOtjk81R3RLps-_lhQ.png</url>
            <title>Stories by Ioannis Petrousov on Medium</title>
            <link>https://medium.com/@petrousoft?source=rss-ec18b2815c05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:47:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petrousoft/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[Migrating My dotfiles to an Agentic Setup]]></title>
            <link>https://medium.com/@petrousoft/migrating-my-dotfiles-to-an-agentic-setup-de3e8171d70c?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/de3e8171d70c</guid>
            <category><![CDATA[agentic-development]]></category>
            <category><![CDATA[dotfiles]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 19:49:36 GMT</pubDate>
            <atom:updated>2026-11-05T19:49:36.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I0qJ_X6DlVZK2jEN" /><figcaption>Photo by <a href="https://unsplash.com/@zulfugarkarimov?utm_source=medium&amp;utm_medium=referral">Zulfugar Karimov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a> supposedly matches dotfiles.</figcaption></figure><p>Like many developers, I spent years managing my system configuration using a bare Git repository rooted in $HOME. It is a simple and elegant trick in which you alias git to point to a .mydot directory, set --work-tree=$HOME, turn off untracked files in status reports, and commit directly from your home folder. For a solo engineer working manually in the terminal, it works reliably with zero dependencies.</p><p>Recently I started integrating AI coding agents into my terminal workflows and came up with a simple approach to have my dotfiles developed for me by an LLM powered agent. I have spent my fair share of time studying other people’s approach to dotfile management, borrowing things from here and there, RTFM-ing documents and writing Lua code. So, after 264 commits, I decided to outsource my dotfile development to LLM agents.</p><p>In this post, I will share how I restructured my dotfiles to be safe and modular for AI-assisted development, and how the automation pipeline works.</p><h3>The New Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPI26b8u54mB79EJ1Z7KFw.png" /><figcaption>From left column to righ: repository of dotfiles, symlink engine (GNU stow), dotfile targets.</figcaption></figure><p>The updated setup centers on three components:</p><ul><li><strong>A Dedicated Workspace</strong> (~/dev/mydot): An isolated Git repository where both human and agent work. The agent only has access to this folder and its subdirectories.</li><li><strong>GNU Stow for Symlink Management</strong>: Each application (such as Neovim, Sway, Alacritty, or Zsh) is organized into its own self-contained directory tree that mirrors the target structure under $HOME. Stow takes care of creating and folding the symlinks atomically — it’s beautiful!</li><li><strong>manifest.json as a Declarative Source of Truth</strong>: A single JSON document that records which configuration packages exist and which paths belong to them. This provides structured context that any agent can read and understand immediately. More importantly, I know what’s being tracked.</li></ul><p>Edits inside ~/dev/mydot are immediately reflect in $HOME through symlinks and changes can be tested immediately.</p><h3>Automating the Migration: The mydot Lifecycle</h3><pre>./mydot.py -h<br>usage: mydot.py [-h] {discover,stage,simulate,deploy,restore}<br><br>AI-native Dotfile Manager<br><br>positional arguments:<br>  {discover,stage,simulate,deploy,restore}<br>                        Action to perform<br><br>options:<br>  -h, --help            show this help message and exit</pre><p>To automate the migration, I co-authored (which is a lie because it was mostly written by the LLM) a Python program (mydot.py) that implements a multi-step lifecycle:</p><h4>Interactive Discovery (discover)</h4><p>This phase inspects the host system for known baseline tools (nvim, sway, alacritty, zsh, git, and gh). To pick up additional personal utilities and configs, it scans ~/.config and $HOME, filters out system and application noise (like browser profiles and cache directories), and launches an interactive fuzzy selector (fzf).</p><p>Once selected, the target paths are mapped to package names and written to manifest.json.</p><h4>Staging and Secret Scrubbing (stage)</h4><p>Using the manifest as its guide, the staging step copies candidate configurations from their actual locations into the repo.</p><p>This step acts as a security filter. It scrubs my known transient tokens and generates a .gitignore to exclude those secrets.</p><h4>Simulation (simulate)</h4><p>Before modifying any actual config on the system, the simulation phase executes a dry run using GNU Stow’s native simulation flags. This prints the exact symlinks Stow intends to create and highlights any conflicting files that already exist in the target directories.</p><h4>Deployment and Automated Backups (deploy)</h4><p>The script generates a timestamped backup directory in $HOME (e.g., ~/.dotfiles_backup_YYYYMMDD_HHMMSS). Moves original configurations into the backup folder, preserving their relative directory paths. Runs Stow to link each package from the repository into $HOME.</p><p>At this point, the system is fully operating on symlinks pointing back to the repository.</p><h4>The Safety Net: Rollback (restore)</h4><p>If anything behaves unexpectedly, the restore action provides an instant rollback. It automatically finds the latest backup directory, tears down the active Stow symlinks, and recursively restores the original files back to their exact locations in $HOME.</p><h3>What Co-Authoring with AI Looks Like in Practice</h3><p>With this structure in place, the development can now become agentic and controlled:</p><p><strong>Scoped Context</strong>: When I need to refine a configuration, whether that is adjusting Neo-tree visibility rules or updating Pyright language server virtualenv detection, I open the agent directly in the repo (~/dev/mydot). The agent sees only configuration files and version history, with zero exposure to personal documents or credentials.</p><p><strong>Immediate Feedback</strong>: Because live files are symlinked to the repo, any edit the agent makes takes effect instantly. I can reload the application, verify the behavior, and request adjustments without switching contexts.</p><h3>Conclusion</h3><p>Asking the agent to simply configure my nvim setup to do what I want it to do saves me valuable time. Instead of reading documents, code and fighting dependencies, I just send a send a request and the agent makes it its goal.</p><p>If you are exploring agentic workflows for your own development environment, prioritizing workspace boundaries and automated backups will save you a lot of headaches.</p><p>You can find my setup online: <a href="https://github.com/gpetrousov/mydot">github.com/gpetrousov/mydot</a>.</p><p>I’m curious to know how you’re adapting your dotfiles and developer environment for AI tooling? Feel free to leave your thoughts in the responses below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de3e8171d70c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the case of an AI compliance video auditor]]></title>
            <link>https://medium.com/@petrousoft/exploring-the-case-of-an-ai-compliance-video-auditor-c14ceae51f66?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/c14ceae51f66</guid>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 18:29:16 GMT</pubDate>
            <atom:updated>2026-09-29T18:29:16.481Z</atom:updated>
            <content:encoded><![CDATA[<p>There are numerous examples of real world environments which require constant monitoring for regulation compliance. Construction sites, for example, require employees to wear safety vests and protective hats. Maritime operations have strict rules for personnel when operating in certain environments, such as on the deck of a ship. Such workplace regulations evolve and require constant adaption of the monitoring personnel or systems.</p><p>Traditional computer vision approaches struggle with this rapid rate of change. Standard object detection pipelines require annotating hundreds of images, modifying neural network heads, and running expensive retraining cycles for every new rule.</p><p>To solve this operational bottleneck, I built a zero-shot video auditor. The system translates natural language safety policies directly into real-time surveillance search queries without requiring any fine-tuning or custom dataset labeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*fYleAmgh0jYyZRR5mlIkXQ.png" /><figcaption>A snapshot of the system running on Hugging Face.</figcaption></figure><h4>The System Architecture</h4><pre>[Raw Surveillance Video] <br>       │ (OpenCV Temporal Downsampling)<br>       ▼<br> [Extracted Frames] <br>       │ (Open-CLIP ViT-B-32 Image Encoder)<br>       ▼<br> [512-d Visual Vectors] ──────► [In-Memory ChromaDB Collection]<br>                                              ▲<br> [Natural Language Policy]                    │ (Squared Euclidean Search)<br>       │                                      │<br>       ▼ (Open-CLIP Text Encoder)             │<br> [512-d Text Vector] ─────────────────────────┘</pre><p>The system executes in four sequential stages:</p><ul><li><strong>Frame Extraction:</strong> An OpenCV ingestion worker samples video streams at regular time intervals.</li><li><strong>Multi-Modal Embedding:</strong> Each sampled frame passes through an Open-CLIP Vision Transformer (ViT-B-32), producing a normalized 512-dimensional embedding vector.</li><li><strong>Vector Indexing:</strong> The visual vectors are stored inside an in-memory ChromaDB collection alongside their source video timestamps.</li><li><strong>Semantic Querying:</strong> When a user types a safety rule violation in plain English, the text is encoded into the same 512-dimensional space to perform an immediate nearest-neighbor search.</li></ul><h4>Verifying Model Decisions with Visual Heatmaps</h4><p>One major challenge with multi-modal retrieval is interpretability. If the model flags a video frame at timestamp 14.5s for the query <em>“person operating a yellow construction machine”</em>, we need to verify why the model chose that frame.</p><p>To solve this, I implemented a patch-based occlusion attribution engine directly in Python.</p><p>The algorithm divides the retrieved frame into a grid of local patches, passes each crop through the CLIP vision encoder, and calculates the cosine similarity against the text query. Resizing this similarity matrix produces a visual heatmap over the original frame.</p><p>This highlights the exact regions driving the match (such as the machine chassis and the operator cabin) while ignoring irrelevant background elements.</p><h3>Other Use Cases</h3><p>The pipeline is fundamentally an open-vocabulary text-to-image retrieval engine. Because it does not rely on hardcoded safety classes, the same architecture can be deployed across several completely different industries either with zero retraining, or fine-tuned.</p><ul><li><strong>Digital Asset Retrieval:</strong> Media companies and content creators with massive unindexed video libraries can query their archives using natural descriptions of scenes or actions rather than relying on manual tagging.</li><li><strong>Smart City Traffic and Public Infrastructure:</strong> Municipal teams can search traffic camera streams for specific vehicle types, monitor lane blockages, or detect anomalies like road debris and flooding without configuring dedicated roadside sensor models.</li></ul><p>By switching the query from safety rules to business-specific phrases, the system transforms raw video archives into searchable visual databases across any domain.</p><h3>Summary &amp; Deliverables</h3><p>The goal of this project was to explore how an AI system could be used in the context of compliance and regulation combining text and computer vision into a multimodal AI system capable of querying raw video footage for specific semantic events.</p><p>The research prioritized building an end-to-end working proof of concept (PoC). The system implements the complete indexing pipeline, verifies zero-shot retrieval mechanics, and introduces a patch-based attribution engine to explain model predictions visually.</p><p>The entire workflow is packaged into an interactive Gradio application deployed live on Hugging Face Spaces. You can upload an MP4 video clip, test arbitrary natural language queries, and inspect the resulting retrieval frames alongside their spatial attribution heatmaps in real time.</p><ul><li><strong>Live Demo:</strong> <a href="https://videotti.petrousoft.com/">https://videotti.petrousoft.com/</a></li><li><strong>Source and notebooks: </strong><a href="http://github.com/gpetrousov/multimodal_ai_assignment_demokritos/">github</a></li><li><strong>Technical Report: PDf </strong><a href="https://github.com/gpetrousov/multimodal_ai_assignment_demokritos/">github</a></li><li><strong>Presentation Slides: </strong><a href="https://docs.google.com/presentation/d/1DW28UWfK28nR-G_rB0mqrZmNZY3uNZMmDJpCxxdA-fk/edit?usp=sharing">docs</a></li></ul><h3>References</h3><ul><li><a href="https://puc.overheid.nl/nsi/doc/PUC_80377_14/6/">https://puc.overheid.nl/nsi/doc/PUC_80377_14/6/</a></li><li><a href="https://osha-safety-training.net/blogs/news/comprehensive-guide-to-maritime-osha-standards-and-regulations-for-business-safety-compliance-managers">https://osha-safety-training.net/blogs/news/comprehensive-guide-to-maritime-osha-standards-and-regulations-for-business-safety-compliance-managers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c14ceae51f66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning models with Supervised Contrastive Learning (SupCon)]]></title>
            <link>https://medium.com/@petrousoft/fine-tuning-models-with-supervised-contrastive-learning-supcon-6b5fc8d03951?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b5fc8d03951</guid>
            <category><![CDATA[supcon]]></category>
            <category><![CDATA[contrastive-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[emotion-recognition]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 19:51:35 GMT</pubDate>
            <atom:updated>2026-09-01T19:51:35.096Z</atom:updated>
            <content:encoded><![CDATA[<p>Speech Emotion Recognition (SER) is a notoriously difficult challenge. When working with small datasets like RAVDESS (roughly 1200 training samples), standard deep learning architectures tend to cheat. Instead of learning generalized emotional features, they take the path of least resistance, by memorizing the specific pitch, timbre, and cadence of the individual actors.</p><p>This happens because standard Cross-Entropy (CE) loss heavily penalizes point-wise misclassifications, forcing the model to exploit any available acoustic artifact to separate classes. The result is a fragile model that underperforms when exposed to unseen speakers or real-world background noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*190z4UhnOvrNl5t7gekv0A.png" /><figcaption>Demo hosted on Hugging Face.</figcaption></figure><h4>The Contrastive Learning Pipeline</h4><p>To address this, we can abandon direct CE classification and transition to <strong>Supervised Contrastive Learning (SupCon)</strong>. Instead of forcing a hard label prediction, SupCon <strong>optimizes a latent space</strong> by mathematically <strong>pulling similar emotions together into tight clusters</strong> while <strong>pushing differing emotions apart</strong>, see <a href="https://arxiv.org/pdf/2004.11362">https://arxiv.org/pdf/2004.11362</a>.</p><pre>LATENT SPACE GEOMETRY (SupCon)<br>   <br>        [Car]                [Dog]<br>       Sample C             Sample B<br>          ▲                    ▲<br>          └─── ◄── PUSH ──► ───┘<br>                 │        │<br>                 ▼        ▼<br>             • A1  ◄─PULL─►  • A2<br>                [Cat Cluster]</pre><p>In this research, the training pipeline processes 1D audio as 2D Mel-Spectrograms (treating sound like an image) and utilizes a three-stage approach:</p><ul><li><strong>Contrastive Clustering:</strong> We apply SpecAugment to randomly mask blocks of time and frequency in the audio. By feeding two differently masked versions of the same file into a custom CNN, the model is forced to ignore the distortions and map both views to the exact same spatial coordinate.</li><li><strong>Linear Probing:</strong> The CNN encoder is frozen, and a linear classifier is attached to prove the clusters are linearly separable.</li><li><strong>End-to-End Fine-Tuning:</strong> The entire network is unfrozen with differential learning rates to carefully bind the feature extractor to the classifier without destroying the learned clusters.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*9lcfu1xisZhT1QpvAWZTuQ.png" /><figcaption>Summary of the model training pipeline.</figcaption></figure><h4>Results and the Noise Stress Test</h4><p>To prove the core hypothesis, we benchmarked the SupCon architecture against a standard CE Baseline and a heavyweight ResNet18.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*foCfprY-Zk2nksjCBB3dww.png" /><figcaption>Noise robustness across tested models.</figcaption></figure><ul><li><strong>Clean Accuracy:</strong> The SupCon pipeline successfully boosted test accuracy from the baseline’s 53% to 60%, proving that contrastive pre-training yields superior feature separation.</li><li><strong>Acoustic Resilience:</strong> When injected with extreme Gaussian noise (0.5 Standard Deviation), the baseline CNN completely collapsed to 13% accuracy (random guessing). In contrast, the SupCon representations degraded much slower, maintaining higher stability.</li></ul><p>By shifting the focus from label prediction to robust representation learning, we can effectively deploy resilient audio models even in noisy, unpredictable environments.</p><h3>Summary &amp; Deliverables</h3><p>The primary goal of this research was to move beyond standard Cross-Entropy loss and experiment with architectural interventions to improve a model’s predictive performance and stability.</p><p>The empirical results demonstrate that the lightweight, fine-tuned SupCon CNN outperformed the standard CNN baseline, achieving higher overall accuracy on clean audio (60% versus 53%). Furthermore, when subjected to the Gaussian noise stress test, the SupCon architecture demonstrated a significantly slower degradation rate, proving its increased robustness under noisy conditions.</p><p>However, working with the clean but limited RAVDESS dataset highlighted a fundamental reality of deep learning. While techniques like contrastive pre-training can maximize the utility of small datasets and improve noise tolerance, dataset scale and diversity remain the ultimate factors in building highly accurate, production-ready models.</p><ul><li><strong>Live demo:</strong> <a href="https://sersupcon.petrousoft.com/">https://sersupcon.petrousoft.com/</a></li><li><strong>Full source code &amp; Research notebooks:</strong> <a href="https://github.com/gpetrousov/dl_assignment_demokritos/tree/master">github</a></li><li><strong>Presentation:</strong> <a href="https://docs.google.com/presentation/d/1ShSmXY2OqCEbQQjYiLYCFc8Psu2bioECoFHhliiDEiQ/edit?slide=id.gc6f75fceb_0_0#slide=id.gc6f75fceb_0_0">docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b5fc8d03951" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pushing ML algorithms to their limits: Building a surgical image classifier using multi-modal…]]></title>
            <link>https://medium.com/@petrousoft/pushing-ml-algorithms-to-their-limits-building-a-surgical-image-classifier-using-multi-modal-ebbf7b095bbc?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebbf7b095bbc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[farming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 15:04:43 GMT</pubDate>
            <atom:updated>2026-08-27T15:04:43.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pushing ML algorithms to their limits: Building a surgical image classifier using multi-modal feature fusion</h3><p>In agricultural computer vision, deep learning architectures often dominate the conversation. However, the primary purpose of this research was to pragmatically explore the limits of classical statistical machine learning, without relying on neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U8pgzFlXX5RZttMf-d6sbQ.png" /><figcaption>Snapshot of the developed classifier model available online.</figcaption></figure><p>The challenge was to classify weeds among commercial crops under a very specific set of rules. In the real world, errors carry different costs. If the model misclassifies a weed as a crop (a false positive), the weed survives and slightly reduces the overall yield. But if it misclassifies a crop as a weed (a false negative), the autonomous weeding tool destroys a healthy seedling. That directly hurts the farmer’s return of investment (ROI).</p><p>To solve this, I designed a pipeline that fuses multiple visual features and strictly optimizes the decision threshold. The absolute requirement was to hit a 91% or higher crop recall rate. Here is a look at how I approached the research and what the evaluations showed.</p><p>(Note: All implementation logic, preprocessing scripts, and evaluation notebooks are available in the linked GitHub repository).</p><h3>1. Feature Engineering: Multi-Modal Fusion Without Deep Nets</h3><p>Instead of leaning on resource-heavy Convolutional Neural Networks that need GPUs to run, I focused on extracting deterministic, hand-crafted visual features. This approach guarantees low latency, keeps the model highly interpretable, and sets a strong baseline for what statistical models can actually achieve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*jHcvhSkntwRB4YUnT3UqqA.png" /></figure><p>The pipeline combines three different ways of looking at an image. First, Histogram of Oriented Gradients (HOG) captures the physical shape and edges of the plants. Second, Local Binary Patterns (LBP) picks up on the surface textures. Finally, HSV Color Histograms help separate the different shades of green and brown, which makes the model more robust to shadows and changing lighting conditions in the dirt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJpzoCxnFvNjtO2KdQ788Q.png" /><figcaption>Sample of leaf shape extraction from image using filters on the HSV channels.</figcaption></figure><p>Raw HOG features create a massive amount of data that can easily overwhelm a statistical model, so I used Principal Component Analysis (PCA) to shrink the dataset. By plotting the cumulative variance, I found the optimal sweet spot. Retaining just the top 800 components successfully captures 90% of the original structural information while drastically reducing the data size, making it much easier for the classifier to handle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Y8GStxY3pl77XBuj5gUFRA.png" /><figcaption>PCA scree plot.</figcaption></figure><h3>2. Benchmark Evaluation &amp; Model Optimization</h3><p>To find the absolute ceiling of what classical methods can do, I tested several different classifier families using the exact same training and test datasets using Pycaret. The top three performing algorithms from my exploration were <strong>Random Forests</strong>, <strong>Complement Naive Bayes</strong>, and <strong>Support Vector Machines</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yur0ztQ29jqj_TcafCG1-w.png" /></figure><p>The best results ultimately came from a Radial Basis Function (RBF) SVM. By mapping the combined features into a more complex mathematical space, the SVM was able to find a clean boundary between the crops and the weeds. I also applied a balanced class weight parameter. This automatically adjusted the model’s penalties based on how often each class appeared, which stopped it from unfairly favoring the most common class.</p><h3>3. Decision-Threshold Tuning: The “Surgical” Operating Point</h3><p>Out of the box, standard classification models use a simple 50/50 probability split for their decision threshold. If the model is more than 50% sure an image is a weed, it calls it a weed. In an automated farming environment, that default logic leads to unacceptable crop loss.</p><p>To meet the safety rules of this project, I used Precision-Recall Curve analysis on the validation data. By testing different decision thresholds, I bypassed the default logic to find the exact operating point that guaranteed at least a 91% recall for the crop class. This custom threshold dynamically overrides the standard predictions. It forces the model to operate surgically, prioritizing crop safety over raw, overall accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aui3zh-2x0d9QjPiPVnC5w.png" /><figcaption>SVM Confusion Matrix and PR curve optimization.</figcaption></figure><p>The jagged PR curve on the right hand side clearly shows the severe imbalance of the dataset I worked with.</p><h3>4. Interactive Demo</h3><p>An interactive demo of this research is available online. I packaged the trained SVM, the Scaler, and the PCA components into a web application.</p><p>The demo uses the exact same steps developed in my research notebooks. You can upload a single image and watch the optimized threshold logic make its decision in real time.</p><h3>Summary &amp; Deliverables</h3><p>This project was a great way to map out the practical limits of statistical machine learning. It shows that if you combine smart feature engineering with deliberate threshold tuning, you can solve high-stakes classification problems without needing the massive computing power or the opaque nature of deep learning.</p><p>However, the pure nature of the problem mandates the eventual implementation of artificial neural networks and a continuous adaptation to the weeds and crops growing on the specific field.</p><ul><li><strong>Live Demo:</strong> <a href="http://autofarm.petrousoft.com/">https://autofarm.petrousoft.com</a></li><li><strong>Full Source Code &amp; Research Notebooks:</strong> <a href="https://github.com/gpetrousov/ml_assignment_demokritos">GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebbf7b095bbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bootstrapping ML environments with uv]]></title>
            <link>https://medium.com/@petrousoft/bootstrapping-ml-environments-with-uv-72e111bbae78?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/72e111bbae78</guid>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[package-management]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[uv]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 08:50:32 GMT</pubDate>
            <atom:updated>2026-08-26T08:50:32.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I came across an article showcasing how <a href="https://medium.com/@sohail_saifi/uv-is-replacing-pip-virtualenv-conda-and-pyenv-all-at-once-11386f27f2da">uv is replacing pip, virtualenv, conda, and pyenv all at once</a>. I have been considering researching a consolidated workflow to set up my Machine Learning (ML) environments, including Jupyter notebooks, so decided to give uv a try.</p><p>The aforementioned article presents several migration scenarios but it skips the use case in which you need to install a specific version of PyTorch and CUDA matching your hardware drivers. Here, I showcase how I bootstrap my ML environments with custom version for torch ,torchvision and torchaudiousing uv .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ckgQ0VtFyXF-Sf368NuQA.jpeg" /><figcaption>Image from the author.</figcaption></figure><h3>The Frankenstack</h3><p>Until recently, my usual workflow for creating isolated Python environments consisted of the following steps:</p><ol><li>use pyenv to install a specific version of Python.</li><li>Use pip to install Conda.</li><li>Use conda to install packages, like PyTorch, which require C++ system libraries</li><li>Fall back to pip for everything else.</li></ol><p>I developed into this multi-tool workflow because it centralizes my entire environment ecosystem under $HOME/.pyenv/versions. By provisioning Miniconda through pyenv, both Conda binaries and pip-installed wheels resolved into isolated subdirectories without contaminating my system-level Python.</p><pre># Verify where your packages live<br>python -c &quot;import site; print(site.getsitepackages())&quot;<br># OR<br>pip show torch</pre><p>In this setup I had to maintain 2 separate dependencies files, one for pip and one for conda. An example of such setup <a href="https://github.com/gpetrousov/ml_assignment_demokritos/tree/published">lives on my ML project</a>.</p><pre>├── notebooks/<br>│   ├── 00_baseline.ipynb<br>│   └── 01_report.ipynb<br>├── weedcrop/                   # Module Source package<br>│   ├── autofarm.py             # Core library logic (Extraction, Training, Eval)<br>│   └── ...<br>├── requirements.txt            # Pip dependencies<br>├── environment.yml             # Conda dependencies<br>└── README.md                   # Repository documentation</pre><p>This setup works well if you control every piece of the stack, understand the ins-and-outs of the tools, and know how they all tie together. However, the <a href="https://www.reddit.com/r/startups/comments/1le7nth/is_your_dev_workflow_a_frankenstein_stack_too_i/">tech industry</a> refers to this setup as <a href="https://www.shopify.com/enterprise/blog/frankenstack">a “Frankenstack”</a>. It relies heavily on the granular knowledge of the developer to provision the environment properly and to juggle two separate dependency files (requirements.txt and environment.yml).</p><h3>A Fast &amp; Portable Alternative</h3><p>While my old setup gave me total control and clean directory isolation, maintaining multiple configuration files always added unwanted friction, especially when I needed to install new packages. That is where uv caught my attention. Instead of piecing together three separate utilities for Python runtimes, large binary packages, and lockfiles, uv consolidates those responsibilities into a single workflow without sacrificing the environment isolation I rely on.</p><p>PyTorch distributes its CUDA dependencies via standard wheels hosted on their own index. From the developer’s side, you need to have a hardware driver compatible with that version, <a href="https://discuss.pytorch.org/t/system-cuda-version-vs-torch-wheel-cuda-version/157756">follow the conversation on the forums</a>.</p><p>uv allows us to configure the PyTorch download source directly in a pyproject.toml file. Setting an explicit index prevents uv from searching this specific CUDA index for unrelated packages.</p><h4>The Setup Script</h4><p>The following script generates a dependency tracking file (pyproject.toml), forces uv to pull a specific CUDA 12.4 index for PyTorch and installs everything in the new project environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b3725d5c43df48f9c80f0c5132ce36a/href">https://medium.com/media/3b3725d5c43df48f9c80f0c5132ce36a/href</a></iframe><h4>Why This is Better</h4><p>When you run this script, uv automatically downloads Python 3.11.4 if you don&#39;t have it, fetches the CUDA wheels, and generates a uv.lock file.</p><p>If you need to reproduce this environment on another machine, or in a CI pipeline, you only need the pyproject.toml and uv.lock files. A single command reproduces the exact environment in a few seconds:</p><pre>uv sync</pre><p>The <a href="https://docs.astral.sh/uv/guides/integration/pytorch/#using-a-pytorch-index">documentation</a> mentions how to setup a custom index to pull PyTorch from.</p><h3>Final Thoughts</h3><p>This setup is much faster and more efficient than what I’ve used previously for tracking environment dependencies. I haven’t found any caveats yet, but time will tell.</p><p>Going forward, I plan to optimize the bootstrap script for my existing PyTorch projects using this exact method. You can check out where I’ll be applying it next in my <a href="https://github.com/gpetrousov/multimodal_ai_assignment_demokritos">Safety Auditor RAG system</a> and <a href="https://github.com/gpetrousov/dl_assignment_demokritos">Speech Emotion Recognition (SER) setup</a>.</p><p>If you’re interested in knowing more about the mechanics of uv, I highly recommend the <a href="https://www.youtube.com/watch?v=gSKTfG1GXYQ">presentation from Charlie Marsh</a>.</p><p><em>“Found this helpful? Connect with me on </em><a href="http://medium.com/@petrousoft"><em>Medium</em></a><em>, </em><a href="https://www.linkedin.com/in/ioannispetrousov/"><em>LinkedIn</em></a><em> or check out my </em><a href="https://github.com/gpetrousov"><em>GitHub</em></a><em> for more practical ML workflows and deep-dive projects.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72e111bbae78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A complete guide to Principal Component Analysis — PCA]]></title>
            <link>https://medium.com/@petrousoft/a-complete-guide-to-principal-component-analysis-pca-d3da31350d01?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3da31350d01</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 09:43:43 GMT</pubDate>
            <atom:updated>2025-11-21T09:43:43.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>A complete guide to Principal Component Analysis — PCA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*kHz9f_Ir9WP2QNYP9mpiJA.png" /><figcaption>Scree plot. Photo by the author.</figcaption></figure><p>As mentioned in my previous post, I started a cutting-edge MSc program in AI at the research center Demokritos. Read all about my decision here: <a href="https://medium.com/@petrousoft/i-rejected-an-ai-msc-from-a-top-university-heres-what-i-chose-instead-10575cfadcd6">https://medium.com/@petrousoft/i-rejected-an-ai-msc-from-a-top-university-heres-what-i-chose-instead-10575cfadcd6</a></p><p>My first assignment for the preparatory course, <a href="https://msc-ai.iit.demokritos.gr/en/classes/fundamentals-and-background-artificial-intelligence">Fundamentals and Background on Artificial Intelligence</a>, was to write a report on <strong>Principal Component Analysis (PCA)</strong>. This report allowed me to dive deep into a powerful statistical technique primarily used for <strong>dimensionality reduction</strong> in datasets with a large amount of features.</p><p>Imagine you have a dataset with hundreds of features (columns) describing a simple object, like a house. Some features might be redundant (e.g., “house square footage” and “house area in acres” contain almost the same information). Training a machine learning model on all these features can be slow, complex, and prone to the <strong>“Curse of Dimensionality”.</strong></p><p><strong>PCA solves this problem.</strong> Its core function is to transform a set of potentially <strong>correlated variables</strong> (the original features) into a new set of <strong>uncorrelated variables</strong> called <strong>Principal Components (PCs)</strong>. The goal is to capture as much of the <strong>information (variance)</strong> from the original dataset as possible using the fewest possible PCs.</p><p>I detail the math behind these steps in a simple, step-by-step manner in my academic report. If you are serious about understanding the <em>how</em>, check it out here: <a href="https://drive.google.com/file/d/1gkC6oLj21dDTfSvy6nOr_5dx94R-9nY3/view?usp=sharing">https://drive.google.com/file/d/1gkC6oLj21dDTfSvy6nOr_5dx94R-9nY3/view?usp=sharing</a></p><p>I also share the full source code for the report, along with the Python code samples I used to demonstrate PCA over the classic <strong>Iris Flower Dataset</strong> — an ideal small example for showing dimensionality reduction from 4 features to 2 Principal Components: <a href="https://github.com/gpetrousov/pca_lta_assignment_demokritos/blob/master/pca_lta_showcase.ipynb">https://github.com/gpetrousov/pca_lta_assignment_demokritos/blob/master/pca_lta_showcase.ipynb</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3da31350d01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I rejected an AI MSc from a top university. Here’s what I chose instead…]]></title>
            <link>https://medium.com/@petrousoft/i-rejected-an-ai-msc-from-a-top-university-heres-what-i-chose-instead-10575cfadcd6?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/10575cfadcd6</guid>
            <category><![CDATA[higher-education]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[challenge]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 15:03:55 GMT</pubDate>
            <atom:updated>2025-08-27T22:00:50.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgidxi5yGhhnPjWpryWb7A.jpeg" /><figcaption>Accepted (film 2006).</figcaption></figure><p>A few months ago I decided to take a serious step towards furthering my education in Artificial Intelligence (AI). AI has been atracting a lot of attention lately and I have been chiefly avocating myself with learning the intricacies and math behind the magic. To solidify my knowledge, I decided to apply for an MSc program. My goal is to connect with people in the field and deepen my understanding.</p><h3>My requirements</h3><p>I created a set of criteria to help me evaluate potential programs:</p><p><strong>Relatively short duration:</strong> I’m funding my own education and can’t stay a student forever. While programs typically range from 12–24 months, I focused on those around 18 months, including the thesis period.</p><p><strong>Practical knowledge.</strong> With a background in automation and cloud engineering, I wanted a program that would give me practical skills I could apply immediately. While most programs offer theoretical knowledge, I wanted to build models using well known frameworks like PyTorch and Tensorflow.</p><p><strong>I must be able to attent in person.</strong> From experience, I found out that to truly commit to something, you have to attend it up close and connect with your peers.</p><p><strong>Budge friendly.</strong> At 35, I don&#39;t qualify for any education related government funding. Affordability was a key factor.</p><p><strong>Sequential classes:</strong> The idea of waking up for a class at 09:00, having a long break, and then another class at 15:00 felt inefficient. I only considered programs with classes delivered sequentially, without interruptions.</p><h3>Universities</h3><p>Here’s the list of universities from Greece I found that met my criteria.</p><h4>UNIWA — University of West Attica</h4><p>This was my first choice. Artificial Intelligence &amp; Deep Learning: <a href="https://aidl.uniwa.gr/">https://aidl.uniwa.gr/</a></p><p><strong>Pros</strong></p><ul><li>Part-time studies possible for 5–6 semesters</li><li>You can undertake half of the courses and pay half of the fees</li><li>Courses are taught in English</li><li>Practical oriented (NVIDIA, Google, …)</li><li>Project-based assessment</li><li>Teaching hours: 17.00–21.45</li><li>They will give you an online English assessment test — no degree necessary</li></ul><p><strong>Cons</strong></p><ul><li>applications start in July 2025</li><li>classes start in March 2026</li></ul><h4>Demokritos</h4><p>This was my second option.</p><p>Artificial Intelligence: <a href="https://msc-ai.iit.demokritos.gr/">https://msc-ai.iit.demokritos.gr/</a></p><p><strong>Pros</strong></p><ul><li>Practical knowledge</li><li>Top research facility in Greece</li><li>Most exams are code-based</li><li>Classes are taught 17:00–21:00</li></ul><p><strong>Cons</strong></p><ul><li>Price 4500 euros - priciest option</li></ul><h4>AUTH — Aristotle University of Thessaloniki</h4><p>Top university in Greece and one of the best in Europe.</p><p><a href="https://ai.csd.auth.gr/">https://ai.csd.auth.gr/</a></p><p><strong>Pros</strong></p><ul><li>Top univesrity</li><li>Well priced (600 euros/cemester)</li><li>Choose your own courses</li></ul><p>Cons</p><ul><li>Longer education</li><li>Attention to theoretical knowledge</li><li>Rigid acceptance criteria</li><li>Duration: 24 months</li></ul><h4>University of Thessaly</h4><p>A well regarded university with a new program in AI.</p><p><a href="https://aia.dit.uth.gr/">https://aia.dit.uth.gr/</a></p><p><strong>Pros</strong></p><ul><li>Well priced</li></ul><p><strong>Cons</strong></p><ul><li>It’s a new program — no practical results yet</li><li>Short duration: 2 semesters to complete + thesis.</li><li>Smaller city, less exposure.</li></ul><h4>University of Πειραιά</h4><p><a href="https://cs.unipi.gr/metaptyxiakes-spoudes/aics-sdai/texnhth-nohmosynh-kai-eksypnes-efarmoges-logismikou/">https://cs.unipi.gr/metaptyxiakes-spoudes/aics-sdai/texnhth-nohmosynh-kai-eksypnes-efarmoges-logismikou/</a></p><p><strong>Pros</strong></p><ul><li>Python classes</li><li>Reasonably priced (2400 euros)</li></ul><p>Cons</p><ul><li>Distance learning</li><li>Documents provided are out of date — ask for info</li><li>Website is unmaintained, bad navigation</li></ul><h3>Applications &amp; Interviews</h3><p>I ended up applying and interviewing for 2 programs which I found most interesting: AUTH and Demokritos. AUTH seems to offer a solid program from a theoretical perspective which can qualify you to further your education into a PhD. On the other hand, Demokritos promotes the transfer of applied knowledge, part of which I found in Github repositories from former students.</p><p>I was interviewed by the teaching staff from both institutions - a first for me. I prepared as best I could by reviewing my knowledge in Neural Networks focusing on the theoretical foundations behind batches and gradient descent, which I had previously implemented from scratch, see <a href="https://github.com/gpetrousov/notebooks/blob/22bf2c162a987d9684d1fe4ea2fa71dbe7023065/mikroml_notebooks/04_minibatch.ipynb">https://github.com/gpetrousov/notebooks/blob/22bf2c162a987d9684d1fe4ea2fa71dbe7023065/mikroml_notebooks/04_minibatch.ipynb</a></p><p>Demokritos was up first. I was presented with 3 options to expand upon during the interview:</p><ol><li>talk about my thesis, if it was about AI - which it was not</li><li>talk about professional experience in AI - which I didn’t have</li><li>discuss a scientific paper on AI - I chose this one</li></ol><p>I was interviewed by 2 staff members who asked me about my previous experience focusing on AI in a professional setting. After that, we proceeded talking about the paper chose - Attention is all you need, see <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a> Overall, the interview went as fine as it could. We only had 30&#39; to our time which felt a lot shorter. The interviewers seemed tired, as if they had a full day of back-to-back interviews. I cought myself making 2 mistakes during our conversation which I debriefed myself on later.</p><p>The interview at AUTH was delayed by quite a lot - a tight schedule. This time, I was interviewed by a larger crowd - 4 people. Our conversation went about my previous experience and my current living situation in the Netherlands. I was also asked about my English proficiency. The conversation moved quickly and ended a bit more abruptly than my previous interview.</p><h3>Decissions</h3><p>Few weeks later, I received acceptance letters from both institutions. I chose to reject AUTH and accept Demokritos. Here’s why:</p><p>Interviewing with AUTH felt corporate, rigid and burreocratic. I felt that the interviewers hadn’t spent much time reviewing my profile (CV) or motivation letter, asking me questions that were clearly stated in my motivation letter. Additionally, I was asked about my profeciency in English, despite me having scored a C1 in online TOEFL test 2 weeks prior the deadline.</p><p>On the other hand, the interview with Demokritos felt like interviewing at a startup. The content was better organized by providing me options to discuss about. The interviewers were pragmatic stating things like “…we will teach you Artificial Intelligence…” and “…previous experience is not a requirement.”. My profile was assessed more axiocratically by focusing on motivation, previous achievements and potential rather than checkboxes.</p><p>I ended up accepting the invite from Demokritos.</p><h3>What I learned</h3><p>Researching for the “best” MsC program is a rabbit hole scenario. I spent way too much time on it.</p><p>Paying 1500 euros/month for rent in some village around a technical university in the Netherlands and commute 60&#39; just didn’t make sense for me.</p><p>I’ve found that younger teaching staff are often more motivated to improve their programs and share their knowledge. I still keep in touch with a few former professors because of this.</p><h3>Conclusion</h3><p>After 8 years in the Netherlands, I’m going back to Greece to further my education and challenge myself with a new field - AI. Plans after that? Don’t know yet. However, I always admired the title of “doctor”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10575cfadcd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The decay of Internet Service Providers]]></title>
            <link>https://medium.com/@petrousoft/the-decay-of-internet-service-providers-f2f20686b9bc?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2f20686b9bc</guid>
            <category><![CDATA[netherlands]]></category>
            <category><![CDATA[isp]]></category>
            <category><![CDATA[odido]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 16:23:15 GMT</pubDate>
            <atom:updated>2025-08-02T16:23:15.797Z</atom:updated>
            <content:encoded><![CDATA[<p>I live in the Netherlands and pay a hefty price for my internet subscription at home. My fee at my home got increased by almost 10 euros in the same year. And, while I was happy with the quality of their service, it felt bitter to pay 65 euros each month. So, we decided to try something new and signed up with one of the rivals, Odido. Here’s what followed.</p><h4>Why switch?</h4><p>According to the contract, my former ISP had the right to increase the monthly subscription by up to 10% in June 2024. And certainly they did; all the way up. Our monthly subscription went up from 54 euros per month to 64.</p><p>Odido offered the same throughtput 1Gbps with a 50% discount for 8 months. After the 8 months, it would switch to a fee of 52 euros. Switching for that price was a no-brainer.</p><h3>The Odido experience</h3><p>The serviceman installed the ISP’ router, said everything is fine and went to their next client. Shortly after, after having read the instructions on how to use your own router and having made the changes, I installed my UDM pro on the modem.</p><p>Here’s the depiction of the internet connection from Odido as it shows on my router. Red intervals are connection outages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_J8HyYSIwnRjLWND4Nltw.png" /><figcaption>1 hour with Odido</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcAkEGZbfvcKWKCG0Hrvqg.png" /><figcaption>1 day with Odido</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9TkYDNwyeA_Rgfk7TzngA.png" /><figcaption>1 week with Odido</figcaption></figure><p>I was taken aback by the horrible performance. While the throughput was fine, averaging at 978Mbps, idle latency went up to 90ms, transmission delay up to 120ms. That translated into pressing on a movie/video in Netflix/Youtube, getting the loading GIF and waiting for infinity for it to load.</p><p>I went back to using their device. That made things worse.</p><h3>Cancellation process</h3><p>Odido’s client service line is slower than their internet connection. You tend to get put on hold each time you explain your situation. After each holding time, you get a new employee and you have to explain them the same situation. During the holding times, you get a looping music which feels like something from the early 2000’s when this became a thing.</p><p>After many call attempts and several employees later, we managed to schedule a cancellation of the connection and went back to using KPN. I will omit the horrible details of how we ended up staying for 1 whole month on the horrible connection. How we were double charged by KPN because of a cancellation mistakes from Odido. How the service employees of Odido have absolutely no access to the subscription system and cannot manually override they dates. How the network engineers were unable to find anything wrong with the connection while clearly it was suffering from outages, even throughout the day.</p><h3>ISP situation in the Netherlands</h3><p>Having studied telecommunications at my University, we always praised the network connections the people received in Western Europe. And surely, overall the throughput and latency was better than in Greece.</p><p>However, at the moment, ISPs seem be bicker about getting more clients without rewarding the customers who prefer to stay longer with them. Instead, you get offered bundles of crap, such as movie, music or sports packages, which you don’t necessarily require. I see the same trend even with business accounts.</p><h3>You reap what you sow</h3><p>Yesterday I had an online buyer coming to my house to buy my PC speakers. When I opened the door, he said that he doesn’t have GPS, or internet, on his mobile so he couldn’t send me a message about the exact location of my house. He showed me his phone and he had no mobile signal at all. Admittedly, he was an Odido user.</p><p>Later that day, I found out that Odido had a major outages and its users were experiencing outages all over the country. This continued to the next day with the outage making its way to major news websites:</p><ul><li><a href="https://nieuws.nl/algemeen/telecomprovider-odido-kampt-met-storing-oorzaak-nog-onduidelijk">Telecomprovider Odido kampt met storing, oorzaak nog onduidelijk</a></li><li><a href="https://nos.nl/artikel/2577329">Storing Odido toch nog niet helemaal verholpen, mogelijk compensatie</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*2guRnJaotqBOe_7hFdq2pQ.png" /></figure><p>While most of the websites report that the outage is over, you can’t truly know unless you’re a subscriber.</p><h3>Conclusion</h3><p>Most contracts come with a “thinking time” of 2 weeks during which you can switch your connection. I’m happy to report I’m no longer a client of Odido and signed a new contract with KPN.</p><p>Consumerism has taken over ISPs in the worst possible way, Omnichannell. In Layman’s Terms, they try to sell you bundles of crap, like sports, music and TV packages, which you don’t necessarily need. I see the same trend even for business accounts. All offer some kind of a package designed to vendor lock you and turn you into a bingewatching vegetable.</p><p>If only there was an add-on to block the phonecalls and door-to-door visits by ISPs trying to sell me their packages…</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2f20686b9bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SQLAlchemy 2.0 to implement CRUD operations with FastAPI]]></title>
            <link>https://medium.com/@petrousoft/using-sqlalchemy-2-0-to-implement-crud-operations-with-fastapi-a56b040571ba?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56b040571ba</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Wed, 21 May 2025 09:27:29 GMT</pubDate>
            <atom:updated>2025-05-21T09:27:29.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLy7nXXkcZKsiUnHMzr7cA.jpeg" /><figcaption>Yes it’s generated.</figcaption></figure><p>I bought this course on Udemy to help me speed up my learning in FastAPI. The author uses a project based approach which teaches you how to use FastAPI to implement API endpoints and progressively injects more framework, including Pydantic and SQLAlchemy. While most of the content seems to be useful and up to speed, unfortunately, I couldn’t correlate the content from the course with the documentation from SQLAlchemy. That is primarily because SQLAlchemy had a new version release 2.0 which introduces changes in the way we define ORM Models and implement SQL operations. In this blog, I want to showcase how to convert a Pydantic model into its respective SQLAlchemy one and implement the CRUD operations using the new approach the 2.0 version. As an example, I’m going to use a user management system which I developed from before, see <a href="https://github.com/gpetrousov/tachydev/blob/fe2c18bab07a8278c507d27d581c84548e5f58ee/user_management/main.py">https://github.com/gpetrousov/tachydev/blob/fe2c18bab07a8278c507d27d581c84548e5f58ee/user_management/main.py</a></p><h3>Systemtic approach to using SQLAlchemy</h3><p>This approach outlines the steps we execute each time we create a new database. These steps are repeating so I create a systemic out of them. The steps are the following:</p><ol><li>Declare the model</li><li>Initialize the schema</li><li>Implement a connection</li><li>Perform the operations</li></ol><p>II have created a set of snippets to help me remember those steps: <a href="https://github.com/gpetrousov/tachydev/tree/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/sql_alchemy">https://github.com/gpetrousov/tachydev/tree/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/sql_alchemy</a></p><h4>Declare the model</h4><p>In a previous example, I implemented the following User model which describes the user object to be stored. This example uses the pydantic BaseModel to describe the property types.</p><pre>from pydantic import BaseModel, Field, EmailStr<br><br>class User(BaseModel):<br>    username: str<br>    hashed_password: str<br>    email: EmailStr<br>    active: bool = True<br>    id: int</pre><p>Following is the same model converted into a SQLAlchemy model which now describes the table name and the columns the database is going to have. Each row in the database stores the user object with its respective properties.</p><pre>from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase,<br><br><br>class Base(DeclarativeBase):<br>    pass<br><br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    username: Mapped[str] = mapped_column(String(8), unique=True, nullable=False)<br>    hashed_password: Mapped[str] = mapped_column(String(8))<br>    email: Mapped[str] = mapped_column(String)<br>    active: Mapped[bool] = mapped_column(Boolean, default=True)<br>    id: Mapped[int] = mapped_column(Integer, unique=True, primary_key=True)</pre><p>The SQLAlchemy 2.0 version mandates the use of a Base()class which extends the DeclarativeBase(). Furthermore, we define the columns of the database by using the mapped_column() function instead of the Column() class as before. The rest of the code should be self-explanatory. See docs: <a href="https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#union-types-inside-the-type-map">https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html#union-types-inside-the-type-map</a> for details or grab my code: <a href="https://github.com/gpetrousov/tachydev/blob/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/user_management/main.py#L27">https://github.com/gpetrousov/tachydev/blob/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/user_management/main.py#L27</a></p><h4>Schema initialization</h4><p>Next up is a process called schema initialization. This process generates the table and the columns inside a database. Before the initialization, the database cannot accept any objects for storage.</p><pre>from sqlalchemy import Integer, String, Boolean, create_engine<br><br>Base.metadata.create_all(bind=engine) # Schema initialization<br>Session = sessionmaker(engine)<br>app = FastAPI()</pre><h4>Implement a connection &amp; Perform operations</h4><p>The database is ready to accept connections. Here I declare the root API endpoint which connects to the database and performs an operations to return all the users from the database. SQLAlchemy 2.0 promotes the construction of use of ORM statements, such as select() and their execution with .execute()to interact with the database.</p><p><a href="https://github.com/gpetrousov/tachydev/blob/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/user_management/main.py#L57C1-L67C39">https://github.com/gpetrousov/tachydev/blob/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/user_management/main.py#L57C1-L67C39</a></p><pre># READ - SELECT<br>@app.get(&quot;/&quot;)<br>async def get_users():<br>    &quot;&quot;&quot; Return the usersDB - unprotected endpoint &quot;&quot;&quot;<br>    with Session() as sess:<br>        orm_statement = select(User)<br>        try:<br>            result = sess.execute(orm_statement)<br>            return result.scalars().all()<br>        except Exception as e:<br>            print(f&quot;get_users(): {e}&quot;)</pre><h3>Implement the INSERT operation</h3><p>The author of the Udemy course teaches to use .query() and .filter() functions to select and filter the data from a database. The more modern approach of SQLAlchemy uses .where() to filter the query results.</p><p>Here I’m implementing the INSERT operation which corresponds to a user registration. To check if the User already exists in the database, I implemented the get_user_from_db() function which uses the select(User).where(User.username == username) statement for filtering. This also uses the .scalar_one_or_none() method which either returns a row from the database or None see <a href="https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.CursorResult.scalar_one_or_none">https://docs.sqlalchemy.org/en/20/core/connections.html#sqlalchemy.engine.CursorResult.scalar_one_or_none</a></p><p>The difference from the root endpoint (above) is that here we also make modifications to the database by adding a new user. To persist those modifications, we need to commit them by calling the .commit() function.</p><pre>def get_user_from_db(username):<br>    orm_statement = select(User).where(User.username == username)<br>    with Session() as sess:<br>        try:<br>            existing_user = sess.execute(orm_statement).scalar_one_or_none()<br>        except Exception as e:<br>            print(f&quot;get_user_from_db: {e}&quot;)<br>    return existing_user<br><br># CREATE - INSERT<br>@app.post(&quot;/register&quot;, status_code=status.HTTP_201_CREATED)<br>async def register_new_user(new_user: UserRequest):<br>    &quot;&quot;&quot; Register new user and add to the database &quot;&quot;&quot;<br>    existing_user = get_user_from_db(new_user.username)<br>    if existing_user:<br>        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=&quot;User exists&quot;)<br>    insert_orm_statement = insert(User).values(<br>            username=new_user.username,<br>            email=new_user.email,<br>            hashed_password=bcrypt_context.hash(new_user.password)<br>            )<br>    with Session() as sess:<br>        try:<br>            sess.execute(insert_orm_statement)<br>            sess.commit()<br>        except Exception as e:<br>            print(f&quot;register_new_user: {e}&quot;)</pre><h3>Implement the UPDATE operation</h3><p>Similarly to above, I defined the update ORM statement using .where() to filter by username to update only the information of the currently logged in user. Once the information is updated, I call the .commit() function to persist them.</p><pre># UPDATE - SELECT - UPDATE<br>@app.put(&quot;/update&quot;, status_code=status.HTTP_204_NO_CONTENT)<br>async def update_me(current_user: Annotated[User, Depends(get_current_user)], updated_user: UserRequest):<br>    &quot;&quot;&quot; Update my user information &quot;&quot;&quot;<br>    print(f&quot;Update user: {updated_user}&quot;)<br>    orm_update_statement = update(User).where(User.username == current_user.username).values(<br>            username=updated_user.username,<br>            email=updated_user.email,<br>            hashed_password=bcrypt_context.hash(updated_user.password)<br>            )<br>    with Session() as sess:<br>        try:<br>            sess.execute(orm_update_statement)<br>            sess.commit()<br>        except Exception as e:<br>            print(f&quot;update_me: {e}&quot;)</pre><h3>Implement the DELETE operation</h3><p>The /delete endpoint operates only on the user which is logged in and allow them to delete their entry in the database. This restriction is implemented with the delete(User).where(User.username == username) query. Similar to before, we commit the operation.</p><pre>def delete_user(username):<br>    orm_delete_statement = delete(User).where(User.username == username)<br>    with Session() as sess:<br>        try:<br>            sess.execute(orm_delete_statement)<br>            sess.commit()<br>        except Exception as e:<br>            print(f&quot;delete_user: {e}&quot;)<br><br><br># DELETE - DELETE<br>@app.put(&quot;/delete&quot;, status_code=status.HTTP_204_NO_CONTENT)<br>async def delete_me(current_user: Annotated[User, Depends(get_current_user)]):<br>    &quot;&quot;&quot; Delete my user record &quot;&quot;&quot;<br>    delete_user(current_user.username)</pre><h3>Gotchas</h3><p>FastAPI features its own library to implement SQL operations called sqlmodel, see <a href="https://fastapi.tiangolo.com/tutorial/sql-databases/">https://fastapi.tiangolo.com/tutorial/sql-databases/</a>. While I haven’t looked, the claim is that it uses SQLAlchemy under its hood to implement the same database operations. SQLAlchemy seems like a more popular library so I chose to focus on that.</p><p>SQLAlchemy seems like a beast library. You have 2 modules — Core and ORM — and the new version appears to be trying to unify both of them under the same roof. At least that’s what I understand from the docs when looking at the operations. Check the example bellow, you have insert, update and delete in both docs but the usage is the same.</p><p><a href="https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html">https://docs.sqlalchemy.org/en/20/orm/queryguide/dml.html</a><br><a href="https://docs.sqlalchemy.org/en/20/core/dml.html">https://docs.sqlalchemy.org/en/20/core/dml.html</a></p><p>The INSERT , UPDATE and DELETE operations which modify the database, have a repeating pattern, they all create a connection and commit their changes. The Udemy course uses a clever approach by implementing this pattern as a dependency injection into the API endpoints which require it. Perhaps you can figure out your own.</p><h3>Conclusion</h3><p>This post showcases the newer approach to using SQLAlchemy 2.0 with FastAPI when implementing API endpoints which require database access. There are several approaches to implement the same functionality, however, I found the one described above compliant with the SQLAlchemy 2.0 approach. You can grab my code from <a href="https://github.com/gpetrousov/tachydev/blob/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/user_management/main.py">https://github.com/gpetrousov/tachydev/blob/84cd11181457a7f5a7321a7a58b5dcc2bdea19f0/user_management/main.py</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56b040571ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2 Authentication Using JWTs and FastAPI]]></title>
            <link>https://medium.com/@petrousoft/oauth2-authentication-using-jwts-and-fastapi-5dc2869da618?source=rss-ec18b2815c05------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dc2869da618</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[fastapi-tutorials]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ioannis Petrousov]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 13:15:46 GMT</pubDate>
            <atom:updated>2025-06-25T13:41:38.536Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simply explained</h4><p>I lost my brain when trying to understand how to implement authentication and JWT token with FastAPI. The “Security” section from the docs consists of 4 sections progressively building the /token API endpoint which should return the JWT token after a successful authentication — see <a href="https://fastapi.tiangolo.com/tutorial/security/">https://fastapi.tiangolo.com/tutorial/security/</a>. By the end of section 4, I came up with the following function call graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBwN6TWHI9f6ZEjGSlW9Iw.png" /><figcaption>Perhaps a timing diagram would make more sense here.</figcaption></figure><p>This looks like something that came out from a medical book. I couldn’t explain to myself what each function call did, and dependency injections made it a lot worse — see <a href="https://fastapi.tiangolo.com/tutorial/dependencies/">https://fastapi.tiangolo.com/tutorial/dependencies/</a></p><p>Nonetheless, I proceeded to figure out the process in depth, as an engineer does. The approach was to apply the divide and conquer method by breaking the process down into easily understandable individual components and then connecting them back to the whole.</p><h3>The password flow</h3><p>The password flow is described as a specification in the auth0 docs — see <a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow">https://auth0.com/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow</a></p><p>Here’s my explanation of it:</p><p>The client sends a POST request to the /login API endpoint. The request contains the username and password of the user.</p><p>The backend performs the Login flow:</p><p>1. Authenticate user<br> 1.1 Verify the user exists in the database (based on the username)<br> 1.1.1 If the username is in the database return the User object<br> 1.1.2 If the username does not exists in the database return None<br> 1.2 Verify the provided password with the stored hashed password<br> 1.2.1 If verification is False, raise exception<br> 1.3 Return User object from database<br>2. Generate JWT token using the User object<br> 2.1 Initialize data: {“sub”: username}<br> 2.2 Add token expiration time: {“exp”: time_delta}<br> 2.3 Join the above into a single dict (update())<br> 2.4 Encode it using: jwt.encode()<br>3. Create the JWT token object with access_token and token_type fields<br> 3.1 Return the JWT token object to the client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sxolGn4z4Nz4vZzs.png" /><figcaption><a href="https://auth0.com/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow">https://auth0.com/docs/get-started/authentication-and-authorization-flow/resource-owner-password-flow</a></figcaption></figure><p>I proceeded to implement the algorithm with FastAPI.</p><h3>Login</h3><p>It all starts with creating the /login API endpoint which implements the individual processes. The function of this endpoint accepts a special data form of type OAuth2PasswordRequestForm(). I outlined the steps 1, 2, 3 in the code snippet bellow so the flow is more clear.</p><p>This OAuth2PasswordRequestForm()class implements the specifications of OAuth2 for the username and password fields. As a developer, it’s not important to know all the details of this implementation. However, it’s important to understand that the values sent to the backend are not of type JSON, but are fields of the OAuth2PasswordRequestForm class — see <a href="https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L61">https://github.com/fastapi/fastapi/blob/master/fastapi/security/oauth2.py#L61</a></p><pre>@app.post(&quot;/login&quot;, response_model=JWTToken)<br>async def login(login_form: Annotated[OAuth2PasswordRequestForm, Depends()]):<br>    &quot;&quot;&quot; Login and return JWT token &quot;&quot;&quot;<br><br>    # 1. Authenticate user<br>    user = authenticate_user(login_form.username, login_form.password)<br>    if user is None:<br>        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;Unauthorized user&quot;)<br><br>    # 2. Create JWT token<br>    to_encrypt = {&quot;sub&quot;: user.username}<br>    exp_time = datetime.now(timezone.utc) + timedelta(minutes=5)<br>    to_encrypt.update({&quot;exp&quot;: exp_time})<br>    encoded_jwt = jwt.encode(to_encrypt, SECRET_KEY, ALGORITHM)<br><br>    # 3. Return JWT token object<br>    return JWTToken(access_token=encoded_jwt, token_type=&quot;Bearer&quot;)</pre><h4>1. User authentication</h4><p>The user authentication here is pretty straightforward and is implemented in the authenticate_user() function. This function will return the user object or None. It’s important to note a couple of things with this code. First, I’m using a simple list (USERS_DB) to store users in for matters of focus. Second, password validation happens via an external function (verify()).</p><pre>def authenticate_user(username, password):<br>    &quot;&quot;&quot; Validate username;Validate password &quot;&quot;&quot;<br><br>    #1.1 Validate username<br>    existing_user = None<br>    for u in USERS_DB:<br>        if u.username == username:<br>            existing_user = u<br>            break<br>    if existing_user is None:<br>        return None<br><br>    #1.2 Validate password<br>    if not bcrypt_context.verify(password, existing_user.hashed_password):<br>        return None<br><br>    return u</pre><p>I find the implementation of this function quite interesting. Before running the comparisons, it attempts to guess the type of the hashed password and if it can’t it fails with raise exc.UnknownHashError(“hash could not be identified”) Again, it’s not necessary to be aware of the whole flow, but if you are, see <a href="https://github.com/asmodehn/passlib/blob/master/passlib/context.py#L1451">https://github.com/asmodehn/passlib/blob/master/passlib/context.py#L1451</a></p><h4>2. Create JWT token</h4><pre># 2. Create JWT token<br>    to_encrypt = {&quot;sub&quot;: user.username}<br>    exp_time = datetime.now(timezone.utc) + timedelta(minutes=5)<br>    to_encrypt.update({&quot;exp&quot;: exp_time})<br>    encoded_jwt = jwt.encode(to_encrypt, SECRET_KEY, ALGORITHM)</pre><p>Once we have the user object, we can start constructing the JWT token object. The spec describes that the token consists of 3 parts separated by dots — Header, Payload, Signature. To be honest, I didn’t bother reading the docs since it’s all abstracted anyway by the jwt.encode() function. What I did pay attention to though, is that the function requires to receive a payload. This payload needs to be a dictionary which contains 2 keys “sub” and “exp” which have the username and expiration time of the token respectively. If any of these fields is missing, the function call will fail in the payload validation — see:</p><ul><li><a href="https://github.com/jpadilla/pyjwt/blob/8a65fbe46d989d0ab0c1f5fc3577841d66884411/jwt/api_jwt.py#L416">https://github.com/jpadilla/pyjwt/blob/8a65fbe46d989d0ab0c1f5fc3577841d66884411/jwt/api_jwt.py#L416</a></li><li><a href="https://github.com/jpadilla/pyjwt/blob/master/jwt/api_jwt.py#L480">https://github.com/jpadilla/pyjwt/blob/master/jwt/api_jwt.py#L480</a></li></ul><h4>3. Return JWT token</h4><p>The last step of the /login API endpoint returns the JWT token back to the client. In my case, this is an object which consists of 2 properties as shown bellow. The client is responsible for storing the access_token and sending it with each request to a protected API endpoint.</p><pre># 3. The JWT token object<br>class JWTToken(BaseModel):<br>    access_token: str<br>    token_type: str</pre><h3>Protecting an API endpoint</h3><p>With the login flow in place, we can protect any API endpoint with the expectation that the client will send the access_token it received from the backend with each request. An API call to a protected API endpoint performs the following steps:</p><p>The backend:<br>1. Decodes the JWT token<br> 1.1 Verify “sub” is present<br> 1.2 Extract username from “sub”<br> 1.2 Verify “exp” has not expired<br>2. Get user item from database<br>3. Check if user item is disabled<br> 3.1 Perform API functionality</p><p>For demonstration purposes, I’ll focus on protecting a simple API endpoint which returns the user which is currently logged in to the backend.</p><pre>@app.get(&quot;/me&quot;, status_code=status.HTTP_200_OK)<br>async def get_me(current_user: Annotated[User, Depends(get_current_user)]):<br>    &quot;&quot;&quot; Get my user information &quot;&quot;&quot;<br>    return current_user</pre><p>The code appears to be very short for the algorithm steps described above. More confusing is the argument and its type that this function takes. This is where dependency injections come into play. Each time this endpoint is called, before it starts executing its code, it triggers the get_current_user() function and passes whatever data it received from the client.</p><pre>async def get_current_user(token: Annotated[str, Depends(OAuth2PasswordBearer(tokenUrl=&quot;login&quot;))]):<br>    try:<br>        # 1. Decode the token<br>        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])<br>        username = payload.get(&quot;sub&quot;)<br>        if username is None:<br>            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;U/name missing.&quot;)<br>        expires = payload.get(&quot;exp&quot;)<br>        if datetime.now(timezone.utc) &gt; datetime.fromtimestamp(expires, timezone.utc):<br>            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;Token expired.&quot;)<br>    except InvalidTokenError:<br>        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;Invalid token error.&quot;)<br>    # 2. Get use from the database<br>    user = get_user_from_db(username)<br>    if user is None:<br>        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;U/name not found&quot;)<br>    return user</pre><p>In turn, this function takes as its argument a token of type OAuth2PasswordBearer which is the token returned by the /login API endpoint defined above. If successfully verified, this token should now contain the expected payload structure and have not expired. If this is the case, the function will return the User object from the database to its caller which is async def get_me(current_user: Annotated[User, Depends(get_current_user)]) which in turn returns it to the client.</p><h4>Dependency gotchas</h4><p>At first, it appears strange, however, this is the pattern. Each API endpoint you need secured, you need to annotate with the function which will verify the token — get_current_user() in this case.</p><p>This way you can define other API endpoints which might not necessarily return thecurrent_user information but do something else. Examples:</p><pre>@app.get(&quot;/print100&quot;, status_code=status.HTTP_200_OK)<br>async def print_100(current_user: Annotated[User, Depends(get_current_user)]):<br>  return 100<br><br>@app.put(&quot;/delete&quot;, status_code=status.HTTP_204_NO_CONTENT)<br>async def delete_me(current_user: Annotated[User, Depends(get_current_user)]):<br>    &quot;&quot;&quot; Delete my user record &quot;&quot;&quot;<br>    delete_user(current_user.username)<br><br>@app.get(&quot;/calculate&quot;, status_code=status.HTTP_200_OK)<br>async def calculate_result(current_user: Annotated[User, Depends(get_current_user)]):<br>  return 22/7</pre><h3>Conclusion</h3><p>Type annotations and dependencies in Python were not a thing when I started learning the language back in 2012. However, its widespread use dictated that it needs to have some of the features of compiled languages, such as Go.</p><p>This article focused on simplifying the explanation of the /login flow with JWT token (OAuth2) and securing API endpoints. Improvements can be made by encapsulating some of the functionality into more functions. However, that might lead to the diagram in the beginning of the article.</p><p>You can download the full implementation of this backend: <a href="https://github.com/gpetrousov/tachydev/blob/1.0_user_management/user_management/main.py">https://github.com/gpetrousov/tachydev/blob/1.0_user_management/user_management/main.py</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc2869da618" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>