Portfolio Debug

Total items: 5

  • title: From CNNs to Transformers: Top-k Image Retrieval path: _portfolio/4_Top-k-Image-Retrieval.md output: <!doctype html><html lang="en" class="no-js"><head> From CNNs to Transformers: Top-k Image Retrieval Home </head><body> <div class="masthead"><div class="masthead__inner-wrap"><div class="masthead__menu"><nav id="site-nav" class="greedy-nav"> <ul class="visible-links"> <li class="masthead__menu-item masthead__menu-item--lg persist"> Home</li><li class="masthead__menu-item"> About</li><li class="masthead__menu-item"> Portfolio</li><li class="masthead__menu-item"> Gallery</li><li class="masthead__menu-item"> CV</li><li class="masthead__menu-item"> Blog</li><li class="masthead__menu-item"> Contact</li><li id="theme-toggle" class="masthead__menu-item persist tail"> </li></ul><ul class="hidden-links hidden"></ul></nav></div></div></div><div class="initial-content"><div id="main" role="main"><article class="page" itemscope itemtype="http://schema.org/CreativeWork"><div class="page__inner-wrap"><header><h1 class="page__title" itemprop="headline">From CNNs to Transformers: Top-k Image Retrieval</h1><p class="page__date"> Published: </p></header><section class="page__content" itemprop="text"><p>View code on GitHub
    Read full paper (CVPR format)</p><p>This was a competition project for our Machine Learning course—four members team which the goal to: retrieve the top-10 most similar images for each query. Queries were real photos of celebrities, and the gallery was synthetic AI-generated portraits of the same people, but rendered in completely different artistic styles.</p><p>This wasn’t a pixel-matching problem. A real photo of someone in a suit and a cartoon-style portrait of the same person share almost nothing at the texture level. We needed semantic understanding—models that could reason about identity despite radical visual differences.</p><hr /><h2 id="my-role--focus">My Role & Focus</h2><p>I worked in a team of four, and I focused mainly on two areas:</p><p>CLIP — I ran the CLIP variants (ViT-B/32, B/16, L/14), handling both frozen and fine-tuned setups. This involved figuring out how to properly unfreeze transformer layers, tuning learning rates, and eventually discovering we’d been doing fine-tuning wrong the entire competition.</p><p>Metrics design — We initially used generic retrieval metrics, but I realized we needed something aligned with the competition’s weighted scoring system (600 points for Top-1, 300 for Top-5, 100 for Top-10). I built the evaluation pipeline that tracked this properly and helped us understand where models were actually failing.</p><p>Looking back, one thing I’d change: CLIP has its own contrastive loss built-in, and we should have used it from the start instead of reinventing it post-competition.</p><hr /><h2 id="what-we-tried">What We Tried</h2><p>We tested everything: ResNets, EfficientNets, GoogLeNet, DINOv2, and multiple CLIP variants. We experimented with pooling strategies (Global Average Pooling vs. Generalized Mean Pooling), froze vs. fine-tuned encoders, and ran ablations on loss functions.</p><p>The pattern that emerged was clear: transformers consistently outperformed CNNs when semantic similarity mattered more than texture matching. CLIP, pretrained on 400M image-text pairs, had learned to embed meaning rather than just pixels. It could look at a real photo and a stylized illustration and understand they depicted the same person—something ResNets struggled with.</p><p>But here’s where it got interesting: having a powerful architecture didn’t automatically translate to good results.</p><hr /><h2 id="the-fine-tuning-fix">The Fine-Tuning Fix</h2><p>During the competition, we were convinced we were fine-tuning CLIP properly. We weren’t.</p><p>The training loop had a subtle bug: parameter updates weren’t propagating to the transformer blocks. We were essentially running frozen inference with an unfrozen classification head, which is why our competition-day score with ViT-L/14 was 510.24—decent, but nowhere near its potential.</p><p>Post-competition, We went back and debugged the entire training pipeline:</p><ul><li>Fixed layer unfreezing to ensure gradients flowed through all transformer blocks</li><li>Added gradient accumulation (simulating larger batches without OOM errors)</li><li>Implemented explicit memory management (torch.cuda.empty_cache())</li><li>Replaced pure cross-entropy with a hybrid loss: cross-entropy + contrastive learning</li></ul><p>That last point was critical. Cross-entropy alone pushes classes apart but doesn’t preserve relational structure in the embedding space. If two celebrities look similar, their embeddings should reflect that, even if they’re different identities. Contrastive loss enforces this: pull same-class embeddings together, push different-class embeddings apart.</p><p>With these fixes, ViT-L/14’s score jumped to 791.82—a +281.6 improvement. That’s not a minor bump; that’s the difference between a working training pipeline and a broken one.</p><hr /><h2 id="why-clip-actually-worked">Why CLIP Actually Worked</h2><p>CLIP’s advantage comes from its pretraining objective. It’s trained on image-caption pairs, learning to align visual and textual semantics in a shared embedding space. This gives it abstract reasoning capabilities that CNNs don’t have.</p><p>A CNN sees edges, textures, and color gradients. CLIP sees “a person with specific facial features” regardless of whether they’re photographed or illustrated. When you’re matching across massive domain shifts, that’s the capability you need.</p><p>But—and this is important—CLIP’s zero-shot performance wasn’t enough. Even with 400M pretraining examples, it needed task-specific fine-tuning to distinguish between real and synthetic faces in our dataset. The trick was doing that fine-tuning correctly, which we initially didn’t.</p><hr /><h2 id="lessons-id-apply-next-time">Lessons I’d Apply Next Time</h2><p>Use native model tools when they exist. CLIP has a built-in contrastive loss designed for its architecture. We ended up implementing our own variant post-competition, which worked, but it would’ve been smarter to start with what the authors provided.</p><p>Infrastructure matters as much as architecture. The difference between our competition score and our post-competition score wasn’t about discovering a better model—it was about fixing memory bottlenecks and gradient flow. Scaling laws are real: larger models perform better, but only if your training pipeline can actually train them.</p><p>Metrics guide everything. We spent the first half of the competition optimizing for the wrong thing because our evaluation didn’t match the competition’s weighted scoring. Once I built the proper metric tracker, decision-making became much clearer.</p><p>Ablations reveal more than leaderboards. We ran side-by-side comparisons of every architecture, pooling strategy, and loss function. That’s how we learned transformers systematically beat CNNs for semantic retrieval. The leaderboard told us scores; ablations told us why.</p><hr /><h2 id="results">Results</h2><table><thead><tr><th>Model</th><th>Configuration</th><th>Top-k Accuracy</th></tr></thead><tbody><tr><td>CLIP ViT-L/14</td><td>Fine-tuned, hybrid loss (post-competition)</td><td>791.82</td></tr><tr><td>CLIP ViT-L/14</td><td>Fine-tuned, CE only (competition day)</td><td>510.24</td></tr><tr><td>CLIP ViT-B/16</td><td>Fine-tuned</td><td>603.85</td></tr><tr><td>EfficientNet-B3</td><td>Fine-tuned, GAP</td><td>0.8513 (Precision@K on Animals dataset)</td></tr><tr><td>ResNet-152</td><td>Fine-tuned</td><td>~0.72 (Precision@K)</td></tr></tbody></table><p>The final system retrieves semantically correct matches even when query and gallery images look nothing alike visually—exactly what we needed.</p><hr /><h2 id="technical-stack">Technical Stack</h2><p>Models: CLIP (ViT-B/32, B/16, L/14), DINOv2, EfficientNet (B0, B3), ResNet (34, 50, 101, 152), GoogLeNet
    Framework: PyTorch, torchvision, Hugging Face Transformers
    Evaluation: Custom weighted Top-k accuracy aligned with competition scoring
    Training optimizations: Gradient accumulation, mixed precision (fp16), explicit memory management
    Collaboration: Team of 4, version control via GitHub, experiments logged in JSON</p><hr /><p>making models trainable, not just picking the right architecture.</p><p>We had access to ViT-L/14 from day one. It took us time to actually unlock its performance because the barrier wasn’t the model—it was memory constraints, gradient bugs, and loss function design.</p><hr /><p>📂 Full code and experiments
    📄 Technical paper (CVPR format)</p><p>Team: Silvia Bortoluzzi, Diego Conti, Sara Lammouchi, Tereza Sásková
    Course: Introduction to Machine Learning, University of Trento (2024–2025)</p><hr /></section><footer class="page__meta"></footer><nav class="pagination"> Previous Next </nav></div></article></div></div><div class="page__footer"><footer> <footer class="page__footer"><div class="page__footer-follow"><ul class="social-icons"><li> GitHub</li></ul></div></footer></footer></div></body></html>

    url: /portfolio/topk-image-retrieval/ link: teaser: /Users/terezasaskova/Desktop/portfolio-1/images/home-bg.jpg

  • title: Reddit & Conflict: Israel–Palestine Discourse Analysis path: _portfolio/conflict-analysis.md output: <!doctype html><html lang="en" class="no-js"><head> Reddit & Conflict: Israel–Palestine Discourse Analysis Home </head><body> <div class="masthead"><div class="masthead__inner-wrap"><div class="masthead__menu"><nav id="site-nav" class="greedy-nav"> <ul class="visible-links"> <li class="masthead__menu-item masthead__menu-item--lg persist"> Home</li><li class="masthead__menu-item"> About</li><li class="masthead__menu-item"> Portfolio</li><li class="masthead__menu-item"> Gallery</li><li class="masthead__menu-item"> CV</li><li class="masthead__menu-item"> Blog</li><li class="masthead__menu-item"> Contact</li><li id="theme-toggle" class="masthead__menu-item persist tail"> </li></ul><ul class="hidden-links hidden"></ul></nav></div></div></div><div class="initial-content"><div id="main" role="main"><article class="page" itemscope itemtype="http://schema.org/CreativeWork"><div class="page__inner-wrap"><header><h1 class="page__title" itemprop="headline">Reddit & Conflict: Israel–Palestine Discourse Analysis</h1><p class="page__date"> Published: </p></header><section class="page__content" itemprop="text"><p>View code on GitHub
    View visualizations</p><p>This project focus on the relationship between real-world conflict events and online conntent on social media using cross-correlation analysis and unsupervised topic modeling. The central research question: Do social media discussions respond to geopolitical violence in real-time?</p><p>We integrated two data sources—Reddit comment streams (unstructured social data) and ACLED conflict events (structured geopolitical data)—to quantify how online attention patterns correlate with offline violence in Gaza and the West Bank. The analysis revealed a 15-day lag in peak discourse volume relative to conflict intensity, with evidence of selective amplification based on event severity.</p><hr /><h2 id="problem-formulation--data-integration-challenges">Problem Formulation & Data Integration Challenges</h2><h3 id="data-sources">Data Sources</h3><p>Reddit corpus: 2.1GB dataset spanning March–June 2025, containing approximately 1.2M comments from conflict-related subreddits. Raw text exhibits high variability: colloquial language, sarcasm, emotionally charged rhetoric, and domain-specific terminology.</p><p>ACLED event database: Structured records of 5,000+ conflict incidents with temporal, geographic, and categorical metadata (event type, fatalities, civilian targeting). Events include battles, explosions, targeted killings, and violence against civilians.</p><h3 id="core-challenge-cross-domain-alignment">Core Challenge: Cross-Domain Alignment</h3><p>The primary challenge was aligning asynchronous, semantically distinct data streams for temporal comparison:</p><ol><li><p>Semantic extraction from noisy text: Reddit comments required aggressive preprocessing to extract meaningful signal. Standard NLP pipelines underperformed due to domain-specific jargon, neologisms, and syntactic irregularities.</p></li><li><p>Event granularity mismatch: ACLED provides incident-level records with fine-grained categorization (20+ event subtypes). Reddit discourse operates at thematic levels that don’t map cleanly to ACLED’s taxonomy. We needed dimensionality reduction on both sides.</p></li><li><p>Temporal aggregation: Reddit exhibits strong day-of-week effects and time-of-day biases. ACLED events cluster around military operations schedules. Naive daily aggregation produced non-stationary time series unsuitable for correlation analysis.</p></li></ol><hr /><h2 id="methodology">Methodology</h2><h3 id="text-preprocessing-pipeline">Text Preprocessing Pipeline</h3><p>We implemented a multi-stage cleaning and normalization pipeline:</p><p>Regex-based cleaning:</p><ul><li>URL removal via pattern matching</li><li>Punctuation stripping</li><li>Numeric token removal</li></ul><p>spaCy-based linguistic normalization:</p><ul><li>Lemmatization to preserve semantic fidelity (e.g., “bombing” to “bomb”)</li><li>Stopword removal with length filtering (tokens > 2 characters)</li><li>Part-of-speech tagging for linguistic features</li></ul><p>Key decisions:</p><ul><li>Lemmatization over stemming: Preserved semantic fidelity rather than aggressive truncation.</li><li>Sentence boundary detection: Retained via spaCy’s sentencizer to preserve local context for topic modeling.</li><li>Vectorization constraints: CountVectorizer with max_df=0.9, min_df=10 to filter ultra-frequent generic terms and ultra-rare noise tokens.</li></ul><p>Computational optimization: Processed in 1000-row chunks with batch spaCy inference (batch_size=32) to avoid memory overflow on 2.1GB corpus.</p><h3 id="acled-event-categorization">ACLED Event Categorization</h3><p>ACLED’s fine-grained event taxonomy was collapsed into two high-level categories aligned with discourse relevance:</p><ul><li>Combat: Battles + Explosions/Remote violence (military-to-military engagements)</li><li>Civilian Harm: Violence against civilians (asymmetric targeting, likely to generate moral outrage)</li></ul><p>This reduction was theoretically motivated: prior research in media studies suggests public attention gravitates toward civilian casualties over military operations (Galtung & Ruge’s news value theory).</p><h3 id="temporal-alignment--smoothing">Temporal Alignment & Smoothing</h3><p>Both datasets were aggregated to daily granularity and smoothed using a 7-day centered rolling window.</p><p>Rationale:</p><ul><li>Removes high-frequency noise (weekend effects, single-day spikes)</li><li>Preserves medium-term trends (weekly discourse cycles)</li><li>Centers the window to avoid phase shifts in correlation analysis</li></ul><h3 id="cross-correlation-analysis">Cross-Correlation Analysis</h3><p>To detect temporal lag, we computed the cross-correlation function between ACLED event counts and Reddit post volumes. Both series were z-score normalized prior to correlation to ensure scale invariance.</p><p>Implementation approach:</p><ul><li>Standardized both time series (mean=0, standard deviation=1)</li><li>Computed correlation at all possible time offsets</li><li>Identified lag corresponding to maximum correlation</li></ul><p>Result: Maximum correlation of r=0.56 at lag +15 days, indicating Reddit discourse systematically trails conflict events by approximately two weeks.</p><hr /><h2 id="topic-modeling-latent-dirichlet-allocation">Topic Modeling: Latent Dirichlet Allocation</h2><p>To characterize thematic structure, we applied LDA to the Reddit corpus using a bag-of-words representation.</p><p>Model configuration:</p><ul><li>n_components=5 (determined via coherence score evaluation)</li><li>max_iter=5 (sufficient for convergence on this corpus size)</li><li>Document-term matrix generated via CountVectorizer with preprocessed text</li></ul><p>Extracted topics (top-10 terms per topic):</p><table><thead><tr><th>Topic</th><th>Dominant Terms</th><th>Interpretation</th></tr></thead><tbody><tr><td>0</td><td>airstrike, IDF, Gaza, bomb, military</td><td>Military Operations</td></tr><tr><td>1</td><td>hospital, aid, civilians, killed, UNRWA</td><td>Humanitarian Crisis</td></tr><tr><td>2</td><td>Netanyahu, Iran, Trump, Biden, blame</td><td>Geopolitical Attribution</td></tr><tr><td>3</td><td>protest, march, campus, solidarity</td><td>Activism & Mobilization</td></tr><tr><td>4</td><td>media, bias, coverage, propaganda</td><td>Meta-Discourse on Framing</td></tr></tbody></table><p>Temporal topic dynamics: We computed daily topic distributions by aggregating per-document topic assignments, then overlaid these on the ACLED fatality timeline to identify event-discourse associations.</p><h3 id="key-finding-selective-amplification">Key Finding: Selective Amplification</h3><p>Topic intensity correlated with event severity (measured by fatalities), not event frequency:</p><ul><li>High-fatality events (>50 deaths) generated 10x more discussion than low-level violence</li><li>June 17 airstrike on aid convoy (85 fatalities) produced massive spike in Topic 1 (Humanitarian Crisis)</li><li>Sustained low-intensity clashes (<10 fatalities/day) generated minimal Reddit activity</li></ul><p>This suggests discourse operates via a threshold activation function: events must exceed a salience threshold to penetrate public attention.</p><hr /><h2 id="technical-implementation--engineering-decisions">Technical Implementation & Engineering Decisions</h2><h3 id="why-lda-over-transformer-based-models">Why LDA Over Transformer-Based Models?</h3><p>We evaluated both LDA and BERTopic:</p><table><thead><tr><th>Method</th><th>Pros</th><th>Cons</th><th>Decision Rationale</th></tr></thead><tbody><tr><td>LDA</td><td>Fast, interpretable, provides topic distributions</td><td>Bag-of-words assumption, no semantic embeddings</td><td>Chosen for exploratory analysis; sufficient for thematic clustering</td></tr><tr><td>BERTopic</td><td>Semantic embeddings, better coherence</td><td>Computationally expensive, less transparent</td><td>Viable for future work with GPU resources</td></tr></tbody></table><p>LDA was sufficient because we needed coarse thematic categories, not fine-grained semantic distinctions. BERTopic would add value if distinguishing between subtopics (e.g., “hospital bombing” vs. “hospital blockade”).</p><h3 id="memory--computational-optimization">Memory & Computational Optimization</h3><p>Challenge: 2.1GB corpus exceeded single-pass memory limits.</p><p>Solution: Streaming pipeline with chunked processing using pandas chunksize parameter. Each chunk was processed independently and appended to output file incrementally.</p><p>Alternative considered: Dask for distributed processing. Not adopted due to overhead for single-machine workload and lack of GPU parallelization needs.</p><h3 id="cross-correlation-vs-granger-causality">Cross-Correlation vs. Granger Causality</h3><p>Granger causality would provide directional inference (does X cause Y?), but requires:</p><ul><li>Stationarity (violated by trend components in both series)</li><li>Linear VAR assumptions (unlikely given nonlinear discourse dynamics)</li></ul><p>Cross-correlation is more robust for:</p><ul><li>Exploratory lag detection</li><li>Non-stationary data</li><li>Pattern similarity over causal inference</li></ul><p>Future work could apply Transfer Entropy for model-free causal detection.</p><hr /><h2 id="results--quantitative-findings">Results & Quantitative Findings</h2><table><thead><tr><th>Metric</th><th>Value</th><th>Interpretation</th></tr></thead><tbody><tr><td>Peak Cross-Correlation</td><td>r=0.56 at lag +15 days</td><td>Reddit lags conflict events by approximately 2 weeks</td></tr><tr><td>Topic 1 (Humanitarian)</td><td>28% of total discourse</td><td>Dominant theme during high-fatality events</td></tr><tr><td>Selective Attention Ratio</td><td>10:1 (high vs. low fatality)</td><td>Public attention is event-severity dependent</td></tr><tr><td>Corpus Size</td><td>1.2M comments, 2.1GB</td><td>Processed in <2 hours with chunk-based pipeline</td></tr></tbody></table><h3 id="validation-annotated-event-mapping">Validation: Annotated Event Mapping</h3><p>We manually validated the top 5 deadliest events against discourse spikes:</p><table><thead><tr><th>Date</th><th>Event Description</th><th>Fatalities</th><th>Reddit Spike (7-day avg)</th></tr></thead><tbody><tr><td>June 17</td><td>Airstrike on aid convoy</td><td>85</td><td>+320% vs. baseline</td></tr><tr><td>May 18</td><td>Sustained urban combat</td><td>62</td><td>+180% vs. baseline</td></tr><tr><td>March 18</td><td>Hospital complex strike</td><td>51</td><td>+250% vs. baseline</td></tr></tbody></table><p>All high-fatality events produced discourse spikes within the 15±5 day window, confirming lag consistency.</p><hr /><h2 id="limitations--future-directions">Limitations & Future Directions</h2><p>Sentiment analysis integration: Current analysis focuses on volume and topics. Incorporating polarity and emotion detection (e.g., via VADER or transformer-based sentiment models) would capture tonal shifts beyond thematic changes.</p><p>Event causality modeling: Cross-correlation establishes temporal association, not causation. Transfer entropy or dynamic Bayesian networks could provide causal inference.</p><p>Longitudinal extension: Analysis covers 4 months. Extending to multi-year datasets would test lag stability across different conflict phases (escalation vs. de-escalation).</p><p>Multilingual expansion: Current corpus is English-only. Incorporating Arabic and Hebrew discourse from regional platforms would provide comparative analysis of information asymmetries.</p><p>Automated event categorization: Manual ACLED categorization could be replaced with supervised classification using event embeddings (e.g., BERT fine-tuned on ACLED descriptions).</p><hr /><h2 id="technical-stack">Technical Stack</h2><p>Core Libraries: pandas, NumPy, spaCy, scikit-learn , gensim , scipy NLP Pipeline: Regex normalization → spaCy lemmatization → CountVectorizer → LDA
    Statistical Methods: Cross-correlation, rolling window smoothing, z-score normalization
    Visualization: Matplotlib with dual-axis time-series plots and lag correlation graphs
    Data Sources: Reddit, ACLED
    Compute Environment: Single-node processing, 16GB RAM, chunked I/O for memory efficiency</p><hr /><h2 id="implications-for-computational-social-science">Implications for Computational Social Science</h2><p>This work demonstrates that social media discourse operates on delayed, selective attention mechanisms when responding to geopolitical events. The 15-day lag suggests information diffusion through news cycles, secondary commentary, and thematic framing processes rather than direct real-time observation.</p><p>The selective amplification finding aligns with news value theory: events must be exceptional (high fatality, civilian targeting) to penetrate the attention economy. Low-intensity violence—despite cumulative humanitarian impact—fails to generate sustained discourse.</p><p>From a methodological standpoint, the project highlights the importance of temporal alignment techniques in cross-domain analysis. Naive correlation without smoothing and lag detection would have produced spurious null results.</p><hr /><p>📂 Full implementation and reproducible notebooks
    📊 Visualization suite and data artifacts</p><p>Author: Tereza Sásková
    Institution: University of Trento, Computational Social Science (Spring 2025)</p></section><footer class="page__meta"></footer><nav class="pagination"> Previous Next </nav></div></article></div></div><div class="page__footer"><footer> <footer class="page__footer"><div class="page__footer-follow"><ul class="social-icons"><li> GitHub</li></ul></div></footer></footer></div></body></html>

    url: /portfolio/reddit-conflict/ link: teaser: /images/portfolio/reddit-conflict/reddit_top5_LDA.png

  • title: Podcast Recommendation Platform path: _portfolio/3_podcast-recommendation-platform.md output: <!doctype html><html lang="en" class="no-js"><head> Podcast Recommendation Platform Home </head><body> <div class="masthead"><div class="masthead__inner-wrap"><div class="masthead__menu"><nav id="site-nav" class="greedy-nav"> <ul class="visible-links"> <li class="masthead__menu-item masthead__menu-item--lg persist"> Home</li><li class="masthead__menu-item"> About</li><li class="masthead__menu-item"> Portfolio</li><li class="masthead__menu-item"> Gallery</li><li class="masthead__menu-item"> CV</li><li class="masthead__menu-item"> Blog</li><li class="masthead__menu-item"> Contact</li><li id="theme-toggle" class="masthead__menu-item persist tail"> </li></ul><ul class="hidden-links hidden"></ul></nav></div></div></div><div class="initial-content"><div id="main" role="main"><article class="page" itemscope itemtype="http://schema.org/CreativeWork"><div class="page__inner-wrap"><header><h1 class="page__title" itemprop="headline">Podcast Recommendation Platform</h1><p class="page__date"> Published: </p></header><section class="page__content" itemprop="text"><p>A hybrid recommender that answers two questions at once: what does this user like, and what is this episode actually about?</p><p>View code on GitHub Architecture docs</p><table><thead><tr><th> </th><th> </th></tr></thead><tbody><tr><td>Context</td><td>Big Data Technologies course, University of Trento — team project</td></tr><tr><td>My role</td><td>Data ingestion, Kafka & Spark pipelines, transcript processing and model training</td></tr><tr><td>Stack</td><td>Python · Apache Kafka · Spark (Structured Streaming, ML) · Delta Lake · Airflow · MongoDB · DuckDB · Streamlit · Docker</td></tr><tr><td>Techniques</td><td>Speech-to-text · sentence embeddings + KNN · implicit-feedback matrix factorisation (ALS) · hybrid ranking</td></tr><tr><td>Outcome</td><td>Fully containerised pipeline, from raw podcast audio to per-user recommendations in a live dashboard, runnable with one make command</td></tr></tbody></table><hr /><h2 id="architecture">Architecture</h2><p>Two independent pipelines feed one ranking step. The content pipeline turns audio into text and finds episodes that talk about similar things. The behaviour pipeline turns listening events into a collaborative-filtering model. A final Spark job blends both scores and writes the result to MongoDB for the dashboard.</p>

    Architecture: content pipeline (PodcastIndex, Kafka, Vosk, Delta Lake, embeddings + KNN, MongoDB) and behaviour pipeline (event simulator, Kafka, Spark Streaming, Delta Lake, ALS, MongoDB) merge into a hybrid ranking served by Streamlit; Airflow orchestrates all jobs. Architecture diagram, vertical layout <figcaption>Click any box to open the code that implements it. Dashed boxes are storage; Airflow schedules every job.</figcaption>
    <table><thead><tr><th>Layer</th><th>What happens</th><th>Tools</th></tr></thead><tbody><tr><td>Ingest</td><td>Trending episodes are pulled from the open PodcastIndex API and published to Kafka; audio is converted to 16 kHz mono and transcribed locally. User plays, likes and skips are simulated and streamed through a second topic.</td><td>Kafka, Vosk</td></tr><tr><td>Store</td><td>Transcripts, embeddings and aggregated user × episode engagement land in Delta Lake as the single source of truth.</td><td>Delta Lake</td></tr><tr><td>Model</td><td>Transcripts are embedded and compared with KNN (top-k cosine). Engagement scores train an ALS model for collaborative filtering.</td><td>SentenceTransformers, Spark ML</td></tr><tr><td>Serve</td><td>Both outputs are joined into one score per user–episode pair and stored in MongoDB. The dashboard reads recommendations from Mongo and live analytics straight from Delta via DuckDB.</td><td>Spark, MongoDB, DuckDB, Streamlit</td></tr></tbody></table><hr /><h2 id="engineering-decisions">Engineering decisions</h2><p>Listening data has no ratings, so I modelled it as implicit feedback. A 10-second play and a full listen are both “interactions”, but they mean very different things. Each event type gets a weight (full play > like > short play > skip), events are aggregated into daily user × episode scores, and ALS is trained with implicitPrefs=true: whether a user interacted is the preference, and how strongly is the confidence (c = 1 + α·r). Configuration: rank 32, α = 40, λ = 0.08, non-negative factors.</p><p>Long transcripts don’t fit an embedding model, so they are chunked. all-MiniLM-L6-v2 has a short input limit, while a podcast episode is thousands of words. Each transcript is split into token chunks, each chunk is embedded, and the episode vector is a token-weighted average, re-normalised so cosine similarity stays meaningful.</p><p>Heavy work on Spark, light reads on DuckDB. Spark is the right engine for streaming aggregation and distributed ALS, but starting it for every dashboard refresh is wasteful. The dashboard queries Delta tables directly with DuckDB, in process and without a cluster, so charts like “events per minute” update in real time.</p><p>Reproducibility built into the storage layer. Kafka retains events so pipelines can be replayed from an offset, and Delta Lake’s time travel lets a model be retrained on an exact earlier version of the data.</p><p>Two simple ideas behind the ranking. The final score is 0.7 · ALS + 0.3 · content similarity. ALS captures taste; similarity to episodes the user already listened to pulls topically related content up the list. In the dashboard, top-rated episodes use a Bayesian average, so one 5-star vote cannot outrank fifty 4-star votes.</p><hr /><h2 id="results">Results</h2>
    Streamlit dashboard with KPI cards, top recommendation per user, live engagement chart and top episodes<figcaption>Streamlit dashboard: KPI cards, the top recommendation for each user, live engagement per minute, and top episodes by weighted engagement.</figcaption>
    <ul><li>Four Airflow DAGs (new_episodes, user_events, recommendation, demo) run the system end to end.</li><li>Recommendations are written as a complete snapshot to MongoDB on every run, so the dashboard always reads one consistent version.</li><li>The whole stack — Kafka, Spark, Airflow, MongoDB, Streamlit — starts with make init in Docker Compose.</li></ul><hr /><h2 id="limitations-and-next-steps">Limitations and next steps</h2><p>Being honest about what a course project does not do is part of the design:</p><ul><li>Simulated users. There was no access to real listening data, so events are generated. The next step would be real tracking (e.g. Snowplow) and offline evaluation with precision@k / recall@k.</li><li>Cold start. Candidates currently come from ALS, and similarity re-ranks them, so a brand-new episode only appears once it has some interactions. Adding a content-only candidate path for new episodes would fix this.</li><li>Scaling similarity. Exact KNN is fine for a course-sized catalogue; a production version would use an approximate index (FAISS/HNSW).</li><li>Operations. Model and data-drift monitoring (Evidently, Great Expectations) and an A/B split between hybrid and ALS-only ranking would be the next additions.</li></ul><p>View the repository on GitHub</p></section><footer class="page__meta"></footer><nav class="pagination"> Previous Next </nav></div></article></div></div><div class="page__footer"><footer> <footer class="page__footer"><div class="page__footer-follow"><ul class="social-icons"><li> GitHub</li></ul></div></footer></footer></div></body></html>

    url: /portfolio/podcast-platform/ link: teaser: /images/dashboard.png

  • title: Weekend Registration System — Ski Zadov path: _portfolio/2_form_app.md output: <!doctype html><html lang="en" class="no-js"><head> Weekend Registration System — Ski Zadov Home </head><body> <div class="masthead"><div class="masthead__inner-wrap"><div class="masthead__menu"><nav id="site-nav" class="greedy-nav"> <ul class="visible-links"> <li class="masthead__menu-item masthead__menu-item--lg persist"> Home</li><li class="masthead__menu-item"> About</li><li class="masthead__menu-item"> Portfolio</li><li class="masthead__menu-item"> Gallery</li><li class="masthead__menu-item"> CV</li><li class="masthead__menu-item"> Blog</li><li class="masthead__menu-item"> Contact</li><li id="theme-toggle" class="masthead__menu-item persist tail"> </li></ul><ul class="hidden-links hidden"></ul></nav></div></div></div><div class="initial-content"><div id="main" role="main"><article class="page" itemscope itemtype="http://schema.org/CreativeWork"><div class="page__inner-wrap"><header><h1 class="page__title" itemprop="headline">Weekend Registration System — Ski Zadov</h1><p class="page__date"> Published: </p></header><section class="page__content" itemprop="text"><p>A booking system used by real customers: parents choose which winter weekends their children ski, and the database makes sure the course rules can’t be broken.</p><p>Open the live app</p><p class="notice--info">The source code is private because it runs the school’s real customer data. I’m happy to walk through it in an interview.</p><table><thead><tr><th> </th><th> </th></tr></thead><tbody><tr><td>Client</td><td>Ski Zadov, our family ski school in Šumava</td></tr><tr><td>My role</td><td>Sole developer — requirements, database design, backend, frontend, deployment and data import</td></tr><tr><td>Stack</td><td>Python · Flask · SQLAlchemy · PostgreSQL · Railway · Gunicorn · vanilla JavaScript · Google Sheets</td></tr><tr><td>Status</td><td>In production since the 2025/26 winter season</td></tr></tbody></table><hr /><h2 id="the-problem">The problem</h2><p>Families buy a season course in the school’s e-shop. That entitles each child to 8 lessons across a 12-weekend winter, chosen week by week, in up to three time slots (Friday afternoon, Saturday morning, Saturday afternoon). Bookings for a weekend close on Wednesday at midnight.</p><p>Before this app, all of this was tracked by hand: counting lessons per child, chasing late sign-ups, and avoiding double bookings — while many families register several siblings under one parent email.</p><hr /><h2 id="architecture">Architecture</h2>

    Parents use a custom domain served by a Flask web service on Railway, connected to PostgreSQL over Railway's private network. A one-off job imports enrolled students from the e-shop CSV. Staff read weekly attendance in Google Sheets through a token-protected JSON feed and can make admin overrides.<figcaption>Everything runs in one Railway project: the web service and PostgreSQL talk over the private network; staff work from Google Sheets.</figcaption>
    <hr /><h2 id="turning-course-rules-into-database-logic">Turning course rules into database logic</h2><p>Each business rule has one clear owner in the system, so it can’t be bypassed by a double click, a second browser tab or two parents booking at once.</p><table><thead><tr><th>Course rule</th><th>How it’s enforced</th></tr></thead><tbody><tr><td>One booking per child, weekend and time slot</td><td>UNIQUE (user_id, user_name, weekend_date, time_slot) on submissions — re-submitting updates the row instead of duplicating it</td></tr><tr><td>Max 8 lessons per child per season</td><td>Count of accepted “yes” bookings inside the season window, checked before every insert; each time slot counts as one lesson</td></tr><tr><td>Siblings share a parent’s email</td><td>A student is identified by email + name; the submitted name must match one of the students enrolled under that email</td></tr><tr><td>Only paying customers can book</td><td>Lookup against enrolled_students, imported from the e-shop export</td></tr><tr><td>Bookings close Wednesday 24:00</td><td>Cutoff = weekend date − 3 days, compared in the Europe/Prague time zone so daylight-saving changes don’t shift it</td></tr><tr><td>Staff can make exceptions</td><td>Token-protected admin override that skips quota and cutoff and records the reason in note</td></tr></tbody></table><h3 id="data-model">Data model</h3><p>Three tables (users, enrolled_students, submissions); Postgres enums mean an invalid time slot or status simply cannot be stored. The two core tables:</p><div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight">CREATE TABLE enrolled_students ( -- who bought the course id VARCHAR(255) PRIMARY KEY, -- deterministic hash of email + name email VARCHAR(255) NOT NULL, -- not unique: siblings share it jmeno VARCHAR(255) NOT NULL, prijmeni VARCHAR(255) NOT NULL, is_active BOOLEAN NOT NULL DEFAULT TRUE );

