# Keyword Demand, Search Volume & CPC Valuation Engine (`vesper_studio/demand-check`) Actor

Calculate Google search volumes, Google Ads CPC (low/high/avg), search intent classification, and long-tail metro expansion across US/CA. Calculates total market volume and monthly traffic value ($/mo) with instant DEMANDE FORTE / MOYENNE / FAIBLE verdict.

- **URL**: https://apify.com/vesper_studio/demand-check.md
- **Developed by:** [Xavier Richard](https://apify.com/vesper_studio) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 40.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$4.00 / 1,000 evaluated keyword metrics

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

## demand_check — Chiffrage de la Demande (Volumes, CPC, Longue Traîne)

Outil automatisé d'évaluation de la demande et de valorisation de mots-clés pour annuaires et sites de données thématiques (États-Unis, Canada, France/Europe).

En quelques secondes, ce module extrait les requêtes de longue traîne via **Google Suggest**, récupère les volumes réels Google Ads, le niveau de concurrence et le CPC via **Apify** (`memo23/keyword-metrics`), analyse un échantillon **Google SERP** (présence d'annonces Google Ads et Pack Local Maps) et calcule la valeur marchande mensuelle du trafic avec un verdict argumenté : **DEMANDE FORTE**, **DEMANDE MOYENNE** ou **DEMANDE FAIBLE**.

***

### 1. Installation & Prérequis

#### Prérequis

- Python 3.12 ou supérieur sous Windows 10/11.
- Dépendances principales : `httpx`, `pydantic`, `rich`, `apify-client`, `pandas`, `openpyxl`, `pyarrow`.

#### Mise en place

1. **Installer le socle commun `datakit` :**
   ```powershell
   cd "C:\Users\Lenovo\datakit"
   python -m pip install -e .
   ```

2. **Installer le module `demand_check` en mode éditable :**
   ```powershell
   cd "C:\Users\Lenovo\Projet dev web\Apify Scraper\Scraper Perso\demand_check"
   python -m pip install -e .
   ```

3. **Lancer les tests de validation (100% locaux, aucun appel payant) :**
   ```powershell
   pytest tests
   ```

***

### 2. Configuration des Clés & Authentification

Toutes les clés sont lues dynamiquement depuis le fichier `.env` (jamais stockées dans le code).

Créez votre fichier `.env` à partir de `.env.example` :

```env
## Clé Apify
APIFY_TOKEN=apify_api_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

## Proxy Bright Data pour SERP (optionnel)
BRIGHTDATA_API_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
BRIGHTDATA_SERP_ZONE=serp
BRIGHTDATA_UNLOCKER_ZONE=unlocker

## Acteur de secours optionnel
## APIFY_KEYWORD_ACTOR=memo23/keyword-metrics
```

#### Comment obtenir votre Token Apify

1. Créez un compte gratuit sur [apify.com](https://apify.com).
2. Rendez-vous dans **Console > Settings > Integrations** (ou cliquez sur votre profil en haut à droite).
3. Dans la section **API tokens**, copiez votre **Personal API token** (commence généralement par `apify_api_...`).
4. Collez cette valeur dans votre fichier `.env` pour la variable `APIFY_TOKEN`.
5. Si votre forfait Apify est un forfait restreignant les acteurs publics tiers du Store, le module active automatiquement son référentiel certifié afin d'assurer la continuité de l'analyse sans interruption.

***

### 3. Modèle Économique & Coût par Niche

Le module est conçu pour minimiser les coûts d'acquisition de données grâce à un découpage strict des sources et un cache SQLite persistant :

| Source | Rôle | Coût Estimé |
|---|---|---:|
| **Google Suggest (Autocomplétion)** | Découverte de la longue traîne (villes, near me, cost...) | **0,00 $ (Gratuit)** |
| **Apify (`memo23/keyword-metrics`)** | Volumes Google Ads, CPC bas/haut, concurrence | **~0,25 $ par lot de 1 000 mots-clés** |
| **Bright Data SERP API** | Échantillon de 10 requêtes (annonces & pack local) | **~0,03 $ (~0,003 $/requête)** |
| **Coût Total d'une Niche** | Exploration complète (50 villes + suffixes) | **< 0,30 $** |
| **Seconde Exécution (Cache 30 j)** | Ré-évaluation ou relecture | **0,00 $ (0 appel payant)** |

#### Garde-fous intégrés :

- **Plafond de sécurité `--max-usd`** (défaut : 2,00 $) : avant chaque lot payant, le solde prévisionnel est contrôlé. Si le plafond est atteint, l'exécution s'arrête proprement avec message explicatif (`BudgetExceededError`).
- **Cache SQLite (`data/cache.sqlite`)** : les métriques de mots-clés sont conservées pendant **30 jours**. Toute requête déjà chiffrée est servie instantanément avec zéro appel payant.
- **Règle d'intégrité** : Aucun mot-clé sans donnée Google Ads n'est inventé ou extrapolateur ; il demeure affiché à `n.d.` (None).

***

### 4. Utilisation en Ligne de Commande (CLI)

Le module est accessible via `python -m datakit.demand` ou `python -m demand_check`.

#### 1. Expansion à partir de graines + 50 métropoles + volumes

Part d'un mot-clé racine, interroge Google Suggest sur la matrice des 50 plus grandes métropoles US (`places_us.csv`) et des suffixes d'intention, puis chiffre les métriques :

```powershell
python -m datakit.demand expand --seed "septic tank pumping" --country us --places top50
```

Pour le Canada (avec Montréal et Québec en français) :

```powershell
python -m datakit.demand expand --seed "vidange fosse septique" --country ca --places top25
```

Option pour fouiller l'alphabet complet (`<graine> a`, `<graine> b`...) :

```powershell
python -m datakit.demand expand --seed "mobile home movers" --country us --places top50 --letters
```

#### 2. Chiffrage d'une liste de mots-clés existante

Envoie une liste de mots-clés directement au moteur d'évaluation :

```powershell
python -m datakit.demand metrics --file keywords.txt --country us
```

Ou directement en ligne de commande :

```powershell
python -m datakit.demand metrics --keywords "septic tank pumping,septic tank pumping cost,septic cleaning near me" --country us
```

#### 3. Traitement par lot de niches (fichier CSV)

Analyse une liste de niches en continu (même format que `niche_check`) :

```powershell
python -m datakit.demand batch --file niches.csv --country us
```

Format du CSV accepté :

```csv
niche,keywords,country,places
mobile home movers,mobile home movers|mobile home transport,us,Houston TX|Phoenix AZ
septic tank pumping,septic tank pumping,us,top50
```

***

### 5. Signification de Chaque Indicateur

| Indicateur | Définition & Formule | Interprétation pour un Annuaire |
|---|---|---|
| **Volume total mensuel** | Somme des volumes moyens mensuels de recherche Google Ads. | Mesure la taille globale du marché. Un volume $\ge 15,000$ rech/mois indique une demande grand public ou professionnelle soutenue. |
| **Volume transactionnel** | Volume des requêtes contenant `near me`, `in <ville>`, `best`, `service`, `company`, etc. | Coeur de cible d'un annuaire : intention directe de contacter ou d'embaucher un professionnel local. |
| **Volume requêtes prix** | Volume des requêtes contenant `cost`, `price`, `quote`, `estimate`, `how much`. | Indique des prospects en fin de cycle d'achat cherchant à comparer les tarifs des prestataires. |
| **Volume informationnel** | Volume des requêtes de type `how to`, `diy`, `guide`, `tips`, `signs of`. | Trafic éducatif utile pour le SEO éditorial et les guides d'annuaire, mais moins directement monétisable au lead. |
| **Valeur estimée du trafic** | $\sum (\text{volume} \times \text{CPC} \times 0.3)$ | Équivalent financier du trafic si l'annuaire devait l'acheter sur Google Ads, basé sur un CTR moyen réaliste de 30% (`--ctr 0.3`). |
| **CPC médian pondéré** | Médiane des CPC pondérée par le volume de chaque requête. | Évite qu'une requête marginale à 50$ fausse la moyenne. Reflète la valeur réelle d'un clic sur les termes les plus recherchés. Un CPC $\ge 4.00$$ signale des leads à haute marge (plomberie, transport, forage...). |
| **Part de la longue traîne** | $\frac{\text{Volume des requêtes locales ('in <ville>')}}{\text{Volume de la requête racine générique}}$ | Mesure la dispersion géographique. Un ratio $> 1.0$ prouve que les gens cherchent massivement ville par ville, ce qui valide l'architecture multi-villes d'un annuaire. |
| **Tendance 12 mois** | Pente de régression linéaire calculée sur l'historique mensuel. | Indique si l'intérêt pour la niche est `en hausse` ($> +3%$), `stable` ou `en baisse` ($< -3%$). |
| **SERP — Part Google Ads** | % des requêtes de l'échantillon testé avec annonces payantes. | Valide que les entreprises concurrentes paient déjà activement pour capter ces clients. |
| **SERP — Part Local Pack** | % des requêtes déclenchant le 3-Pack Google Maps. | Confirme le caractère résolument local de la recherche (idéal pour un annuaire d'artisans ou prestataires). |

***

### 6. Règles de Décision & Verdicts

Les seuils sont configurables dans `demand_check/rules.py` :

| Verdict | Conditions Principales | Signification pour le Projet |
|---|---|---|
| **🟢 DEMANDE FORTE** | Volume total $\ge 15,000$ (ou transactionnel $\ge 5,000$), CPC médian $\ge 4.00$$, présence avérée d'annonces Google Ads et de packs locaux. | Niche prioritaire. Fort potentiel d'annuaire monétisable par abonnement ou vente de leads qualifiés. |
| **🟡 DEMANDE MOYENNE** | Volume $\ge 4,000$ (ou transactionnel $\ge 1,000$), CPC $\ge 1.50$$. | Niche viable pour un annuaire spécialisé ou d'autorité, avec acquisition SEO ciblée. |
| **🔴 DEMANDE FAIBLE** | Volume $< 4,000$ et CPC $< 1.50$$. | Monétisation difficile au clic ou au lead. Déconseillé pour un annuaire dédié. |

***

### 7. Fichiers et Formats Produits

Toutes les sorties sont stockées dans le dossier `out/demand/` :

- `out/demand/<slug>.csv` : Ensemble complet des mots-clés découverts avec leur intention, volume, CPC bas/haut, niveau de concurrence et tendance.
- `out/demand/<slug>.parquet` : Même jeu de données au format binaire Parquet pour analyse BigQuery ou Pandas.
- `out/demand/summary.csv` : Synthèse comparative multiligne (une ligne par niche avec verdict et raisons chiffrées).
- `out/demand/<slug>_report.md` : Rapport Markdown complet prêt à être partagé ou inclus dans votre documentation d'audit.

# Actor input Schema

## `seeds` (type: `array`):

Initial root keyword seeds to expand and evaluate (e.g. \['septic tank pumping'] or \['mobile home movers', 'mobile home transport']).

## `niche_name` (type: `string`):

Custom display name for the niche report. Defaults to the first seed keyword.

## `country` (type: `string`):

Two-letter ISO country code for Google search and Google Ads metrics.

## `lang` (type: `string`):

Search and autocompletion language code (e.g. 'en', 'fr').

## `places` (type: `string`):

City expansion preset or custom pipe-separated list. Options: 'top50' (50 largest US metros), 'top25' (Canada top metros with Montreal/Quebec), 'top10', or custom 'Houston TX|Phoenix AZ'.

## `include_letters` (type: `boolean`):

Query Google Suggest with alphabetical suffixes ('seed a', 'seed b'...) to uncover deep long-tail searches.

## `ctr` (type: `number`):

Estimated click-through rate to calculate monthly traffic commercial value (default 0.30 = 30%). Formula: Σ volume × CPC × CTR.

## `max_usd` (type: `number`):

Maximum paid API spending allowed before automatic clean stop (default $2.00).

## `skip_serp` (type: `boolean`):

Skip checking Google Ads and Local Pack Maps on the 10-query sample (faster run).

## `apify_token` (type: `string`):

Optional: Override Apify token for keyword metrics API calls. If empty, uses container environment variable APIFY_TOKEN.

## `brightdata_api_token` (type: `string`):

Optional: Bright Data API token for SERP API and Web Unlocker fallback. If empty, uses container environment variables.

## `brightdata_serp_zone` (type: `string`):

Zone name for Bright Data SERP API.

## `brightdata_unlocker_zone` (type: `string`):

Zone name for Bright Data Web Unlocker.

## Actor input object example

```json
{
  "seeds": [
    "septic tank pumping"
  ],
  "country": "us",
  "lang": "en",
  "places": "top50",
  "include_letters": false,
  "ctr": 0.3,
  "max_usd": 2,
  "skip_serp": false,
  "brightdata_serp_zone": "serp",
  "brightdata_unlocker_zone": "unlocker"
}
```

# Actor output Schema

## `keywords` (type: `string`):

Overall market demand verdict alongside search volume, CPC, and intent metrics per keyword.

## `report` (type: `string`):

Full formatted Markdown demand report with traffic value and top keywords.

# 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 = {
    "seeds": [
        "septic tank pumping"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("vesper_studio/demand-check").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 = { "seeds": ["septic tank pumping"] }

# Run the Actor and wait for it to finish
run = client.actor("vesper_studio/demand-check").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 '{
  "seeds": [
    "septic tank pumping"
  ]
}' |
apify call vesper_studio/demand-check --silent --output-dataset

```

## MCP server setup

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

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/IsU1K7tD7dMpOFoaJ/builds/JOKLztXt5S95ufr6Z/openapi.json
