# Shopify Duplicate Product & Cannibalization Audit (`practical_ai_lab_jp/pal-shopify-catalog-cannibalization-cluster-audit`) Actor

One store URL in: severity-ranked clusters of near-duplicate Shopify listings with merge, redirect or differentiate advice, plus change tracking against your last run.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-shopify-catalog-cannibalization-cluster-audit.md
- **Developed by:** [Practical AI Lab](https://apify.com/practical_ai_lab_jp) (community)
- **Categories:** E-commerce, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 75.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $20.00 / 1,000 audit completeds

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

## Shopify Duplicate Product & Cannibalization Audit

Large Shopify catalogs often hold near-duplicate listings: the same item created twice, copy-style handles (`-1`, `-copy`), or bundles and variants split across several products. Those listings compete with each other for search rank, reviews and ad spend, and staff usually notice only a few by eye.

This Actor takes **one store URL**, reads the store's public product feed, groups look-alike listings into clusters, scores each cluster for cannibalization risk, and tells you what to do with each one: **merge**, **redirect** or **differentiate**. It also stores a baseline so that later runs show which clusters **grew**, **merged**, were **split** or were **resolved**.

> Status: this is a private build. Nothing here has been published, and no pricing plan is configured.

### Quick start (one URL, nothing else)

1. Paste your store URL, for example `https://your-store.com`. That is the only required input. No CSV, no JSON upload, no second snapshot.
2. Run the Actor. The first run ends with `runStatus: "BASELINE_CREATED"`. You get the full first audit (clusters, recommendations, CSV) and the baseline is stored for that store domain.
3. Run it again later with the same URL. The dataset then contains every **changed** cluster, every **resolved** cluster, and a small sample of unchanged clusters (default 5) so you can see what stayed the same.

Copyable input:

```json
{
    "storeUrl": "https://your-store.com",
    "maxPages": 3,
    "similarityThreshold": 70,
    "maxClusters": 100,
    "unchangedSampleSize": 5,
    "resetBaseline": false
}
```

The prefilled value `https://your-store.example` is a placeholder. Replace it with a real store domain; the placeholder cannot be resolved.

#### Scheduling later runs

The Actor does **not** schedule itself and sends **no alerts**. To compare over time:

1. Save the input above as an Apify **Task**.
2. In Apify Console open **Schedules**, create a schedule (for example weekly), and attach that Task.
3. Each scheduled run compares against the previous run's snapshot for the same store domain. Open the run's dataset or the `CLUSTER_MEMBERS.csv` file to read the changes.

Baselines are kept in a named key-value store (`pal-catalog-cluster-audit-state`) in your Apify account, one snapshot per store domain, capped at 25 domains (the least recently updated is evicted) and 300 clusters x 60 members per snapshot. Set `resetBaseline` to `true` for one run to start over.

### What you get

All outputs are joined by `clusterId` and ranked by risk.

| Output | Where | What it answers |
| --- | --- | --- |
| Run summary record (`recordType: "run_summary"`) | Dataset (first row), also `RUN_SUMMARY` in the key-value store | Run status, products analyzed, severity and action counts, vendor and product-type hotspots, sample-size confidence, warnings, limitations |
| Cluster records (`recordType: "cluster"`) | Dataset | Severity-ranked clusters with members, signals, a recommended action, a canonical listing, a redirect map and change status |
| Resolved records (`recordType: "resolved_cluster"`) | Dataset, repeat runs only | Previously flagged clusters that are gone, and whether listings were removed or simply no longer look alike |
| `CLUSTER_MEMBERS.csv` | Key-value store | One row per member listing with rank, severity, action, role, redirect paths and canonical id, ready for a spreadsheet |

#### Four buyer outcomes

1. **Cleanup priority list.** Clusters are ranked by a 0-100 risk score and banded `critical` (80+), `high` (65+), `medium` (50+) and `low`. Each carries one action: `MERGE_LISTINGS`, `REDIRECT_DUPLICATES` or `DIFFERENTIATE`, with a rationale and ordered steps.
2. **Canonical and redirect plan.** Every cluster names a canonical listing (it avoids copy-style handles, then prefers more variants, more images and the older listing). Non-canonical members of merge and redirect clusters get `redirectFromPath` and `redirectToPath`.
3. **Drift since your last run.** Each cluster carries `changeStatus`: `NEW`, `GREW`, `SHRUNK`, `MERGED` (two or more earlier clusters combined), `SPLIT`, `MEMBERS_CHANGED`, `UNCHANGED`, plus `RESOLVED` records. Added and removed product ids and the risk delta are included.
4. **Where to start.** `hotspots` in the summary ranks vendors and product types by how many clustered listings they hold.

#### How clusters are formed

Two listings are linked when a weighted similarity of at least `similarityThreshold` (default 70) is reached and their titles overlap meaningfully:

| Signal | Weight |
| --- | --- |
| Normalized title tokens (colors, sizes, units and filler words removed) | 40 |
| Handle base (trailing `-1`, `-copy` and similar stripped) | 15 |
| Image fingerprint: shared normalized image **file name** from public image URLs | 15 |
| Option structure (option names such as Color / Size) | 10 |
| Vendor | 10 |
| Price proximity (minimum variant price) | 10 |

Signals missing on either listing (no images, no vendor, no price) are left out and the remaining weights are rescaled. Links are merged into clusters with a cap of 60 listings per cluster.

Cluster risk score = 0.40 x cohesion + 0.20 x size + 0.15 x image overlap + 0.10 x price tightness + 0.15 x option-structure match. Components are included in each record as `riskComponents`.

Action rules:

- `REDIRECT_DUPLICATES` if titles are identical and a member looks like a copy (handle suffix next to a sibling handle, or a "copy" or "duplicate" marker) with shared images or identical options; or if titles are identical or very close, images are shared and prices are within 15%.
- `MERGE_LISTINGS` if titles, option structures and price band (within 15%) all match.
- `DIFFERENTIATE` otherwise.

### Safety and politeness

- Only the single HTTPS origin you provide is contacted. No logins, cookies, proxies or contact data collection.
- Only `/products.json?limit=250&page=N` and `/robots.txt` are requested. `robots.txt` is checked (with wildcard and longest-match rules, user-agent token `PALCatalogAuditBot`) **before every storefront request**. If robots.txt cannot be read (anything except HTTP 200, 404 or 410), the run stops. If it disallows the feed, the run stops with `ROBOTS_DENIED` and fetches nothing.
- SSRF protection: HTTPS only, no credentials in URLs, no custom ports, no IP-literal or local hostnames, and every resolved address must be public. Connections are pinned to the validated IP while TLS is verified for the hostname. Redirects are followed manually (max 3) and every hop is revalidated and robots-checked.
- Bounded work: at most 10 feed pages (default 3), a request budget, 15 s request timeouts, a 150 s total fetch budget and capped response sizes. No retries.
- Image comparison uses URL file names only. No images are downloaded.

### Pricing

The code defines one billable event, `audit-completed`, charged at most once per run and **only after** a full audit succeeded, results were written and the baseline was saved. Failed runs (invalid input, robots denial, unsafe host, fewer than 10 products, fetch errors) are never charged. **No payable plan or price is configured in this project.**

### Limitations and sample-size caveats

- Only products in the public `/products.json` feed are seen. Stores that disable the feed, hide products from it, or sit behind a password page cannot be audited.
- With fewer than 50 products the summary reports `confidence.level: "low"`: clusters and risk scores are leads to check by hand, not conclusions. At 50-299 products confidence is `medium`; 300 or more is `high`, which still does not make the heuristics exact.
- Similarity is heuristic. Titles that describe the same item with different words, or different items sharing generic wording, can be missed or wrongly linked. Legitimate bundles and variants can look like duplicates, so review before acting.
- The `-1` / `-2` handle rule can flag products whose names legitimately end in a small number.
- Risk scores rank overlap likelihood. They do not use traffic, sales, Search Console or ad data and do not measure lost revenue.
- Catalogs larger than `maxPages` x 250 products are analyzed only up to that limit (`catalogPossiblyTruncated` is set). Changing `maxPages` or `similarityThreshold` between runs can create false changes; the run adds a warning when it notices.
- Cross-run tracking uses product ids. Deleted and re-created products can appear as `RESOLVED` plus `NEW`.
- Very large look-alike groups hit internal comparison limits; the run reports this in `warnings`.
- The Actor never edits your store. Redirect and merge steps are suggestions.

### Illustrative record shape (synthetic, not a real run)

```json
{
    "recordType": "cluster",
    "priorityRank": 1,
    "severity": "critical",
    "riskScore": 88.0,
    "changeStatus": "BASELINE",
    "memberCount": 2,
    "recommendedAction": "MERGE_LISTINGS",
    "canonicalHandle": "example-cotton-tee",
    "members": [
        { "handle": "example-cotton-tee", "role": "canonical" },
        {
            "handle": "example-cotton-tee-1",
            "role": "merge_variants_into_canonical",
            "redirectFromPath": "/products/example-cotton-tee-1",
            "redirectToPath": "/products/example-cotton-tee"
        }
    ]
}
```

### Development

Tests are fully offline (mocked DNS, HTTP and storage) and use only the standard library:

```
python -m unittest discover -s tests -t .
```

Layout: `src/validation.py` (input), `src/safety.py` (SSRF, robots, fetcher), `src/parsing.py` and `src/normalize.py` (feed parsing and fingerprints), `src/clustering.py`, `src/scoring.py`, `src/recommend.py`, `src/changes.py`, `src/state.py`, `src/report.py`, `src/service.py` (run flow) and `src/main.py` (Apify SDK entry point).

# Actor input Schema

## `storeUrl` (type: `string`):

One HTTPS storefront URL, for example https://your-store.com. Only the domain is used. The Actor reads only the public /products.json feed and only if the store's robots.txt allows it. Replace the placeholder with your own store domain.

## `maxPages` (type: `integer`):

Each page holds up to 250 products. 3 pages cover up to 750 products. Larger catalogs are analyzed only up to this limit.

## `similarityThreshold` (type: `integer`):

Minimum pair similarity (50-95) for two listings to be linked. Raise it for fewer, stricter clusters; keep the same value between runs so changes stay comparable.

## `maxClusters` (type: `integer`):

Caps the clusters written to the dataset and CSV, highest risk first.

## `unchangedSampleSize` (type: `integer`):

On repeat runs the dataset lists every changed cluster plus this many top unchanged clusters as a sample.

## `resetBaseline` (type: `boolean`):

Ignore the stored baseline for this store and create a new one (emits BASELINE_CREATED).

## Actor input object example

```json
{
  "storeUrl": "https://your-store.example",
  "maxPages": 3,
  "similarityThreshold": 70,
  "maxClusters": 100,
  "unchangedSampleSize": 5,
  "resetBaseline": false
}
```

# Actor output Schema

## `results` (type: `string`):

Download rows from the latest run in JSON/CSV.

# 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 = {
    "storeUrl": "https://your-store.example"
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-shopify-catalog-cannibalization-cluster-audit").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 = { "storeUrl": "https://your-store.example" }

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-shopify-catalog-cannibalization-cluster-audit").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 '{
  "storeUrl": "https://your-store.example"
}' |
apify call practical_ai_lab_jp/pal-shopify-catalog-cannibalization-cluster-audit --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,practical_ai_lab_jp/pal-shopify-catalog-cannibalization-cluster-audit"
        }
    }
}
```

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/hbYO3xPu7SPF1Ijg9/builds/MUO4ku36lOy8IuC29/openapi.json