CREATE TABLE submissions ( – one row per child × weekend × slot id SERIAL PRIMARY KEY, user_id VARCHAR(255) NOT NULL REFERENCES users(user_id), user_name VARCHAR(255), weekend_date DATE NOT NULL, time_slot timeslotenum NOT NULL, – FRIDAY_1400 | SATURDAY_0815 | SATURDAY_1400 answer answerenum NOT NULL, – ANO | NE status statusenum NOT NULL, – ACCEPTED | REJECTED submitted_at TIMESTAMP DEFAULT now(), note TEXT, UNIQUE (user_id, user_name, weekend_date, time_slot) );

CREATE INDEX idx_weekend ON submissions (weekend_date); – weekly attendance lists CREATE INDEX idx_user ON submissions (user_id); – a family’s bookings CREATE INDEX idx_status_answer ON submissions (status, answer); – quota counts </code></pre></div></div><p>Cancellations aren’t deleted: the row flips to NE / REJECTED. That keeps a full history of what each family did and frees the lesson back into their quota automatically.</p><h3 id="preventing-race-conditions">Preventing race conditions</h3><p>The quota check is a classic read-then-write: count lessons, then insert. If two requests for the same family arrive together, both can read “7 used” and both insert, ending at 9.</p><p>Every booking therefore runs inside a PostgreSQL advisory lock keyed on the family’s email (pg_try_advisory_lock). Requests for the same family are serialised, while different families never wait for each other. If the lock isn’t free, the user gets a clear “try again” message instead of a wrong result.</p><hr /><h2 id="deployment-on-railway">Deployment on Railway</h2><ul><li>Deployed from GitHub with a Nixpacks build and Gunicorn as the production server (railway.json holds the start command, health check and restart policy).</li><li>App and database on Railway’s private network. The app prefers DATABASE_PRIVATE_URL and only falls back to the public URL, and normalises the postgres:// scheme Railway provides into what SQLAlchemy expects.</li><li>Resilient connections. A start-up check retries until Postgres is reachable; the connection pool uses pool_pre_ping and recycles connections every 30 minutes so idle drops don’t surface as errors.</li><li>Self-healing. A /health endpoint is used by Railway’s health check, and the service restarts automatically on failure.</li><li>Secrets only in environment variables. A setup script generates the keys, and the app refuses to start in production if any default secret is still in place.</li><li>Custom domain on the school’s own domain, with HSTS, a Content-Security-Policy and per-endpoint rate limits.</li></ul><h3 id="importing-customers-from-the-e-shop">Importing customers from the e-shop</h3><p>Enrolled students come from the e-shop’s CSV export. A one-off import runs inside Railway’s environment (railway run), so database credentials never leave the platform. Each student’s ID is a deterministic hash of email + name, which makes the import idempotent: running it again updates existing students instead of creating duplicates.</p><h3 id="attendance-in-google-sheets">Attendance in Google Sheets</h3><p>Instructors already work in Google Sheets, so instead of building an admin UI they had to learn, the app exposes token-protected JSON endpoints per weekend (attendance list and summary). The sheet pulls from them, so each weekend’s list is always current.</p><hr /><h2 id="what-id-improve-next">What I’d improve next</h2><ul><li>Schema migrations with Alembic instead of creating tables at start-up, so the schema can evolve safely between seasons.</li><li>Automated tests in CI for the quota, cutoff and sibling rules — the parts where a bug costs a family a lesson.</li><li>Season dates as configuration rather than constants in code, so a new season needs no deploy.</li><li>A deterministic lock ID (e.g. Postgres hashtext) so the per-family lock still holds if the service ever scales to several instances.</li></ul></section><footer class="page__meta"></footer><nav class="pagination"> Previous Next </nav></div></article></div></div><div class="page__footer"><footer> <footer class="page__footer"><div class="page__footer-follow"><ul class="social-icons"><li> GitHub</li></ul></div></footer></footer></div></body></html>

