<?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 Sahar Darafsh on Medium]]></title>
        <description><![CDATA[Stories by Sahar Darafsh on Medium]]></description>
        <link>https://medium.com/@sdrfsh?source=rss-9e8d659bd5d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*An5XcozQJoU8jUqea-DP3A.png</url>
            <title>Stories by Sahar Darafsh on Medium</title>
            <link>https://medium.com/@sdrfsh?source=rss-9e8d659bd5d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:07:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdrfsh/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[My Vector Database Would Fall Asleep Between My Trips]]></title>
            <link>https://pub.towardsai.net/my-vector-database-would-fall-asleep-between-my-trips-65e61fc3cee9?source=rss-9e8d659bd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/65e61fc3cee9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sahar Darafsh]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 14:31:02 GMT</pubDate>
            <atom:updated>2026-11-18T14:31:02.055Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Choosing between pgvector and Qdrant for a travel planner with exactly one user, and the three Postgres weak spots I want fixed before I commit.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCweq3WE4hqzaTB5u_UKbA.png" /><figcaption>Image generated by AI</figcaption></figure><p>In my last article, my weekend <a href="https://pub.towardsai.net/my-travel-planner-decided-i-love-taxis-131e177af9c7">travel planner decided I love taxis</a>. One note about a taxi app in Sicily turned into a rule about me, and that was only one of eleven flaws the prototype showed me.</p><p>At the end, I promised a choice: pgvector or Qdrant. This is that choice.</p><p>The prototype kept my travel notes in Chroma, on my laptop. That was perfect for a weekend. But the rebuild needs a backend API and a website I can open on my phone in the middle of Porto. My laptop will be at home. So the notes need a home on a server, and the trips are already moving to Postgres.</p><p>Two candidates were left. Put the vectors into Postgres with pgvector, or give them their own database in Qdrant.</p><h3>The fact that decided most of it</h3><p>Let me be honest about my app’s traffic. 🙃</p><p>There’s one user: me. I travel a few times a year, not every week. Between trips, the planner can sit untouched for a month or more. And it’s a side project, so I don’t want to pay for any of it until it proves it’s worth it.</p><p>Qdrant has a free cloud plan, and it’s a good one for trying things out. But its documentation is clear about one rule. Your database there is called a cluster, and if a free cluster isn’t used for a week, it’s suspended. If nobody reactivates it, it’s deleted after four weeks.</p><p>Now picture my usage. Say I plan a trip, then don’t touch the app for six weeks. I open it at the airport… and my database is asleep. Or gone.</p><p>Postgres is a different story, because I need it anyway. The rebuild moves the trips there, and the places and plans will follow. Wherever that database runs, it has to be awake whenever I open the app, or the planner can’t even list my trips. So keeping it awake is a problem I have to solve once, no matter where the vectors go. With pgvector, the notes become one more table in that same database. No second service to keep awake, no second bill.</p><p>You might ask: why not run Qdrant myself, in Docker, next to Postgres? Qdrant is open source, so that would also be free. But it would be one more service to run, update and back up, for one user. With pgvector, the backups I already make for my trips cover the notes too.</p><p>So I’m leaning towards Postgres. But I’m choosing mostly on price, so I want to know what I lose. I listed the weaknesses of pgvector for my case, and I didn’t want to commit until each one had a fix.</p><p>To understand them, though, you need to know how the search finds a note in the first place.</p><h3>How the search finds a café</h3><p>pgvector can search in two ways. By default, it does an exact search: it compares my question with every note and returns the true closest ones. That’s perfect, and it’s also slow once there are millions of rows.</p><p>For speed, you add an index. The one I’ll use is HNSW, short for Hierarchical Navigable Small World. The name is a mouthful, but the idea is simple. When a note is saved, it gets linked to a few notes that are similar to it. Later, the search walks along those links instead of checking everything.</p><p>Here’s a small example. Say I have 1,000 travel notes, and some of them are linked like this:</p><ul><li>“Rooftop bar in Lisbon” ↔ “Viewpoint café in Porto” ↔ “Terrace café in Valletta”</li><li>“Castle in Heidelberg” ↔ “Fortress in Mdina”</li></ul><p>I ask: <em>“cozy café with a view”</em>.</p><ol><li>The search starts at some note, say “Castle in Heidelberg”. Not very close to my question.</li><li>It looks at that note’s links and jumps to the one that’s closer: “Rooftop bar in Lisbon”.</li><li>It jumps again, to “Viewpoint café in Porto”. Even closer.</li><li>None of the Porto note’s links is any closer, so it stops. Result: “Viewpoint café in Porto”. ✅</li></ol><p>It looked at around ten notes instead of a thousand.</p><p>That web of links is called a graph. The “hierarchical” part means the real graph has layers. Think of a road trip: you take the highway to reach the right region, then small streets to find the exact café. The top layer is the highway, with few notes and long jumps. The lower layers have more notes and short steps. The walk above is what happens on one layer.</p><p>And here’s the catch. If the perfect café note isn’t linked anywhere along that path, the walk never sees it. So HNSW is an approximate search: fast, and usually right, but not always.</p><h3>What about IVFFlat?</h3><p>pgvector has a second index, IVFFlat, and it’s the same kind of thing. Both are ANN indexes (approximate nearest neighbour): they skip most of the data to be fast, and accept that they might miss the very best match now and then.</p><p>They’re just built differently:</p><ul><li><strong>HNSW</strong> is a web of links between similar notes, and the search hops along them.</li><li><strong>IVFFlat</strong> sorts the notes into buckets of similar notes, and the search opens only the closest bucket or a few of them. By default, only one (ivfflat.probes = 1).</li></ul><p>The pgvector docs say HNSW gives better query performance, while IVFFlat builds faster and uses less memory. One more detail made it easy for me: IVFFlat learns its buckets from the data that’s already in the table, so it should be built after the data is there. HNSW has no such training step and can be created on an empty table. My notes will grow slowly, a trip at a time, so HNSW it is.</p><p>Now, the three weak spots.</p><h3>Weak spot 1: a filtered search can come back almost empty</h3><p><strong>Why.</strong> HNSW first collects a fixed number of candidates, and only then applies the WHERE clause. That number is hnsw.ef_search: how many candidates the search looks at, 40 by default. If only a few of those 40 match my filter, I get only a few results back, even when the table has plenty of matching rows that are just a little less similar to my question.</p><p>The pgvector README gives a sharp example: if a condition matches 10% of the rows, then with the default of 40, only about 4 rows will match on average. Ask for 5, get 4. Or fewer.</p><p>The easiest way I found to picture it is a cloakroom.</p><p>Ten thousand people hang their jackets in one huge cloakroom. You ask the attendant for “the 5 red jackets that are mine”.</p><p><strong>Without iterative scans,</strong> the attendant grabs the 40 reddest jackets in the whole room and checks the name tags. None of them are yours. They come back and say, “Sorry, nothing found.” Your red jackets are in there, they just weren’t among the 40 reddest.</p><p><strong>With iterative scans,</strong> the attendant grabs 40 jackets, finds none of yours, and grabs the next 40. They keep going until they’ve found 5 of yours, or until they hit a limit and give up. You get your jackets. ✅</p><p>What maps to what:</p><ul><li><strong>The jackets</strong> are the notes, stored as vectors.</li><li><strong>“Reddest”</strong> means closest in meaning to the question.</li><li><strong>The name tag</strong> is the user_id filter: only my notes, not other users&#39; notes.</li><li><strong>The 40</strong> is hnsw.ef_search.</li></ul><p>With only me in the app, every jacket is mine, so the user_id filter can’t cause this. But the verdict filter can. If I ask “What did I like in Vienna?”, the 40 closest notes might all be Vienna cafés I didn’t enjoy. And once a second person uses the app, user_id becomes a problem too.</p><p>To be fair, this doesn’t hurt me today. With a few dozen notes, 40 candidates is nearly the whole table, so nothing gets lost. The trouble starts when the table grows well past 40 rows and the filter matches only a small share of them. That’s exactly where a growing travel journal is heading.</p><p><strong>Fix.</strong> pgvector 0.8.0 added iterative index scans. One setting turns them on:</p><pre>SET hnsw.iterative_scan = relaxed_order;</pre><pre>SELECT id, title<br>FROM notes<br>WHERE user_id = 1<br>  AND verdict = &#39;loved&#39;<br>ORDER BY embedding &lt;=&gt; $1<br>LIMIT 5;</pre><p>Now, if too few rows pass the filter, the search fetches more. The limit from the cloakroom is real too: hnsw.max_scan_tuples stops the search after 20,000 rows by default.</p><p>There’s a second mode, strict_order, which keeps the results in exact order by distance. relaxed_order may mix up the order a little, but it finds more matches. If the order matters, you can sort the results again afterwards.</p><h3>Weak spot 2: search and the app share one database</h3><p><strong>Why.</strong> This is the price of keeping everything in one database. A heavy vector search uses the same CPU and RAM as “save trip” or “list places”. If searches get busy, the rest of the app can slow down, and the other way around.</p><p>For one person planning a few trips a year, I’m not worried today. But I’d like to know the way out before I need it.</p><p><strong>Fix.</strong> There are three steps, from small to big:</p><ol><li><strong>Send searches to a read replica.</strong> That’s a read-only copy of the database that stays in sync with the main one. Searches only read, so they can run there, and saving a trip on the main database doesn’t have to wait behind them.</li><li><strong>Give the database a bigger server.</strong> More CPU and RAM. Boring, but it works.</li><li><strong>Move the vectors to their own store later.</strong> If the first two aren’t enough, that’s the day a dedicated vector database earns its place. Qdrant is still on the list. Just not yet.</li></ol><h3>Weak spot 3: the results are approximate</h3><p><strong>Why.</strong> Remember the café walk? If the best note isn’t linked along the path, HNSW misses it. That’s the trade: a little accuracy for a lot of speed.</p><p><strong>Fix.</strong> Measure first, then tune.</p><p>The rebuild plans an evaluation set: my own questions, each with the notes that should come back. The metric is hit rate@5: how often the right note shows up in the top 5 results. If that number drops, I raise ef_search, so the search looks at more candidates:</p><pre>SET hnsw.ef_search = 100;</pre><p>More candidates means better results and slower queries. The eval set tells me where that trade stops paying off, so I’m not guessing.</p><h3>What Qdrant gives you out of the box</h3><p>Here’s what I’m really giving up. Qdrant and other dedicated vector databases have search features built in, and often you just switch them on. With pgvector, you write them yourself in SQL.</p><p>Two examples made this concrete for me.</p><p><strong>Filtering</strong>: In Qdrant, the extra data stored with each vector, like city or verdict, is called the payload. If you index a payload field, Qdrant applies the filter during the search, not after it. So the cloakroom problem from weak spot 1 doesn’t happen. For apps with many users, you can also mark user_id with is_tenant, and Qdrant keeps each user’s data together, so “only my notes” searches get faster.</p><p><strong>Hybrid search: </strong>Sometimes I search by meaning (“cozy café with a view”), and sometimes by name, like a specific bakery, where keywords work better. Hybrid search runs both and merges the results, often with Reciprocal Rank Fusion (RRF): a note scores higher the closer it is to the top of either list. In Qdrant, that’s a single request.</p><p>In Postgres, I write it myself. The first part below searches by meaning, the second by keywords, and the last part merges the two lists with RRF:</p><pre>-- tsv is a tsvector column with the note&#39;s text<br>WITH semantic AS (<br>  SELECT id, RANK() OVER (ORDER BY embedding &lt;=&gt; $1) AS rank<br>  FROM notes<br>  WHERE user_id = $2<br>  ORDER BY embedding &lt;=&gt; $1<br>  LIMIT 20<br>),<br>keyword AS (<br>  SELECT id, RANK() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS rank<br>  FROM notes, plainto_tsquery(&#39;english&#39;, $3) AS q<br>  WHERE user_id = $2 AND tsv @@ q<br>  ORDER BY ts_rank_cd(tsv, q) DESC<br>  LIMIT 20<br>)<br>SELECT COALESCE(s.id, k.id) AS id,<br>       COALESCE(1.0 / (60 + s.rank), 0)<br>     + COALESCE(1.0 / (60 + k.rank), 0) AS score<br>FROM semantic s<br>FULL OUTER JOIN keyword k ON s.id = k.id<br>ORDER BY score DESC<br>LIMIT 5;</pre><p>It works, and I understand every line of it. But it’s longer, it’s mine to test, and it’s mine to fix. That’s the real cost of pgvector: the queries take more effort to write.</p><h3>So, which one?</h3><p>pgvector, for now.</p><p>Not because it’s better at vector search. Qdrant is built for exactly this, and it shows. I’m choosing Postgres because of my situation: one user, rare trips, no budget, and a free Qdrant cluster that would fall asleep between my trips.</p><p>And each of the Postgres weak spots has a known fix:</p><ul><li><strong>Filters that come back short:</strong> hnsw.iterative_scan = relaxed_order</li><li><strong>One database doing two jobs:</strong> a read replica, then a bigger server, then a separate store</li><li><strong>Approximate results:</strong> hit rate@5 on my eval set, and a higher ef_search if needed</li></ul><p>I’ll switch to Qdrant when one of these happens: the searches slow down the app even after a replica, the app gets real users and keeping each user’s notes apart becomes the main kind of search, or I catch myself writing my third hand-made hybrid query. And once I’m paying anyway, the sleeping rule stops mattering, because it only applies to the free tier.</p><h3>Next stop: does the search even help?</h3><p>Choosing a database was the easy part. The bigger question is whether searching my notes makes the plans any better.</p><p>In the next article, I’ll build an evaluation set, use it to pick an embedding model, and find out if my notes beat Claude with no memory at all. 😅</p><p>Until then, my notes move into Postgres, right next to my trips. And unlike a free cluster, they’ll still be awake when I land in Porto.</p><p>Have you run vector search inside Postgres, or did you pick a dedicated vector database from the start? I’d love to hear what made you choose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65e61fc3cee9" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/my-vector-database-would-fall-asleep-between-my-trips-65e61fc3cee9">My Vector Database Would Fall Asleep Between My Trips</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Travel Planner Decided I Love Taxis]]></title>
            <link>https://pub.towardsai.net/my-travel-planner-decided-i-love-taxis-131e177af9c7?source=rss-9e8d659bd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/131e177af9c7</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sahar Darafsh]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 12:31:01 GMT</pubDate>
            <atom:updated>2026-11-16T12:31:01.762Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A weekend prototype of an MCP travel planner in Python (SQLite, local vector search, a planner prompt), and the 11 flaws it showed me.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdAdOI5rb_Ryq1_qSQJZng.png" /><figcaption>Image generated by AI</figcaption></figure><p>I’m going to Porto in May. So I tried every planning app I could find, and they all gave me the same lists, written for a visitor who isn’t me.</p><p>The things that really matter to me weren’t in any of them. Which cafés I loved in Sicily. Which museum in Vienna bored me. How much I like to fit into one day. None of it was written anywhere a program could read. It lived in my head and in my photo roll.</p><p>I also wanted to learn MCP and RAG properly, and the best way I know to learn something is to build a thing I’ll actually use. So the project became a planner that saves my trips, searches my own travel notes, and plans a day around what I like, with Claude as the interface.</p><p>I built the prototype over a weekend, in three parts. I’ll call them Day 1, 2 and 3 below, and each one adds a layer. And yes, by the end, it had decided I love taxis. We’ll get there.</p><h3>The whole thing on one screen</h3><p>There’s no web app yet. Claude Desktop is the whole interface. Everything else is one Python process plus two data stores on my laptop: SQLite for the trips and a local Chroma vector store for the notes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJuEoDhJ7bhGSvZUgn28CQ.png" /><figcaption>Chart generated by Excalidraw and author</figcaption></figure><p>Each day added one layer: the trip tools on Day 1, the notes search on Day 2, the profile and the planner prompt on Day 3.</p><p>All my personal data lives in one data/ folder that git ignores: the database, the notes, the vector store and the profile. One ignore rule covers all four, so none of my travel notes can end up in the repo by accident.</p><h3>Day 1: a server Claude can talk to</h3><p>This prototype only runs on my laptop, so I used stdio, the simplest transport. Claude Desktop starts my server as a child process. Claude writes requests to the server’s stdin, and the server writes its answers to stdout. Each message is one line of JSON-RPC.</p><p>That has one big side effect: stdout belongs to the protocol, and only to the protocol. Anything else written there gets parsed as a message, fails, and breaks the connection. Even a single forgotten print() could do it. So I used Python’s logging module to send all logs to stderr. Claude Desktop saves them in a log file for each server (%APPDATA%\Claude\logs\mcp-server-travel-planner.log on Windows), and that file is where I did most of my debugging.</p><h3>Old tutorials don’t run anymore</h3><p>If you’re following along, this one will save you some confusion. Most MCP tutorials I found begin with from mcp.server.fastmcp import FastMCP. With the current SDK, that line fails right away with ModuleNotFoundError. Version 2.0, released in July 2026, renamed the class to MCPServer:</p><pre>from mcp.server import MCPServer<br><br>mcp = MCPServer(&quot;travel-planner&quot;)</pre><p>So if an example breaks on the very first line, check which SDK version it was written for, before you start doubting yourself. 🙃</p><h3>The function signature is the API contract</h3><p>Here’s a nice shortcut: the code I write anyway is also the contract Claude reads. I didn’t write a single schema by hand. The SDK reads my Python function and builds the tool from it. The function name becomes the tool name, the docstring becomes its description, and the type hints become a JSON Schema for the arguments.</p><pre>@mcp.tool()<br>def create_trip(<br>    destination: str,<br>    start_date: str,  # YYYY-MM-DD<br>    end_date: str,<br>    travel_type: Literal[&quot;relaxed&quot;, &quot;packed&quot;] = &quot;relaxed&quot;,<br>    budget: int | None = None,<br>    currency: str = &quot;EUR&quot;,<br>) -&gt; dict:<br>    &quot;&quot;&quot;Save a new trip and return it exactly as stored.&quot;&quot;&quot;</pre><p>For the travel type I used Literal. In the schema it becomes an enum, so Claude sees the two allowed values before it ever calls the tool. The default shows up in the schema too.</p><p>The decorator registers the tool as soon as the module is imported. That’s why the mcp object and all the tools sit at the top level of the file. Inside a function, they would only be registered if that function ran, and Claude might never see them.</p><h3>Small data decisions with big effects</h3><p>These look like tiny details, but each one prevents a quiet bug.</p><ul><li><strong>Surrogate ids.</strong> Every trip gets an INTEGER PRIMARY KEY. Claude calls list_trips, copies the id and passes it to get_trip. That’s safer than asking it to retype the destination and date exactly and use them as the key.</li><li><strong>ISO dates as text.</strong> 2027-05-01 sorts correctly as plain text, so ORDER BY start_date works without a date type. 01.05.2027 would compare the day first and sort wrong. I’m not happy keeping dates as strings, but SQLite has no real date type, and for a prototype it’s enough. In the rebuild with Postgres, they’ll be proper DATE columns.</li><li><strong>Lists as JSON stored as text.</strong> Interests go in with json.dumps and come out with json.loads. If there are no interests, the column stays NULL. It doesn’t hold the text “null”, which is what json.dumps(None) would give, and which would look like real data.</li></ul><h3>Errors are messages to Claude</h3><p>This one changed how I think about errors. When a tool fails, Claude reads the error as the tool’s answer, and then decides what to do next. So I wrote my errors as next steps:</p><pre>No trip with id 7. Run list_trips and find the correct trip_id.</pre><p>The tool name in the message has to match the real tool exactly, or the hint sends Claude to a tool that doesn’t exist. Having no trips is a different case, and it isn’t an error at all. list_trips just returns [], because “no trips yet” is a valid answer.</p><h3>Testing before Claude</h3><p>Before connecting the server to Claude Desktop, I tested all three tools in the MCP Inspector (npx @modelcontextprotocol/inspector), including the not-found error.</p><p>At the end of Day 1, I created a packed Porto trip, with food and viewpoints as interests, just by writing a chat message. No form to fill in: I described the trip in normal words, and Claude turned it into a create_trip call with the right arguments. list_trips returned all my trips, sorted by start date. Claude could now save and read my trips. Next, it had to learn what I actually like.</p><h3>Day 2: search over my own notes</h3><p>This is the RAG part: find the notes that fit a question, then let Claude write the answer from them. First, though, the notes had to exist.</p><h3>Writing the memory down</h3><p>I wrote notes for three past trips. My first drafts were messy. They still had template placeholders like “Some Viewpoint” and “Café Example”, and some sections described three places at once.</p><p>The final format is one Markdown file per trip. The front matter describes the trip, and every place gets its own ## section with the same fixed fields (sample data):</p><pre>---<br>trip: Vienna 2025<br>city: Vienna<br>country: Austria<br>travel_type: relaxed<br>---<br><br>## Café Lindenhof<br>type: cafe<br>city: Vienna<br>verdict: loved<br>rating: 5<br>why: Quiet in the morning, good strudel.<br>tip: Sit in the back room.</pre><p>type and verdict use closed lists (loved, liked, disliked, hated for the verdict), so they can work as filters later.</p><h3>Chunking: one place, one vector</h3><p>The pipeline is simple: an ingest script reads the Markdown notes, splits them into chunks, embeds them and stores them in Chroma. It splits each file at the ## headings, so one chunk is one place. A chunk’s text is the heading plus its fields. Its metadata is the front matter, the source file and the section name. Three notes gave 14 chunks.</p><p>I rejected two other options:</p><ul><li><strong>One vector per file.</strong> The embedding model reads about 256 tokens and cuts off the rest. Even within that limit, one vector for five places is an average that matches none of them well.</li><li><strong>Fixed-size windows with overlap.</strong> They cut a place in half, and half a place is a poor source to cite.</li></ul><p>Ingestion is its own script, and I run it whenever the notes change. The server only reads from the store and never re-chunks on startup.</p><h3>Ids that survive a re-run</h3><p>Every time the ingest script runs, it has to recognize which chunk is which, so it updates the old ones instead of adding copies. That all depends on the ids.</p><p>Each chunk id is the file stem plus a slug of the heading, for example vienna-2025#cafe-lindenhof. Same note, same id, so upsert updates the chunk in place. The other options all break somewhere:</p><ul><li>Random UUIDs are new on every run, so every run would add duplicates.</li><li>List positions shift as soon as I add a place.</li><li>A content hash changes with every edit.</li></ul><p>upsert never deletes, though. If I rename a heading, the old chunk stays behind, and the search can then cite a place that is no longer in my notes. So before each ingest run, a set difference finds those orphans:</p><pre>existing = set(collection.get(include=[])[&quot;ids&quot;])<br>current = {chunk[&quot;id&quot;] for chunk in chunks}<br>orphans = sorted(existing - current)<br>if orphans:<br>    collection.delete(ids=orphans)</pre><p>There’s a trap hidden in that code. If chunks were ever empty, every stored id would count as an orphan, and the whole store would be wiped. So the loader raises an error when the notes folder is missing or has no .md files.</p><p>Two type problems came up as well. YAML turns an unquoted date into a Python date, but Chroma metadata only accepts str, int, float and bool. So a small converter turns dates into ISO strings, joins lists with commas and drops None.</p><p>The last surprise was invisible. Some editors save a byte order mark at the start of the file, and then the front matter is silently not found. Reading the files with encoding=”utf-8-sig” fixed it.</p><h3>The bug that showed me what gets embedded</h3><p>Finally, the real test. I asked Claude, “What did I love in Sicily?”</p><p>The results were notes from Vienna. 🤦🏻‍♀️</p><p>It took me a moment to see why. The country was only in the front matter, which Chroma stores as metadata. But only the chunk text goes through the embedding model. So for the vector search, my Sicily cafés were just cafés.</p><p>The fix was a Country: line in the text of every chunk, built once per file from the front matter. It took three tries. My first version wrote the literal text {country} into every chunk. A quick fix would have written None for notes without a country, and Python list syntax like [‘Italy’] when the country is a list (some trips cover more than one country). The final version joins lists with a comma and skips the line when the country is missing.</p><h3>Topic is easy, opinion is hard</h3><p>Next question: “What did I like in Vienna?” It returned every Vienna chunk, with L2 distances between 0.70 and 0.81 (lower means closer). There was no gap between what I liked and what I didn’t. The ## Overall chunk is the one section of a note that isn’t about a single place. It scored weakest of all, at 0.965, because its text named no place.</p><p>The embedding captures what a text is about much better than how I felt about it. A Vienna café I loved and a Vienna café I didn’t like end up almost in the same spot.</p><p>The answer was still right, because Claude read the verdict and rating lines in the results and sorted them itself. For the rebuild, “what did I like” becomes a metadata filter on verdict, and the vectors only handle the topic.</p><h3>The tool around it</h3><p>search_my_travel_memory returns a list of dicts with id, text, source, section, city and the distance rounded to three decimals. source and section are what Claude cites, so I can check where an answer came from. The docstring tells Claude when to use the tool, that a lower distance means a closer match, and to say so when nothing relevant comes back.</p><p>An empty store raises an error telling Claude that the ingest script needs to run. Why not just return an empty list? Because an empty list would read as “you have no relevant memories”, and Claude would answer as if that were true.</p><p>In Claude Desktop, Claude picked the number of results on its own (8). It also handled my typo “Sicly” without any help. 😁</p><p>So Claude could save my trips and search my memories. The last step was turning all of that into an actual plan.</p><h3>Day 3: the planner</h3><p>MCP gives a server three ways to expose things. The difference is who decides when they get used:</p><ul><li><strong>Tool:</strong> the model decides, during the conversation. In this project: create_trip, get_trip, list_trips, search_my_travel_memory.</li><li><strong>Resource:</strong> the app or the user attaches it as context. In this project: profile://me, my preference profile.</li><li><strong>Prompt:</strong> the user picks it from a menu. In this project: plan_day.</li></ul><h3>Profile as a resource</h3><p>data/profile.json holds my defaults, the things that rarely change: pace, when my day starts and ends, a fallback budget, food I like and avoid, interests, and things to skip. The server reads the file on every call, so my edits apply without a restart.</p><p>When a trip and the profile disagree, the trip wins. My profile says relaxed, the Porto trip says packed, and the plan came out packed.</p><h3>plan_day as a prompt</h3><p>In Claude Desktop, I pick plan_day from the prompt menu and fill in two arguments: trip_id and day. The server loads the trip through get_trip, reads the profile, and puts both into the prompt text. The memory search, on the other hand, stays a tool, so Claude decides what to look up while it plans, instead of me guessing in advance which notes matter. I checked that it really called search_my_travel_memory during planning.</p><p>The prompt also asks for a source tag on every reason, so I can see where each idea came from (sample output):</p><pre>- Morning: a quiet café before sightseeing   [memory: vienna-2025#cafe-lindenhof]<br>- Lunch: grilled fish, skip the set menus     [profile]<br>- Evening: sunset from a viewpoint            [general knowledge]</pre><h3>Reading the plans closely</h3><p>I ran the prompt twice: once for a day that turned out to fall outside the trip’s dates, and once for day 2. Both plans looked good at first glance. On a careful read, they had problems. These are the ones that stood out:</p><ul><li><strong>A day outside the trip.</strong> Claude noticed that this day wasn’t part of the trip and said so. Then it planned day 1 anyway, without asking me.</li><li><strong>A local fact became a rule about me.</strong> My Sicily note says a taxi app was easier there. For Porto, the planner concluded that I prefer taxis. And that’s how my travel planner decided I love taxis. 🚕</li><li><strong>Over budget.</strong> The plan’s own estimate was above the daily budget I had set.</li><li><strong>Missing context.</strong> It ignored the hotel breakfast and guessed the travel time between stops. Opening hours and prices all said “check”.</li><li><strong>The wrong shape.</strong> It gave me an hour-by-hour timetable. That’s not how I travel. I travel with a list of options grouped by area, with a note on how to get there.</li><li><strong>Gone after the chat.</strong> The plan wasn’t saved anywhere.</li></ul><h3>Eleven flaws, four causes</h3><p>I wrote down every flaw I found in the plans. There were 11, and they all came from just four causes:</p><ol><li><strong>Missing data.</strong> The planner didn’t know my hotel includes breakfast, so it ignored it.</li><li><strong>Missing tools.</strong> It had no way to check travel times or opening hours, so it guessed.</li><li><strong>The model doing code’s job.</strong> It went over my budget because nothing calculated the prices.</li><li><strong>One trip turned into a rule.</strong> A taxi app was easier in Sicily, so it decided I prefer taxis everywhere.</li></ol><p>The third cause changed my plan the most. Checking a budget or a date is a job for code, not for a language model. Code does the same math the same way every time, while a model writes what a good answer would probably look like. So in the rebuild, code makes those decisions and Claude explains them.</p><p>For the fourth cause, I now separate two kinds of memory:</p><ul><li><strong>What happened on one trip:</strong> “In Sicily, the taxi app was easier than the bus.”</li><li><strong>What is true for me:</strong> “I take a taxi when public transport is bad.”</li></ul><p>A trip memory only becomes a preference if it happens again on another trip, or if I say so myself.</p><h3>What I’m taking into the rebuild</h3><ul><li><strong>The environment costs more time than the code.</strong> Encodings, relative paths, environment variables and config reloads took longer than writing any of the tools.</li><li><strong>Know what gets embedded.</strong> Metadata filters results, and only the text decides similarity. Anything the search should match on has to be in the text. Sicily taught me that one.</li><li><strong>Read the output like a reviewer.</strong> Both plans looked fine at first glance. The flaws only showed up when I went through them line by line.</li><li><strong>One experience is thin evidence.</strong> My planner turned one note about one city into a rule about me. People do the same with places and with each other, and building this made me notice it.</li></ul><h3>What’s next?</h3><p>The prototype is done, and it did its job: it showed me where things break. Now I’m rebuilding it properly, keeping the parts that held up, in this order:</p><ol><li>Project structure, a linter and a formatter</li><li>Tests for the tools and the ingest logic, plus input validation</li><li>A proper schema for places, hotels and itineraries</li><li>RAG with an evaluation set: hit rate at 5 on my own questions, compared against Claude with no memory at all. If the search doesn’t beat that baseline, I’ll drop it.</li><li>A backend API and a website I can use on my phone</li><li>A planner where code scores and ranks the options, and Claude explains the result</li></ol><p>Later articles will cover the evaluation set and the choice between pgvector and Qdrant.</p><p>The Porto trip is still in May. By then, I’d like to plan it with my own notes instead of other people’s lists, and without a taxi waiting for me on every corner! 😄</p><p>If you’ve built an MCP server or a RAG setup on personal data, which part gave you the most trouble?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=131e177af9c7" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/my-travel-planner-decided-i-love-taxis-131e177af9c7">My Travel Planner Decided I Love Taxis</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Hard Can It Be? Teaching AI to Read My Daily Journal]]></title>
            <link>https://sdrfsh.medium.com/how-hard-can-it-be-teaching-ai-to-read-my-daily-journal-2c93c0f66912?source=rss-9e8d659bd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c93c0f66912</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sahar Darafsh]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 09:25:13 GMT</pubDate>
            <atom:updated>2026-10-05T09:25:13.339Z</atom:updated>
            <content:encoded><![CDATA[<p>A few weeks ago I sat down with my old journals, just to read this time.</p><p>Some pages were full of exclamation marks! Some were three lines long, and I could feel how tired I was when I wrote them. Good weeks, bad weeks, and a lot of very ordinary Tuesdays in between. It was like watching my own life on fast forward, all the ups and downs in one sitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmrKIoTUETMdO5ewJoHDiQ.jpeg" /></figure><p>And then the engineer in me asked, &quot;What if I could see all of this as a curve?&quot;</p><p>I’m not a painter or a poet. When I want to understand something, I write code. So I decided to read my journals in the only language I really think in!</p><p>The plan? Let the computer read each day and tell me: was it good, neutral or bad?</p><h3>How hard can it be?</h3><p>My first plan fit on a sticky note:</p><ol><li>Read the journal.</li><li>Split it into days.</li><li>Give each day a label.</li></ol><p>That’s it. A weekend project, maybe less. 😌</p><p>Steps 1 and 2 went fine. My entries live in two formats, some as web pages and some as plain text notes, so I turned the notes into web pages too and read everything the same way. One reader, done!</p><p>Then came the first surprise. I don’t only write in English. A big part of my journal is in Persian. It’s written from right to left, with an alphabet close to the Arabic one, and on a computer it gets messy in ways you’d never notice by eye:</p><ul><li><strong>Letters with twins.</strong> A few Persian letters have Arabic versions that look the same on screen but are completely different characters for a computer. Imagine half your keyboards typing a Latin “a” and the other half a Cyrillic “а”. You’d never see it, but a model would think they’re two different words.</li><li><strong>The half space.</strong> Persian has an invisible character (the zero-width non-joiner, or ZWNJ), a space that isn’t really a space. It keeps parts of one word close together without joining them. People often type a normal space instead, so one word becomes two, like “notebook” turning into “note book”.</li><li><strong>Optional marks.</strong> Small marks for short vowels show up in some places and not in others, a bit like writing “café” on Monday and “cafe” on Tuesday.</li></ul><p>So before any model could read a single word, I wrote a small cleaner that fixes all three. Now every entry looks the same to the models, no matter which keyboard or app I wrote it on.</p><p>Okay, I thought, the hard part is done. Now I just need a model.</p><h3>I opened a door and found a whole new world</h3><p>I went to Hugging Face to find “the sentiment model”.</p><p>There isn’t one. There are thousands! 😨</p><p>Models trained on tweets, on movie reviews, and on product reviews. Models that only speak English, models that speak a hundred languages, and models that were never trained on sentiment at all but can still do it.</p><p>This was the moment it stopped looking easy.</p><p>So I picked three models that think in three completely different ways:</p><ul><li><strong>The sentence matcher</strong> (zero-shot NLI). This one was never taught what a good day is. It reads my entry and checks which sentence fits it best: “This day was good,&quot; “This day was neutral,&quot; or “This day was bad.” Change one sentence, and the same model does a whole new job. I loved this idea!</li><li><strong>The tweet reader</strong> (XLM-RoBERTa). A classic sentiment model, trained on tweets in many languages. It says positive, neutral, or negative, and I just translated that to good, neutral, and bad.</li><li><strong>The storyteller</strong> (a local LLM). The same kind of AI that powers chatbots, but small enough to run on my laptop. I explain what each label means, ask it to judge the day as a whole, and it answers with a label, a score from 1 to 10 and one sentence about why. And since these are my journals, nothing leaves my laptop. Not a single word goes to anybody’s cloud.</li></ul><p>Then I gave them a small journal of five days, each one a little tricky on purpose.</p><ul><li><strong>Monday:</strong> a promotion and dinner with friends. Expected good. All three said good. ✅</li><li><strong>Tuesday:</strong> office, emails, pasta, one episode of a series. Expected neutral. All three said neutral. ✅</li><li><strong>Wednesday:</strong> a headache, a missed deadline and an argument with a friend. Expected bad. All three said bad. ✅</li><li><strong>Thursday:</strong> missed the bus, got soaked in the rain, then gave a great presentation and had a long call with Mom. Expected good. The tweet reader said bad. ❌</li><li><strong>Friday:</strong> VPN down, printer jammed, stress all day, but every single task finished. I was a little proud, but still, it could have been better. Expected neutral. The sentence matcher and the tweet reader both said bad. ❌</li></ul><p>Thursday is my favorite. The morning was a disaster, the rest of the day was lovely. The tweet reader saw “disaster”, “missed” and “soaked” and decided it was a bad day. Well… it was trained on tweets, and a tweet is one mood in one moment. A day is not a tweet!</p><p>Friday was hard for everyone except the storyteller. The sentence matcher said bad with 99.7% confidence. Very sure, and very wrong!</p><p>Only the storyteller read until the end, where I’m on the sofa with a cup of tea, a little proud that I finished everything. And its reason for Thursday was exactly what I would say myself: <em>“The day started badly but ended positively.”</em></p><p>Final score: storyteller 5/5, sentence matcher 4/5, tweet reader 3/5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*060qMFeKcaiuevbVN1GucA.jpeg" /></figure><h3>My laptop vs. three AI models</h3><p>All of this started as a quick experiment. But I didn’t want an experiment, I wanted a tool. Give it a journal, pick the models, and get back a table with one row per day.</p><p>Then I got curious about something else: what does each model cost to run?</p><p>My laptop is not a gaming machine. It has a small graphics card, the kind that’s mostly there for the screen. AI models love graphics cards, so I wanted to see if mine could help at all.</p><p>But wait… how do you even get an AI model onto a graphics card?</p><p>The sentence matcher and the tweet reader both run on PyTorch, the library that does the heavy math behind them. And here’s the catch: the PyTorch you get with a normal pip install torch on Windows only knows how to use the processor. To use an NVIDIA card, you need a special build made with CUDA, NVIDIA’s toolkit for doing math on the graphics card.</p><p>So I installed that, and PyTorch finally saw my card: a small GeForce MX250 with only 2 GB of memory.</p><p>A few more things I learned on the way:</p><ul><li><strong>pip won’t swap PyTorch for you.</strong> If the processor version is already installed, pip sees “torch is already there” and moves on. So I wrote a small install script that checks for an NVIDIA card, removes the wrong PyTorch if needed, and installs the right one.</li><li><strong>Found the card, now what?</strong> Just because PyTorch can find a card doesn’t mean it can use it. So my code double checks before loading a model. If this card isn’t supported, it shows a warning and switches to the processor, without crashing.</li><li><strong>2 GB is tiny.</strong> After each model finishes, I delete it and ask PyTorch to give the memory back, so the next model has room.</li><li><strong>The storyteller plays by its own rules.</strong> It doesn’t use PyTorch at all. It runs inside Ollama, which finds the graphics card by itself. Keeping it on the processor is just one setting.</li></ul><p>So, did my little graphics card actually help? Sometimes! 😅</p><ul><li><strong>The sentence matcher:</strong> about 70 seconds on the processor, 20 to 40 seconds on the graphics card. Two to three times faster!</li><li><strong>The tweet reader:</strong> 4 to 8 seconds on the processor, 6 to 14 seconds on the graphics card. Slower! This model is small and quick, so most of its time goes into loading, and copying it onto the graphics card is extra work. With only five days to read, the graphics card never had a chance to win that time back.</li><li><strong>The storyteller: </strong>here the size of the model mattered more than the card. The bigger version took one and a half to two minutes. A version about five times smaller took 25 to 30 seconds on the processor, and it still got all five days right! Even the small one didn’t fully fit in 2 GB, so Ollama put about half of it on the graphics card and half on the processor. That landed around 30 seconds too. Half in, half out didn’t buy me much.</li></ul><p>And the computer fooled me a few times along the way. Once the storyteller “finished” in two seconds. Too good to be true… and it was. It had crashed before reading a single day. 🤦🏻‍♀️ Another time I asked for the graphics card, and it quietly kept using an old copy it had loaded on the processor.</p><p>These bugs don’t crash anything. They just make your numbers lie. So I brought in MLflow, a tool that keeps a diary for experiments. Yes, a diary for my diary project. 😄 Every single run goes in: which model, where it really ran, how long it took, how much memory it used, and how many days it got right. Now I compare runs side by side instead of trusting my memory!</p><h3>One question, one answer</h3><p>A program on my laptop is nice, but I wanted my days rated from anywhere: my journal app, a small script, maybe a future project.</p><p>So I turned it into a service. It just waits for one question, “here is a day, how was it?”, and answers with one word: good, neutral or bad.</p><p>I wrote that question and answer down as a gRPC contract, one proto file that says exactly what you can send and what you get back. From that file, the code for talking to the service is generated automatically in two programming languages and published with every new version. So the service and everything that talks to it always speak the same language.</p><p>A few things I’m happy with:</p><ul><li>It loads a model only the first time someone asks for it, then keeps it ready for the next question.</li><li>It keeps track of how fast it answers and how many good, neutral and bad days it has seen, all in the same MLflow diary. But it never, ever stores what I wrote.</li><li>If something goes wrong, like an empty entry, it says so clearly instead of crashing.</li></ul><p>In the end, everything goes into a container, a packed box with the code, the settings and everything else it needs, so it runs the same way on my laptop and on a server.</p><p>First line of code on a Friday. A running service by Sunday night. Not bad for “how hard can it be?” 😁</p><h3>What three models taught me about my days</h3><p>I started this to see my life as a curve. I ended up with a few lessons that aren’t really about code.</p><p><strong>A bad morning is not a bad day.</strong> That Thursday stayed with me. When I read my old journals, I also judged some days by their worst moment. Exactly like the tweet reader. The model that read until the end got it right.</p><p><strong>The middle is the hardest part.</strong> Every model was sure about the promotion day and the headache day. The trouble was always in between: busy, stressful, but fine in the end. And honestly, most of life happens there.</p><p><strong>A score can’t tell a story. </strong>“8 out of 10” means nothing to me a month later. “Started badly but ended positively” does! I remember that Thursday the moment I read it.</p><h3>What’s next?</h3><p>Now comes the part I started with: running it over all my entries and finally drawing that curve. I also want a bigger test set, especially in Persian, because five days is not enough! And I’m curious how a small model trained just for this would compare to the storyteller.</p><p>I thought I was writing a script to sort my days into three boxes. Instead, I opened a door to a whole new world, and I’m still walking around in it!</p><p>Now… my days have labels, a gRPC contract, and a container. Next, they get a curve! 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c93c0f66912" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Thesis Code to pip install: How I Turned One Preprocessing Trick Into a Python Package]]></title>
            <link>https://sdrfsh.medium.com/from-thesis-code-to-pip-install-how-i-turned-one-preprocessing-trick-into-a-python-package-669dcdf966eb?source=rss-9e8d659bd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/669dcdf966eb</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Sahar Darafsh]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 09:25:01 GMT</pubDate>
            <atom:updated>2026-09-14T09:25:01.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUdfWlQQXGDQ-aDSalACYQ.jpeg" /></figure><p>Last time I showed you the inside of <a href="https://medium.com/@sdrfsh/from-mystery-box-to-neural-network-how-i-built-a-real-time-intention-recognition-system-f26faa35af25">my mystery box:</a> a real-time activity and intention recognition system, built from videos I recorded from my balcony with a camera taped to a hole punch.</p><p>The part everyone asked about wasn’t the CNN. It was the preprocessing.</p><p>Remember the trick? A whole video turns into one grayscale image. Old frames come out dark, and new frames come out bright, so you can see where someone went and how fast, all in a single picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*9t7nMnz53_7AldXLlZGocw.jpeg" /></figure><p>So I went back to <a href="https://github.com/sdrfsh/realtime-activity-and-intention-recognition">my thesis repo</a> to copy that part out for a new project.</p><p>And I couldn’t. 🙃</p><h3>The code was a hostage</h3><p>It wasn’t a preprocessing step. It was three hundred lines glued to <em>my</em> dataset, <em>my</em> frame size, and <em>my</em> folder structure, sitting in the middle of a training script. To reuse it, I’d have to reuse the whole thesis.</p><p>That’s when it hit me: an idea that only runs on the machine of the person who had it isn’t really an idea. It’s a souvenir.</p><p>I wanted to be able to type this:</p><pre>pip install adaptive-motion-preprocessing</pre><p>…and get the trick, without the thesis attached.</p><h3>Breaking one big function into stages</h3><p>The first thing I did was stop thinking “script” and start thinking “pipeline.” I sat down and asked what actually happens to a frame, in order:</p><ol><li><strong>Noise reducer</strong>, cleans the sensor noise (median filter)</li><li><strong>Background subtractor</strong>, separates what moves from what doesn’t (KNN)</li><li><strong>Motion trigger</strong>, decides whether anything is happening right now</li><li><strong>Window collector</strong>, gathers frames into windows of 10 while motion lasts</li><li><strong>Adaptive sampler</strong>, picks 4 of those 10 frames</li><li><strong>Motion history encoder</strong>, paints them into one image, old dim, new bright</li></ol><p>Six small classes instead of one big function. Each one has a single job and checks its own settings, so nothing needs to know what the others are doing. Two of them are yours to replace if you want: the noise reducer and the background subtractor. Write your own, pass it in, and the rest of the pipeline carries on as usual.</p><pre>import cv2<br>import numpy as np<br><br>from amprep import AdaptiveMotionPreprocessor<br><br><br>def rolling_ball(frames=40, height=240, width=320):<br>    &quot;&quot;&quot;A tiny fake video: a white ball rolling across a dark background.&quot;&quot;&quot;<br>    for i in range(frames):<br>        frame = np.full((height, width, 3), 60, np.uint8)<br>        if i &gt;= 10:  # empty frames first, so the background can be learned<br>            x = 30 + (i - 10) * 9<br>            cv2.circle(frame, (x, height // 2), 25, (255, 255, 255), -1)<br>        yield frame<br><br><br>preprocessor = AdaptiveMotionPreprocessor()<br><br>for n, image in enumerate(preprocessor.process(rolling_ball())):<br>    print(f&quot;motion image {n}: shape={image.data.shape}, frames={image.frame_indices}&quot;)<br>    cv2.imwrite(f&quot;motion_{n}.png&quot;, image.data)</pre><p>That’s it. Frames in, motion images out.</p><h3>Every old decision got a second interview</h3><p>Once each choice was sitting alone in its own little class, with nothing to hide behind, I could finally see what I had actually decided back then. And I started arguing with my past self.</p><p>In the thesis, every choice had exactly one judge: <em>does it work on my dataset?</em> A package has to survive other people’s cameras, other people’s machines, and other people’s frame rates. So I made each old decision defend itself again. Two of them lost.</p><p>The first was noise reduction. This stage runs on <strong>every single frame</strong>, before anything else does. If the cleanup is slow, the whole pipeline is slow, and a real-time system whose preprocessing can’t keep up with the camera is just a slow system with big dreams.😅</p><p>So I went with a median filter. It’s fast, so preprocessing never slows the system down. It also removes the tiny specks that make the background subtractor think something moved, and it keeps edges sharp for the next stage. I picked it for speed, but it turned out to be the better choice anyway!</p><h3>The “adaptive” part (and why I didn’t have it before)</h3><p>The second decision I overturned was sampling.</p><p>In my thesis, I sampled frames evenly. Take every third frame, done. It worked… as long as everyone walked like the people in my dataset. Not everyone does.</p><p>Here’s the problem. Sample a slow scene too tightly, and you get four nearly identical frames, a picture of nothing happening. Sample a fast scene across a whole window and the subject teleports between frames, a picture of motion that never happened.</p><p>When something moves fast, every frame counts. The interesting part of the movement is packed into a fraction of a second, and if your samples are spread far apart, you throw most of it away and keep the leftovers. So the faster the subject moves, the closer together the samples should sit.</p><p>So I let the speed decide the spacing:</p><pre>window of 10:   0 1 2 3 4 5 6 7 8 9<br><br>slow motion     X . . X . . X . . X    spread across the window<br>fast motion     . . . . . . X X X X    packed at the newest frames</pre><p>And how do I know the speed? From the masks themselves. A mask already <em>is</em> “what is moving,” so the share of it that changes between one frame and the next is a rate of change. <strong>No optical flow, no extra model.</strong></p><p>What doesn’t change is how many frames I keep. Always 4, so every image has the same shape and the model never gets a surprise.</p><h3>The question I kept flip-flopping on</h3><p>Who opens the camera?</p><p>I went back and forth on this for days. It would be <em>so</em> convenient to accept a file path and handle the video reading inside the package. One line for the user!</p><p>But then the package owns a device handle. It has to decide how to release it, what happens on a crash, what happens with a webcam versus a file versus an RTSP stream. And every one of those decisions would be mine, made badly, in someone else’s project.</p><p>So: <strong>the package does no video I/O at all. </strong>You pass frames, it takes them one at a time, and it never holds the whole thing in memory.</p><p>Nothing in there owns a device handle, so nothing in there can leak one. Four lines of cv2.VideoCapture live in the README instead, where you can read them and change them. 🙂</p><p>And that’s 1.0.0. I stopped tweaking it because more opinions will help more than more of mine will. Try it on your own video and tell me what breaks.</p><h3>Want to see it move?</h3><p>The nicest way to understand what this does is to watch it happen to your own face:</p><pre>git clone https://github.com/sdrfsh/adaptive-motion-preprocessing<br>cd adaptive-motion-preprocessing<br>pip install -e .<br>python examples/live_camera.py</pre><p>Stay out of the shot for a second while it learns the background, then move. You’ll see your camera on one side and your motion trail on the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*EwhNOnkuISe9YSf6cTQWYQ.gif" /></figure><p>The mystery box had one good idea in it. Now it’s pip install-able!</p><p>🔗 <a href="https://pypi.org/project/adaptive-motion-preprocessing/"><strong>PyPI</strong></a> · 🔗 <a href="https://github.com/sdrfsh/adaptive-motion-preprocessing"><strong>GitHub</strong></a></p><p>Issues and opinions are very welcome, especially the ones that tell me the defaults are wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669dcdf966eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Mystery Box to Neural Network: How I Built a Real-Time Intention Recognition System]]></title>
            <link>https://sdrfsh.medium.com/from-mystery-box-to-neural-network-how-i-built-a-real-time-intention-recognition-system-f26faa35af25?source=rss-9e8d659bd5d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26faa35af25</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Sahar Darafsh]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 19:31:29 GMT</pubDate>
            <atom:updated>2026-08-07T19:31:29.847Z</atom:updated>
            <content:encoded><![CDATA[<p>I stepped into computer engineering to create things on my own and continued into artificial intelligence to make them smarter!</p><p>But let me tell you how it actually felt!</p><p>The day I chose my thesis topic as “Real-time activity and intention recognition system,&quot; it all seemed so new and exciting. But as the days went by, I found myself reading more and more papers without understanding a single word… It was total chaos!🤦🏻‍♀️So…</p><p>I considered my system a mystery box, with no pressure to be creative!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYMHHt0ZXEjWUavWNnMGfA.png" /></figure><p>The first thing to consider was input. What are the inputs? How should they be?<br>I wrote down the specifications in detail… camera angle, people&#39;s behavior, picture noises, different lighting, and more!</p><p>I started searching through public datasets to find one that met my needs. The result? NO DATASET FOUND! 😨 Panic started to set in.</p><p>But wait… I can just create my own dataset!</p><p>I couldn&#39;t install a monitoring camera (CCTV camera) in public places, so I actually used a hole punch as a camera stand. I taped the camera to it and recorded people walking on the sidewalk from my balcony.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqjFBmzWTzpa0GurA4f1_A.jpeg" /><figcaption>Yeah, here is my data collection setup!</figcaption></figure><p>That spot was the closest I could find to record the kind of behavior I was expecting to see in my dataset.</p><p>It didn’t really matter that it wasn’t the actual environment because all the scene details and background were going to be removed anyway. The only thing that mattered was how people moved.</p><p>Now it’s just me and hours of videos of people passing by… I split them into small clips, labeled them, and tada… the dataset was ready.</p><p>Watching people move in those frames and thinking about the expected output, lit up some lights for the preprocessing step. Eureka! 💡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1grCEGHnAhBGRo_ky8ZBA.png" /></figure><p>I treated each video as a sequence of black-and-white frames, then preserved their temporal order by overlapping them into a single image. Time itself became the grayscale parameter: the object appears closer to black in earlier frames, and closer to white as time passes.</p><p>This turned each video into a single image that still encodes time. With a full set of these time-encoded images in hand, it’s time to train a proper convolutional neural network (CNN).</p><p><strong>Another panic!</strong> I couldn’t train my CNN model on my laptop!</p><p>Each iteration was taking forever, and I realized that at this rate, I might finish training it by the year 2030! So if Google Colab hadn’t helped, I’d probably have had four more years to go! 😅</p><p>Thankfully, Google Colab came to the rescue, and after a few weeks of trial and error, tweaking the parameters and training the model again and again, I finally got it done.</p><p>Now… Here is my mystery box, you can take a look inside. 😁<br>🔗<a href="https://github.com/sdrfsh/realtime-activity-and-intention-recognition"><strong>Real-time activity and intention recognition</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26faa35af25" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>