End-to-End Guide: Building an AI-powered Competitor-Price-Monitoring App
Goal: Given your own catalog of products (“our DB”) and up to 10 competitor sites chosen by the user, automatically pull the latest prices, match them to your SKUs, and surface the comparison in a clean dashboard / API.
1. High-Level Architecture 🏗️
graph TD
A[Product DB] -->|SKU, name, attrs| B(Product Matcher Service)
C[Competitor List (≤10 sites)] --> D(Scraper Workers)
D --> E[Raw HTML / JSON]
E --> F(Price Extraction Service)
F --> B
B --> G[Price Comparison Engine]
G --> H[Dashboard & Alerts]
subgraph AI/ML
B
end
subgraph Data Lake
E
end
| Layer | Tech Options | Key Output |
|---|
| Scraper Workers | Scrapy, Playwright, Selenium, Puppeteer | Raw pages |
| Price Extraction | Rule-based + ML (NER) | {sku?, title, price, currency} |
| Product Matcher (AI) | Fine-tuned SBERT / MiniLM, Faiss for ANN | (our_sku ↔ competitor_page) match score |
| Comparison / Alerts | Python FastAPI, Node, or Go | REST/GraphQL + UI |
| Storage | Postgres / MySQL for catalog & results; S3/GCS for raw pages | Historical price table |
2. Phase-by-Phase Build Plan
Phase 1 — Requirements & Compliance ✅
- Confirm each competitor’s TOS allows scraping or negotiate/subscribe to their price feeds (some retailers sell APIs).
- Respect
robots.txt, throttle requests, and add user-agent transparency.
- GDPR/CCPA: store only public pricing, no PII.
Phase 2 — Data Ingestion 🚜
-
Internal Catalog Prep
• Required fields: sku, gtin/ean, brand, title, category, package_size, image_url.
• Nice-to-have: aliases (common misspellings), attributes (color, capacity …).
-
Competitor Source Config
{
"site_name": "ExampleShop",
"base_url": "https://exampleshop.com",
"list_type": "category", // or "search"
"entry_points": [
"https://exampleshop.com/category/widgets",
"https://exampleshop.com/category/gadgets"
],
"pagination_selector": "a.next",
"product_page_selector": "div.product-card > a"
}
-
Store this as a table so users can edit the 10 sites in the UI.
Phase 3 — Web Scraping & Anti-bot 🕷️
| Scenario | Approach |
|---|
| Static HTML | Scrapy + CSS/XPath selectors. |
| JS-heavy | Playwright headless Chromium; wait for DOM elements. |
| Anti-bot / Cloudflare | Rotate proxies, residential IPs, or integrate with services like BrightData, Oxylabs. |
Example (Python Scrapy):
class PriceSpider(scrapy.Spider):
name = "prices"
custom_settings = {"DOWNLOAD_DELAY": 1}
def start_requests(self):
for url in self.entry_points:
yield scrapy.Request(url, callback=self.parse_list)
def parse_list(self, response):
for href in response.css("div.product-card > a::attr(href)").getall():
yield response.follow(href, self.parse_detail)
next_page = response.css("a.next::attr(href)").get()
if next_page:
yield response.follow(next_page, self.parse_list)
def parse_detail(self, response):
yield {
"url": response.url,
"title": response.css("h1::text").get(),
"price": response.css("span.price::text").re_first(r"[\d.,]+"),
"currency": response.css("span.price::text").re_first(r"[€$£]"),
"image": response.css("img#main::attr(src)").get()
}
Save raw HTML+timestamp to S3 for auditing.
Phase 4 — Price Extraction & Cleaning 🧽
-
Rule-Based Pre-Cleaner
Strip commas, convert currency, detect multi-pack (/pack of 4).
-
ML Assist (Optional for messy pages)
Fine-tune a Named-Entity-Recognition (NER) model (e.g. spaCy, Flair) to tag <PRICE> in source if CSS paths vary often.
-
Exchange Rates
Pull daily FX rates via ECB or OpenExchangeRates to normalize into your base currency.
Phase 5 — Product Matching (Core AI) 🤖
Problem: Map a competitor line ({title, brand, attrs, img}) to your SKU.
5.1 Baseline Deterministic Rules
• Exact GTIN/EAN/UPC match → 100%
• Fuzzy string match on title + brand (Levenshtein, jaro_winkler > 0.9)
• Attribute overlap check (size, color).
5.2 Learning-based Matcher
-
Training Data
Build dataset of (our_sku, competitor_title) → {match=1/0}.
• 3–5K labeled pairs are enough for initial fine-tune.
• Label using internal category experts or outsource to Labelbox, Toloka.
-
Model Choice
• Sentence-BERT miniLM (sentence-transformers/all-MiniLM-L6-v2) – fast & small.
• Output 384-dim embeddings.
-
Fine-Tune
from sentence_transformers import SentenceTransformer, InputExample, losses
model = SentenceTransformer('all-MiniLM-L6-v2')
train_examples = [InputExample(texts=[sku_text, comp_text], label=label) for ...]
train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=16)
train_loss = losses.CosineSimilarityLoss(model=model)
model.fit(train_dataloader, train_loss, epochs=3)
model.save('matcher')
-
Inference Pipeline
• Embed all your SKU titles once; store in Faiss index.
• For each competitor product, embed text & perform ANN search → top-k candidates.
• Apply a threshold (e.g. cosine ≥ 0.8) and fallback rules.
-
Image Similarity (Optional)
Combine vision embeddings (CLIP) for SKU vs product page images to boost accuracy on ambiguous titles.
Phase 6 — Comparison & Business Logic 📈
-
Latest competitor price vs your current price → difference, % delta.
-
Alert Rules:
• If competitor price < ours by ≥ X % for N hours → Slack/Email webhook.
• Lowest price wins: optionally auto-generate pricing suggestions.
-
Historical Tracking: keep daily snapshots for trend charts.
SQL skeleton:
CREATE TABLE price_snapshot (
id SERIAL PRIMARY KEY,
sku VARCHAR,
competitor VARCHAR,
price DECIMAL,
currency VARCHAR,
scraped_at TIMESTAMP DEFAULT now(),
UNIQUE(sku, competitor, scraped_at::date)
);
Phase 7 — Dashboard & API 🎨
• React + Material-UI or Next.js for frontend.
• FastAPI backend (/prices?sku=123) returning JSON.
• Charts: Recharts, Plotly.
• Auth: JWT or Auth0; role = admin vs viewer.
Phase 8 — Deployment & Ops 🚀
| Component | Container | Notes |
|---|
| Scrapers | Docker; k8s CronJobs | Scale = (#sites × pages)/time |
| API + ML | Docker; auto-scale with HPA | model.pkl on volume |
| Storage | RDS Postgres, S3 | Backups, encryption |
| Monitoring | Prometheus + Grafana | 95-percentile scrape latency |
| CI/CD | GitHub Actions → ECR → ArgoCD | Canary releases |
3. Training & Evaluation Checklist ✔️
- Collect 3–10 K labeled pairs → 80/10/10 split.
- Metrics:
• Precision @ 1 (is top suggestion correct?)
• Recall @ 5 (within top 5 suggestions).
- Human-in-the-loop feedback: allow users to “confirm” or “reject” matches in UI → feed back into training set nightly.
- Re-train monthly; use MLflow for experiment tracking.
4. Security & Legal Footnotes ⚖️
• Rate-limit to avoid DDoS claims.
• Cache pages, don’t hot-link images.
• Provide opt-out mechanism for competitor sites if requested.
• Keep raw logs 30 days max unless needed for compliance.
5. MVP Timeline (12-week example) 🗓️
| Week | Milestone |
|---|
| 1-2 | Catalog schema, competitor config UI |
| 3-4 | Scraper PoC for 2 sites (static + JS) |
| 5-6 | Price extraction & normalization |
| 7-8 | AI matcher v1 (rules + SBERT fine-tune) |
| 9 | Comparison engine & API |
| 10 | Dashboard UI |
| 11 | Security, load tests, monitoring |
| 12 | Pilot with real users & feedback |
Quick Win Tips ✨
- Start with two competitors first; polish match accuracy before scaling to 10.
- Cache FX conversion; currency mismatches are the #1 silent bug.
- Keep raw HTML; impossible to debug extraction without it.
- Use feature flags for auto-repricing—start in “recommendation-only” mode.
Good luck building! If you need code samples for a specific piece (e.g., Playwright anti-bot setup or Faiss ANN queries), just shout.