url: /portfolio/registration-system/ link: teaser: /images/registration_system.png

  • title: Annotation-Free Tree Crown Detection path: _portfolio/1_tree_detection.md output: <!doctype html><html lang="en" class="no-js"><head> Annotation-Free Tree Crown Detection Home </head><body> <div class="masthead"><div class="masthead__inner-wrap"><div class="masthead__menu"><nav id="site-nav" class="greedy-nav"> <ul class="visible-links"> <li class="masthead__menu-item masthead__menu-item--lg persist"> Home</li><li class="masthead__menu-item"> About</li><li class="masthead__menu-item"> Portfolio</li><li class="masthead__menu-item"> Gallery</li><li class="masthead__menu-item"> CV</li><li class="masthead__menu-item"> Blog</li><li class="masthead__menu-item"> Contact</li><li id="theme-toggle" class="masthead__menu-item persist tail"> </li></ul><ul class="hidden-links hidden"></ul></nav></div></div></div><div class="initial-content"><div id="main" role="main"><article class="page" itemscope itemtype="http://schema.org/CreativeWork"><div class="page__inner-wrap"><header><h1 class="page__title" itemprop="headline">Annotation-Free Tree Crown Detection</h1><p class="page__date"> Published: </p></header><section class="page__content" itemprop="text"><p>Open data only, no ground truth, single tree detection</p><p>This is the tree detection pipeline I built at the FBK Digital Commons Lab for project Talea. It finds individual tree crowns in orthophotos (plain RGB aerial images) from several Italian cities, without a single labelled tree needed for finetuning.</p><table><thead><tr><th> </th><th> </th></tr></thead><tbody><tr><td>Context</td><td>FBK Digital Commons Lab - project Talea, 2026</td></tr><tr><td>My role</td><td>Designed and built the detection pipeline end to end</td></tr><tr><td>Stack</td><td>Python · PyTorch · DeepForest · SAM2 · GDAL · rasterio · GeoPandas · DuckDB spatial</td></tr></tbody></table><hr /><h2 id="domain-specific-model--foundation-model">Domain-specific model + foundation model</h2><p>The pipeline combines two models that are each good at one thing:</p><ul><li>DeepForest is a domain-specific model: a RetinaNet detector pretrained on tree crowns. It knows what a tree is, so it finds almost all of them. However it also detect high number of FP - this depending on the context can be for example rooftops. Another common issue of DeepForest detection is high number of FN in dense area, thanks to the nature of detection outputs - bounding boxes.</li><li>SAM2 (Segment Anything Model 2) is a foundation model: general-purpose, never trained on tree labels. It doesn’t know what a tree is, but it knows where an object’s edge is.</li></ul><p>Put together, DeepForest decides where to look and SAM2 draws what’s really there. The crown outline SAM2 draws is then checked, and that’s where the false positives get filtered out. A rooftop can be outlined perfectly, but it isn’t green.</p><p>The principle: recall first, filters after. It’s easier to remove a wrong detection than to recover a tree that was never found.</p>

    Two stages, no training labels. Stage 1, detection: DeepForest, a domain-specific model, proposes a box for every possible tree, with high recall and some false positives. Stage 2, segmentation: SAM2, a foundation model, outlines the crown inside each box, and checks on that outline drop what isn't a tree. The output is one polygon per tree. Tree detection pipeline diagram, vertical layout <figcaption>Two stages, no training labels at any step. Click any box to open the code.</figcaption>
    <hr /><h2 id="stage-1-detection">Stage 1: Detection</h2>
    Aerial image of a residential area next to a wooded park, with red boxes around individual tree crowns<figcaption>DeepForest’s crown bounding boxes - detection over housing area, mix on TP and FP.</figcaption>
    <p>Each red box is a bounding box = output of DeepForest pretrained model - with no fine-tuning.</p><p>What to notice:</p><ul><li>True positives: almost all the trees are found, although in denser areas the boxes aren’t precise.</li><li>False positives: some rooftops are labelled as trees.</li></ul><p>That’s exactly what this stage should do: find everything, even at the cost of a few mistakes.</p><p>To make one detector work across cities, images are cut into patches that always cover the same ground area, whatever the camera resolution, so a tree looks the same size to the model in every city.</p><hr /><h2 id="stage-2-segmentation">Stage 2: Segmentation</h2>
    The same aerial image with yellow outlines tracing the irregular shape of each tree crown<figcaption>The same scene after SAM2: every box has become an outline of the actual crown.</figcaption>
    <p>Each box from stage 1 is given to SAM2 as a prompt, and SAM2 traces the crown inside it.</p><p>What changes compared to stage 1:</p><ul><li>Shapes follow the canopy. The outlines are irregular, like real crowns, instead of rectangles.</li><li>Shadows and background drop out. On the meadow trees, the outline hugs the crown rather than the shadow or the grass that a box also contains.</li><li>Touching crowns get separate outlines, so the dense centre becomes a mosaic of individual trees.</li></ul><p>Filtering the false positives. Because each detection now has a real outline, it can be checked:</p><ul><li>Is it green? A vegetation index over the crown. Rooftops, roads and shadows fail here.</li><li>Is it a plausible size? Outlines too small or too large for a single tree are dropped.</li><li>Is the shape sane? If SAM2 snapped to the wrong object, the original box is kept instead.</li></ul><p>To keep this fast at city scale, each image chip is encoded by SAM2 once, and all boxes in it reuse that encoding.</p><hr /><h2 id="why-not-fine-tune">Why not fine-tune?</h2>
    Two copies of the same aerial image of a park with houses. On the left, orange boxes from the pretrained DeepForest cover almost every tree. On the right, cyan boxes from the fine-tuned DeepForest cover far fewer trees and many boxes are very small.<figcaption>The same scene: pretrained DeepForest (left) vs. DeepForest fine-tuned on an OAM-TCD subset (right).</figcaption>
    <p>The obvious alternative is to fine-tune the detector on labelled trees, so I tested that. I fine-tuned DeepForest on a subset of OAM-TCD, an open tree crown dataset, and compared both models by manual validation in three cities:</p><table><thead><tr><th> </th><th>F1</th><th>Recall</th><th>Precision</th></tr></thead><tbody><tr><td>Pretrained DeepForest</td><td>83.5 %</td><td>89.7 %</td><td>78.0 %</td></tr><tr><td>Fine-tuned DeepForest</td><td>62.6 %</td><td>48.6 %</td><td>87.7 %</td></tr></tbody></table><p>The fine-tuned model is slightly more precise, but it misses half the trees. With recall at 48.6 %, F1 drops by more than 20 points. For a pipeline built on “recall first”, that’s the wrong trade.</p><p>The likely cause is domain shift: the training data isn’t the target data. OAM-TCD comes from different sensors, its images look different from Italian municipal orthophotos, and its labelling style is different too (some trees are labelled one by one, others as whole groups of canopy). Fine-tuning on data like that can also distort the good features the model learned in pretraining (Kumar et al., 2022).</p><p>Recall is measured against all trees found by either model, so it’s an upper bound. Only boxes were validated, not the SAM2 outlines.</p><hr /><h2 id="annotation-free-by-design">Annotation-free, by design</h2><p>Put together, the result is a pipeline that needs no labelled trees at any step:</p><ul><li>Open data only. Most cities publish RGB orthophotos, unlike LiDAR or tree inventories, so the pipeline can run almost anywhere.</li><li>No labels needed. Labelling trees is slow and expensive, and labels from elsewhere don’t transfer well, as the fine-tuning test shows.</li><li>Moves to a new city as it is. A new city only needs its orthophotos and a quick check of the filter thresholds, not a new training set.</li><li>Each tree becomes an object, an outline with its own shape and size, ready for any analysis that needs individual trees.</li></ul></section><footer class="page__meta"></footer><nav class="pagination"> Previous Next </nav></div></article></div></div><div class="page__footer"><footer> <footer class="page__footer"><div class="page__footer-follow"><ul class="social-icons"><li> GitHub</li></ul></div></footer></footer></div></body></html>

    url: /portfolio/singletree-detection/ link: teaser: /images/tree-detection-delineate.jpg