# Tfidf Keyword Ranker (`eichan/tfidf-keyword-ranker`) Actor

- **URL**: https://apify.com/eichan/tfidf-keyword-ranker.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

## TF-IDF Keyword Ranker

**One job:** Rank individual words in **user-supplied text**. This is a deterministic keyword scoring utility, **not** a language model, semantic analyzer, or keyphrase generator.

### Who it is for

Developers preparing search indexes, simple RAG metadata, keyword lists, or interpretable text-analysis pipelines. No login, Apify SDK, external AI service, or user-supplied LLM API key is required. The Python standard library is the only dependency.

### How it works (plain words)

1. Find sequences of Unicode letters, lowercase them, and discard a fixed list of common **English** words and tokens shorter than `minWordLength`.
2. Count how often each remaining word occurs in the **target** `text`.
3. Compute **normalized term frequency**: target word count divided by the number of retained target tokens.
4. If `referenceTexts` were provided, use the target plus reference documents to calculate smoothed inverse document frequency: `IDF = ln((N + 1) / (DF + 1)) + 1`, and multiply normalized TF by IDF. Only words present in the target text can be returned.
5. If **no** reference documents are supplied, `N = DF = 1`, so `IDF = 1`: the results are **term-frequency only**, *not* informative corpus TF-IDF. The `scoring_method` output field explicitly says `tf_only` or `tfidf`.
6. Order by unrounded score descending, then keyword alphabetically, and emit one Dataset item per selected keyword.

Scores are **relative numerical weights**, not calibrated probabilities or a measurement of meaning. Exact output is repeatable for the same input.

### Input

| Field | Type | Default | Constraints |
| --- | --- | --- | --- |
| `text` | string | required | Nonempty, max 100,000 characters |
| `referenceTexts` | array of strings | `[]` | Up to 20 reference texts, each nonempty, max 20,000 characters; total combined length up to 300,000 |
| `maxKeywords` | integer | `10` | 1–50 output rows |
| `minWordLength` | integer | `3` | 2–10 Unicode characters |

**Tiny example (one short text):**

```json
{
  "text": "Solar panels produce electricity. Solar energy is renewable.",
  "maxKeywords": 3
}
```

The Apify input schema pre-fills only the one short `text` field; optional settings have defaults.

### Output (Dataset items)

For the example above, three items are appended. The **actual first item** from `python src/main.py` is:

```json
{
  "rank": 1,
  "keyword": "solar",
  "score": 0.285714,
  "frequency": 2,
  "document_frequency": 1,
  "document_count": 1,
  "scoring_method": "tf_only"
}
```

Every item has the same seven fields. `rank` starts at 1; `frequency` is the number of occurrences in the target; `document_frequency` is the number of input documents containing the keyword; `document_count` includes the target plus references. See `verification/dataset_items.json` for all three actual example rows.

### Limits and honesty

- A single text cannot establish meaningful inverse document frequency. Supply several **representative** reference texts if you need corpus-level weighting.
- Only unigrams (single words) are emitted. No multiword phrases, lemmatization, stemming, synonyms, named entities, or semantic relevance.
- The English stopword list is small and fixed. Non-English text may produce low-quality rankings; languages without spaces between words (e.g. Japanese/Chinese) are **not properly segmented**.
- Hyphens split words; numbers are skipped. Quoted words, misspellings, technical tokens, and unusual punctuation can affect counts.
- Results only reflect the input: no search, outside sources, or facts are introduced. Zero qualifying keywords produces a plain-language error and a nonzero exit code.
- The 1 MB input JSON limit and per-field limits bound processing. Floating scores are rounded to six decimal places in output; sort order uses full precision.

### Running locally

Requires **Python 3.12+**, without `pip install`:

```bash
cd tfidf-keyword-ranker
mkdir -p storage/key_value_stores/default
cp verification/sample_input.json storage/key_value_stores/default/INPUT.json
python src/main.py
```

Outputs appear at `storage/datasets/default/000000001.json` etc. Alternatively, set `ACTOR_INPUT_JSON` to a valid JSON object and run `python src/main.py`. The local root can be changed with `APIFY_LOCAL_STORAGE_DIR`. Errors go to standard error as a single `Error: ...` message (no traceback).

On **Apify cloud**, the runtime's existing `ACTOR_DEFAULT_KEY_VALUE_STORE_ID`, `ACTOR_INPUT_KEY`, `ACTOR_DEFAULT_DATASET_ID`, and `APIFY_TOKEN` are used via HTTPS and the Apify storage REST API. The token is provided by the Apify runtime, **not** supplied in Actor input. No Apify SDK is imported. No other website is contacted.

### Verification (included with this Actor)

```bash
python -m unittest discover -s tests -v
```

`tests/test_main.py` includes *actual* `python src/main.py` subprocess runs with valid `INPUT.json` and valid `ACTOR_INPUT_JSON`, invalid-input checks, and a local stub of the Apify storage API. For the saved smoke evidence, see `verification/smoke_terminal.txt`, `verification/sample_input.json`, and `verification/dataset_items.json`. The smoke command was:

```bash
mkdir -p verification/smoke_storage/key_value_stores/default
cp verification/sample_input.json verification/smoke_storage/key_value_stores/default/INPUT.json
APIFY_LOCAL_STORAGE_DIR=verification/smoke_storage python src/main.py
```

Running again appends new local Dataset records. The `if __name__ == "__main__":` block is intentionally **the last statement in** `src/main.py`.

### Store categorization and pricing proposal

- **Intended Apify Store category:** `AI` (1 category; suitable for AI data preparation rather than an AI-chatbot clone). Actual Store classification depends on Apify's publishing interface.
- **Suggested billing model:** Pay-per-event, **per emitted keyword item**, if monetization is later implemented. This encourages small `maxKeywords` values and lets a customer cap output.
- **Current state:** No pricing, pay events, or billing are configured or implemented; this folder does not publish an Actor.

# Actor input Schema

## `text` (type: `string`):

Only terms from this text are returned.

## `referenceTexts` (type: `array`):

An optional comparison corpus for inverse document frequency; never included in ranked output.

## `maxKeywords` (type: `integer`):

Maximum dataset items produced.

## `minWordLength` (type: `integer`):

Minimum number of Unicode letters per keyword.

## Actor input object example

```json
{
  "text": "Solar panels produce electricity. Solar energy is renewable.",
  "maxKeywords": 10,
  "minWordLength": 3
}
```

# 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 = {
    "text": "Solar panels produce electricity. Solar energy is renewable."
};

// Run the Actor and wait for it to finish
const run = await client.actor("eichan/tfidf-keyword-ranker").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 = { "text": "Solar panels produce electricity. Solar energy is renewable." }

# Run the Actor and wait for it to finish
run = client.actor("eichan/tfidf-keyword-ranker").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 '{
  "text": "Solar panels produce electricity. Solar energy is renewable."
}' |
apify call eichan/tfidf-keyword-ranker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,eichan/tfidf-keyword-ranker"
        }
    }
}
```

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/sHBBWKGottfT2wd34/builds/trR36wJR2GNvgxWn6/openapi.json
