# Text Near Duplicate Finder (`eichan/text-near-duplicate-finder`) Actor

- **URL**: https://apify.com/eichan/text-near-duplicate-finder.md
- **Developed by:** [Eichan Jolly](https://apify.com/eichan) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$3.00 / 1,000 results

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

## Text Near-Duplicate Finder

A deterministic, no-LLM tool for finding **near-identical surface text** among a small group of supplied strings. It emits **only pairs whose token-shingle Jaccard similarity meets or exceeds a threshold**. It never fetches web pages or calls a third-party API.

### Who this is for

Dataset curators, RAG ingestion pipeline builders, article/content editors, and QA teams checking whether supplied documents or snippets are almost identical. It is not a plagiarism detector or semantic similarity model.

### Inputs

- `texts` (**required**): an array of 2–20 **non-empty** strings. Maximum combined length: 100,000 characters.
- `threshold` (optional): a number from `0` to `1`, default **`0.8`**. A pair is emitted when the **unrounded** Jaccard value is greater than or equal to this threshold.

All pairs `i < j` are compared, at most 190 for 20 texts; original indices are **zero-based**. Every matching pair produces one Dataset item. **Zero matches produce zero Dataset items, not a fabricated "no match" item.**

### Tiny working example

Input (same as the real input schema prefill):

```json
{
  "texts": [
    "RAG chunks help search relevant text.",
    "rag chunks help search relevant text!"
  ],
  "threshold": 0.8
}
```

Dataset item:

```json
{
  "firstIndex": 0,
  "secondIndex": 1,
  "similarity": 1.0,
  "method": "deterministic token 3-shingle Jaccard surface similarity (not semantic)"
}
```

There are no results for nonmatching pairs. In a 20-text input, the tool tests every `i < j` pair, even though it outputs only qualifying pairs. Similarity is rounded to **six decimal places for display**, not for threshold filtering.

### Exact method and limitations

1. Apply Unicode NFKC normalization and case-folding, then recognize sequences of Unicode word characters (excluding underscore). Punctuation changes and capitalization are usually ignored.
2. Convert each text into a **set of consecutive three-token shingles** (3-grams). For 1–2 token inputs, the entire token sequence acts as the one shingle.
3. Compute Jaccard similarity `|shingles(A) ∩ shingles(B)| / |shingles(A) ∪ shingles(B)|`.
4. Retain all qualifying pairs; tie and output order are deterministic, ascending `(firstIndex, secondIndex)`.

**This is heuristic surface matching, not semantic understanding.** Reworded passages may score low despite meaning the same thing. Common boilerplate and short texts may appear more similar than expected. A single Chinese or Japanese sentence may be treated as one long token because there is no word segmentation. Set comparison ignores shingle multiplicities, though word order inside each shingle matters. This Actor does not assess copying, authorship, intent, or legal similarity.

Input validation errors (including invalid list size, empty strings, missing required property, invalid threshold, and excessive total text size) print a plain-language error and exit without a traceback.

### Run locally

Requires Python 3.12+; no dependencies to install. From the Actor folder:

```bash
ACTOR_INPUT_JSON='{"texts":["RAG chunks help search relevant text.","rag chunks help search relevant text!"],"threshold":0.8}' python src/main.py
```

Or save a JSON object at `storage/key_value_stores/default/INPUT.json` and call `python src/main.py`. Local results are individual files under `storage/datasets/default/` by default, or `$APIFY_LOCAL_STORAGE_DIR/datasets/default/`. Run `python tests/run_smoke.py` for a fresh temporary storage directory and verified script-mode output.

On Apify, with `APIFY_IS_AT_HOME`, the Actor retrieves the run's input from the default key-value store using Apify's REST API and the **platform-injected** `APIFY_TOKEN`, then appends nonempty matching items to the default Dataset via the same REST API. The Actor does not require login, LLM accounts, external model API keys, or the Apify SDK.

### Store and suggested pricing (not configured)

- Store category: **AI**.
- Suggested price: **$0.001 per matching pair result**. No pair means no suggested per-result charge; actual price depends on later Apify configuration. This is a recommendation only; no billing configured or Actor published.

### Verification

Run `python -m unittest discover -s tests -v` and `python tests/run_smoke.py` from this folder. Tests include local subprocess execution, threshold boundaries, zero-output handling, error paths, and mock Apify REST storage. Actual terminal output and the produced item from a valid `python src/main.py` run are included in `tests/`. Docker builds and real Apify runs have not been performed.

# Actor input Schema

## `texts` (type: `array`):

Two to twenty non-empty texts; total length at most 100,000 characters. The first text has index 0.

## `threshold` (type: `number`):

Minimum unrounded 3-token-shingle Jaccard similarity to include a pair (0 to 1).

## Actor input object example

```json
{
  "texts": [
    "RAG chunks help search relevant text.",
    "rag chunks help search relevant text!"
  ],
  "threshold": 0.8
}
```

# Actor output Schema

## `dataset` (type: `string`):

Dataset containing the Actor's result items

# 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 = {
    "texts": [
        "RAG chunks help search relevant text.",
        "rag chunks help search relevant text!"
    ],
    "threshold": 0.8
};

// Run the Actor and wait for it to finish
const run = await client.actor("eichan/text-near-duplicate-finder").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 = {
    "texts": [
        "RAG chunks help search relevant text.",
        "rag chunks help search relevant text!",
    ],
    "threshold": 0.8,
}

# Run the Actor and wait for it to finish
run = client.actor("eichan/text-near-duplicate-finder").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 '{
  "texts": [
    "RAG chunks help search relevant text.",
    "rag chunks help search relevant text!"
  ],
  "threshold": 0.8
}' |
apify call eichan/text-near-duplicate-finder --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,eichan/text-near-duplicate-finder"
        }
    }
}
```

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/1VqdaWnYyYUy15bgh/builds/PmzOmE5hLNhXyBw31/openapi.json
