PharmaX: Smart Geolocation & Conversational AI for On-Call Pharmacies

Project History, Engineering Pipeline, Mathematical Modeling & Key Learnings


The Inspiration: Field Insights

It all started with a personal experience, one shared by thousands of families in Lomé, Togo. It is 11:00 PM, a loved one falls ill with a sudden fever, and an on-call pharmacy must be found urgently. The information exists (published officially by INAM and ONPT), but it is severely fragmented: a blurry image shared on WhatsApp, a static table on a website, or a lost post on social media.

I realized that the core problem was not an absence of data, but the inability to make it queryable at the crucial moment. The user is forced to perform the machine's task: cross-referencing addresses, guessing distances, and switching applications to calculate a route. From this fragmented healthcare journey arose the drive to create PharmaX: a single, conversational, geolocated Progressive Web Application (PWA) designed to eliminate friction and save vital time.


Building the Project: From Data to Application

The construction of PharmaX followed a rigorous engineering methodology structured around a complete end-to-end pipeline.

1. Data Collection and Processing (ETL Pipeline)

To make the AI system functional and reliable, clean data was mandatory. I built an automated Python scraper to extract official on-call lists from INAM. The main challenge was matching extracted pharmacy names against my own geospatial dataset. I implemented the Jaccard Similarity Index to calculate text alignment:

$$J(A,B) = \frac{|A \cap B|}{|A \cup B|}$$

(where $A$ and $B$ represent the sets of word n-grams forming the pharmacy names).

2. Frugal Artificial Intelligence & NLP

Rather than relying on expensive, internet-dependent Large Language Models (LLMs), I opted for a frugal AI architecture. I trained a lightweight LinearSVC (TF-IDF) model on a domain-specific corpus of 5,000 utterances. To evaluate its classification performance under class imbalance, I used the $\text{F1-macro}$ metric:

$$\text{F1-macro} = \frac{1}{K} \sum_{i=1}^{K} \frac{2 \cdot \text{Precision}_i \cdot \text{Recall}_i}{\text{Precision}_i + \text{Recall}_i}$$

3. Geolocation & Spatial Navigation

For initial route guidance, the system computes geodesic distances ($d$) across the Earth's surface (radius $R \approx 6371 \text{ km}$) using the Haversine formula:

$$a = \sin^2\left(\frac{\Delta \varphi}{2}\right) + \cos(\varphi_1)\cos(\varphi_2)\sin^2\left(\frac{\Delta \lambda}{2}\right)$$

$$d = 2R \cdot \arctan2\left(\sqrt{a}, \sqrt{1-a}\right)$$

The complete stack integrates a lightweight Flask backend (Python), SQLite, Leaflet.js, OpenStreetMap, and the OSRM routing engine for real-time navigation.


Challenges Encountered & Solutions

  • Severe Data Imbalance: Emergency intent (emergency) accounted for less than 3% of incoming queries. A standard model would have overlooked these critical cases. I applied targeted oversampling techniques to force the AI model to accurately identify emergency scenarios.
  • Source Fragility (Human-in-the-Loop): Structure changes on source websites could break standard scrapers. I designed a hybrid verification architecture: 100% automated matching for high-confidence scores, with low-confidence matches flagged for administrator validation via a dedicated back-office.
  • Hardware Constraints: Optimizing for constrained execution environments (without dedicated high-end GPUs) led to continuous codebase efficiency, resulting in 90.7% overall accuracy while maintaining a 99% emergency detection rate.
  • User Usability Validation: Conducting System Usability Scale (SUS) benchmarks with real users was logistically demanding, yet essential to validate real-world impact—reducing emergency search durations from 18 minutes down to 20 seconds.

