# US & Canada Official Business License Registry Scraper (`vesper_studio/registry-harvester`) Actor

Harvest, normalize, and deduplicate official US & Canada state and provincial business licensing registries (Texas TDLR Manufactured Housing, Florida Radon Pros, Ontario Licensed Businesses). Outputs clean B2B datasets ready for Supabase, Clay, CSV, JSON, or Parquet.

- **URL**: https://apify.com/vesper_studio/registry-harvester.md
- **Developed by:** [Xavier Richard](https://apify.com/vesper_studio) (community)
- **Categories:** Lead generation, Business, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$3.50 / 1,000 normalized registry records

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## registry_harvester — Moissonneur de Registres Officiels → Base d'Annuaire

`registry_harvester` est un module de moissonnage générique, modulaire et dédoublonné, conçu pour ingérer des listes officielles (registres de licences d'État, ordres professionnels, annuaires d'associations, open data gouvernemental) quel que soit leur format (CSV, Excel, tableau HTML, PDF, formulaires paginés ou API JSON), et les consolider dans un schéma commun cible prêt pour Supabase.

***

### 1. Architecture Générale

```text
datakit/
  ├── config.py                 # Configuration centrale (chargement .env, clés sans codage en dur)
  ├── fetch.py                  # Téléchargement résilient (Cache SQLite, rate limit 1 req/s, robots.txt, Bright Data Unlocker)
  ├── cache.py                  # Cache persistant SQLite (data/cache.sqlite) : aucune page payée deux fois
  ├── evidence.py               # Traçabilité des sources & compteur d'appels réseau payants
  └── harvest/
        ├── base.py             # Classe Source abstraite + cycle complet fetch → parse → normalize → validate → upsert
        ├── models.py           # Schéma Pydantic Entity, EntityChange, ReviewItem
        ├── parsers.py          # 7 parseurs (csv, xlsx, html_table, html_list, pdf_table, json_api, search_form)
        ├── normalize.py        # Normalisation (adresses US/CA, téléphones E.164, domaines web, statuts, dates)
        ├── dedupe.py           # Moteur de dédoublonnage hybride (règle stricte + RapidFuzz + pivots d'ancrage)
        ├── store.py            # SQLite local (data/harvest.sqlite) + export Parquet/CSV + upsert Supabase par lots
        ├── registry.yaml       # Catalogue des sources (pays, région, URL, fréquence, reuse_terms)
        ├── cli.py              # Commandes en ligne de commande (run, export, new-source)
        └── adapters/           # Adaptateurs par source (~30-80 lignes chacun)
              ├── us_tx_tdlr_manufactured_housing.py
              ├── us_fl_radon.py
              └── ca_on_licensed_businesses.py
```

***

### 2. Installation & Prérequis

#### Prérequis

- Python 3.12+ (testé sous Python 3.14 sur Windows 10/11)
- Outil `uv` ou `pip` dans un environnement virtuel `.venv`

#### Initialisation de l'environnement virtuel

```powershell
## Cloner ou se placer dans le répertoire du projet
cd "C:\Users\Lenovo\Projet dev web\Apify Scraper\Scraper Perso\registry_harvester"

## Création du venv via uv (recommandé) ou python
uv venv .venv
.\.venv\Scripts\activate

## Installation du package en mode éditable avec toutes les dépendances
uv pip install -e .
```

#### Configuration des clés d'API (`.env`)

Copiez le fichier `.env.example` en `.env` :

```powershell
Copy-Item .env.example .env
```

Renseignez vos clés (le fichier `.env` est ignoré par Git) :

```env
## Bright Data (déblocage anti-bot et enrichissement SERP)
BRIGHTDATA_API_TOKEN=votre_cle_brightdata
BRIGHTDATA_SERP_ZONE=votre_zone_serp
BRIGHTDATA_UNLOCKER_ZONE=votre_zone_unlocker

## Apify
APIFY_TOKEN=votre_token_apify

## Supabase
SUPABASE_URL=https://votre-projet.supabase.co
SUPABASE_SERVICE_KEY=votre_service_role_key
```

***

### 3. Commandes CLI

#### 3.1 Lancer la moisson d'une source spécifique

```powershell
python -m datakit.harvest run --source us_tx_tdlr_manufactured_housing
```

#### 3.2 Lancer toutes les sources actives

```powershell
python -m datakit.harvest run --all
```

Options additionnelles :

- `--enrich` : active l'enrichissement automatique des sites web manquants via la recherche Google SERP Bright Data (`"<nom> <ville> <région>"`). Le résultat n'est conservé que si le domaine contient un token du nom, et est marqué `website_source = 'serp_guess'`.
- `--force-refresh` : ignore le cache SQLite local et force le retéléchargement des pages sources.

#### 3.3 Exporter un jeu de données

```powershell
## Export CSV et Parquet en local (dans data/exports/)
python -m datakit.harvest export --dataset manufactured_home_pros --format csv,parquet

## Export vers Supabase (bloqué si les reuse_terms sont 'unknown')
python -m datakit.harvest export --dataset canada_ontario_licensed_pros --format supabase

## Forcer l'export Supabase même si les reuse_terms sont inconnus
python -m datakit.harvest export --dataset manufactured_home_pros --format supabase --force
```

#### 3.4 Ajouter une nouvelle source en 15 minutes

```powershell
python -m datakit.harvest new-source --name us_il_radon --kind html_table --url "https://apps.iema.illinois.gov/Radon/LicenseeListing.aspx"
```

Cette commande génère automatiquement un adaptateur complet et typé dans `datakit/harvest/adapters/us_il_radon.py` et inscrit la source dans `registry.yaml`.

***

### 4. Comment ajouter une nouvelle source en 15 minutes (Guide Pas-à-Pas)

1. **Générez le squelette** :
   ```powershell
   python -m datakit.harvest new-source --name us_ca_electricians --kind csv --url "https://data.ca.gov/licenses.csv"
   ```

2. **Ouvrez le fichier généré** dans `datakit/harvest/adapters/us_ca_electricians.py`.

3. **Ajustez les métadonnées de classe** :
   - Renseignez `reuse_terms` (ex: `"Public Domain / Open Data California"`).
   - Indiquez `is_individual = True` s'il s'agit d'une liste de personnes physiques (leurs adresses personnelles seront automatiquement retirées pour respecter la vie privée).

4. **Complétez `map_record_to_entity(self, record)`** :
   Mappez les clés brutes de la source vers les champs d'`Entity` en utilisant les helpers de normalisation :
   ```python
   def map_record_to_entity(self, record: Dict[str, Any]) -> Optional[Entity]:
       raw_name = record.get("BusinessName")
       if not raw_name:
           return None
       
       return Entity(
           entity_id=generate_stable_entity_id(
               dataset=self.dataset,
               name=normalize_company_name(raw_name),
               region="CA",
               license_number=record.get("LicNum"),
               source_name=self.name,
           ),
           dataset=self.dataset,
           name=normalize_company_name(raw_name),
           license_number=record.get("LicNum"),
           license_type=record.get("Trade"),
           license_status=normalize_license_status(record.get("Status")),
           license_expires=normalize_date(record.get("ExpDate")),
           city=record.get("City"),
           region="CA",
           postal_code=normalize_postal_code(record.get("Zip")),
           phone=normalize_phone(record.get("Phone")),
           website=normalize_website(record.get("Web")),
           source_name=self.name,
           source_url=self.url,
           raw=record,
       )
   ```

5. **Découverte automatique** :
   Grâce au moteur de découverte dynamique (`pkgutil`), votre nouvel adaptateur est immédiatement détecté et enregistré sans modifier aucun autre fichier de code.

6. **Testez immédiatement** :
   ```powershell
   python -m datakit.harvest run --source us_ca_electricians
   ```

***

### 5. Règles de Dédoublonnage et Gestion Incrémentale

#### Dédoublonnage Hybride

1. **Règle stricte (100% de certitude)** :
   Si deux lignes partagent le même numéro de licence et la même région administrative (État ou Province), elles sont fusionnées automatiquement.
2. **Appariement flou (RapidFuzz)** :
   - Nécessite impérativement un **ancrage pivot commun** : même code postal (5 premiers caractères) OU même téléphone E.164 OU même nom de domaine web.
   - Les suffixes légaux (`LLC`, `Inc`, `Corp`, `Ltd`, `The`, ponctuation) sont préalablement retirés.
   - **Score $\ge$ 90%** : Fusion automatique (`merged`).
   - **Score entre 75% et 89%** : Cas ambigu dirigé vers la table `review` pour arbitrage humain sans écrasement aveugle.
   - **Score < 75%** : Entités considérées distinctes.

#### Gestion Incrémentale et Table `changes`

- Chaque entité conserve `first_seen` (date de première détection) et `last_seen` (date de dernière observation).
- Lors d'une ré-exécution, si aucun champ n'a été modifié, **aucun doublon n'est créé** et la table `changes` n'est pas polluée.
- Si une licence expire ou si une adresse change, la table `changes` enregistre l'événement (`license_expired`, `address_changed`, etc.), ce qui permet de générer des alertes et flux hebdomadaires.

***

### 6. Schéma de la Table Supabase (`entities`)

Le script SQL complet est disponible dans [`migrations/001_create_entities.sql`](migrations/001_create_entities.sql).

```sql
CREATE TABLE public.entities (
    entity_id TEXT PRIMARY KEY,                       -- Hash stable SHA-256 déterministe
    dataset TEXT NOT NULL,                            -- Ex: manufactured_home_pros, radon_certified_pros
    name TEXT NOT NULL,                               -- Nom d'usage de l'entreprise ou du professionnel
    legal_name TEXT,                                  -- Raison sociale officielle
    dba TEXT,                                         -- Doing Business As / Enseigne commerciale
    license_number TEXT,                              -- Numéro officiel de licence / accréditation
    license_type TEXT,                                -- Métier ou classe de certification
    license_status TEXT DEFAULT 'unknown',            -- 'active', 'expired', 'suspended', 'unknown'
    license_issued DATE,                              -- Date d'attribution ISO (YYYY-MM-DD)
    license_expires DATE,                             -- Date d'expiration ISO (YYYY-MM-DD)
    address_line TEXT,                                -- Ligne d'adresse professionnelle
    city TEXT,                                        -- Ville
    region TEXT,                                      -- Code ISO État/Province (TX, FL, ON, etc.)
    postal_code TEXT,                                 -- Code postal normalisé (12345, M5V 2T6)
    country TEXT DEFAULT 'US',                        -- Code pays ISO-2
    lat DOUBLE PRECISION,                             -- Coordonnées GPS (si géocodé)
    lon DOUBLE PRECISION,
    phone TEXT,                                       -- Numéro au format international E.164 (+1...)
    email TEXT,                                       -- Email professionnel
    website TEXT,                                     -- Nom de domaine web normalisé
    website_source TEXT,                              -- 'official' ou 'serp_guess'
    categories TEXT[] DEFAULT '{}',                   -- Tags et catégories de l'annuaire
    source_name TEXT NOT NULL,                        -- Identifiant de la source d'origine
    source_url TEXT NOT NULL,                         -- URL exacte de provenance
    source_record_id TEXT,                            -- ID natif dans la source
    first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(),    -- Date de première collecte
    last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(),     -- Date de dernière vue
    is_individual BOOLEAN DEFAULT FALSE,              -- True si personne physique (adresse masquée)
    raw JSONB DEFAULT '{}'::jsonb                     -- Copie intégrale de la ligne d'origine
);
```

***

### 7. Exécution des Tests Unitaires

```powershell
python -m pytest tests -v
```

Tous les tests (normalisation d'adresses US et CA, formats de téléphones, suppression des suffixes légaux, dédoublonnage strict et flou, cas en revue, parseurs CSV/HTML/JSON, stockage incrémental sans doublons, génération de squelettes) s'exécutent en local sans dépendance externe et passent à 100%.

# Actor input Schema

## `source` (type: `string`):

Select an official registry source to harvest, or choose 'all' to collect from all available public sources.

## `since` (type: `string`):

Only re-harvest records if the last harvest is older than this duration (e.g. '7d', '24h', '30m'). Leave empty to always harvest.

## `enrich` (type: `boolean`):

Attempt to discover official company websites using Google SERP search when absent from the official registry.

## `force_refresh` (type: `boolean`):

Bypass local SQLite cache and force re-fetching remote endpoints.

## `max_records` (type: `integer`):

Optional upper limit on records pushed to the dataset (0 for unlimited).

## Actor input object example

```json
{
  "source": "all",
  "since": "",
  "enrich": false,
  "force_refresh": false,
  "max_records": 0
}
```

# Actor output Schema

## `records` (type: `string`):

Deduplicated and normalized official business and professional license records.

## `summary` (type: `string`):

Summary of harvested sources, valid entities, deduplication stats, and run metrics.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("vesper_studio/registry-harvester").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("vesper_studio/registry-harvester").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call vesper_studio/registry-harvester --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,vesper_studio/registry-harvester"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/Dd4C6T6pksues4CRz/builds/mRIgn40UkpbLEaVhT/openapi.json