Key Learnings

  1. AI is only as good as its underlying data: The most complex phase was not training the model, but data cleaning, ETL pipeline stability, and validation (Garbage in, garbage out).
  2. Frugal AI is a necessity and a strength: Complex LLMs are not always required to solve critical local problems. Lightweight, self-contained models offer superior reliability and speed under fluctuating network connectivity.
  3. Human oversight is essential in digital health: AI should not operate as an opaque black box. Blending fast automated matching with human administration builds sustainable user trust.

PharmaX is more than just a technical prototype. It demonstrates that tailored technological innovation can—and must—deliver a direct, measurable social impact.

Share this project:

Updates

posted an update —

Hey hackers! I’m Abdoul-Hafiz. Today, I want to tell you about PharmaX, a project I developed for my Master's thesis in AI & Big Data—but mostly because it was a genuine engineering challenge.

The idea is simple: in Lomé, finding an on-duty pharmacy at 2 AM when a loved one is sick is a nightmare. Information is scattered across PDFs or random Facebook posts. So, we built a conversational agent that finds the nearest open pharmacy and guides you there.

Here is how I hacked it from A to Z, what made me proudest, and what I learned along the way.

My Contribution: Pure "Frugal" Full-Stack I didn't touch hardware; I built everything in pure software under a major constraint: no heavy servers, no GPUs, and sometimes flaky internet connections. I built the entire stack end-to-end:

Backend & API (Flask + SQLite): I wrote the REST API bridging the front end, the AI, and the database. SQLite was the perfect choice for prototyping: zero configuration, ultra-lightweight.

Scraping & ETL (Python / BeautifulSoup): INAM (the national health insurance) doesn't provide an API. So, I coded a scraper to pull the on-duty list directly from their website. Then came the big challenge: matching the scraped pharmacy names with my geolocated database. I used the Jaccard similarity index to compare text (after stripping accents, "Pharmacie de...", etc.).

Artificial Intelligence (scikit-learn): I trained a LinearSVC model on a 5,000-sentence corpus. No ChatGPT here! Just an ultra-lightweight TF-IDF model classifying text into 8 intents (emergency, route, search, etc.).

Frontend & Geo (Leaflet / OSRM): I used the browser's Geolocation API (W3C) along with Leaflet coupled with OSRM (Open Source Routing Machine) to trace real-time routes.

What I’m Most Proud Of It's not just the code itself, but the ingenuity driven by constraints:

Taming class imbalance: Normally, vital emergencies account for less than 3% of queries. A standard model would have ignored them. I used oversampling to force the AI to learn them. Result: 136 out of 137 emergencies detected on my final test set. When coding for healthcare, that number makes me truly proud.

Human-in-the-loop: Since scraping can break if INAM changes its layout, I built an admin dashboard. Validation is hybrid: if the Jaccard similarity score is 100%, it automatically publishes. If it's ambiguous, a human validates it manually. We combine machine speed with human reliability.

Measured real-world impact: I ran tests with real users (traditional method vs. PharmaX). Search time dropped from 18 minutes to 20 seconds, and the success rate doubled (from 40% to 80%). Proving that my code makes a concrete difference on the ground is my greatest pride.

What I Learned (The Hacker’s Lesson)

ML is 20% of the job; Data is 80%: Spending hours doing HTML parsing and text cleaning (ETL) taught me Garbage in, garbage out. AI is powerful, but it’s a slave to data quality.

Frugality is a feature, not a bug: In our African context, we don't need a 100-billion-parameter LLM that costs a fortune in API fees. A good old, well-trained LinearSVC runs in milliseconds, costs nothing, and works offline. That is meaningful innovation.

UX matters as much as the algorithm: The best model in the world is useless if a user panics and doesn't know where to tap. I learned to design for urgency (large buttons, clear guidance).

What’s next? Migrating to PostgreSQL/PostGIS to scale nationally, and adding voice recognition (for users who can't read or are too stressed to type).

All in all, PharmaX proved to me that with open-source tools, resourcefulness, and a deep understanding of local needs, you can hack solutions that can potentially save lives.