# Extractive Sentence Ranker (`eichan/extractive-sentence-ranker`) Actor

- **URL**: https://apify.com/eichan/extractive-sentence-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

$0.01 / actor start

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

## Extractive Sentence Ranker

**One job:** Score and rank **existing sentences** from **user-supplied text**. It never generates, paraphrases, checks, or rewrites a sentence. This is a local text-frequency heuristic, **not** an LLM-based summary or human-level assessment of importance.

### Who it is for

Developers prototyping extractive text previews, content triage, sentence-selection steps in retrieval pipelines, or educational readability workflows. It uses **only** the Python standard library. No Apify SDK, external LLM, login, or user-supplied API key is required.

### How it works (plain words)

1. Split the supplied text at end punctuation followed by whitespace, at newlines, and after Japanese full stops. This is a simple sentence splitter, not a grammar parser.
2. Extract runs of Unicode letters and remove a fixed list of common **English** words and tokens shorter than three letters.
3. Count each remaining word throughout the input. In each sentence, calculate the average of its word frequencies divided by the most frequent word's frequency.
4. Apply a mild penalty for sentences with fewer than four retained tokens: multiply by `min(retained_word_count / 4, 1)`.
5. Rank by descending **unrounded** score, breaking ties by original sentence position. Output the `topN` original sentences (or fewer if fewer can be scored).

The emitted `score` is a heuristic weight between 0 and 1, **not** a probability, factual-quality grade, or summary confidence score. This ranking tends to reward words repeated elsewhere in the input; repeated boilerplate can skew it.

### Input

| Field | Type | Default | Constraints |
| --- | --- | --- | --- |
| `text` | string | required | Nonempty, max 100,000 characters |
| `topN` | integer | `3` | 1–20; fewer items when fewer scoreable sentences |

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

```json
{
  "text": "Solar panels produce electricity. Solar energy powers homes. Wind turbines produce electricity.",
  "topN": 2
}
```

The prefilled UI provides only one short `text`. There are no URLs, data extraction, or generated answers.

### Output (Dataset items)

For the example above, the Actor appends two rows. The **actual first item** from a `python src/main.py` smoke run is:

```json
{
  "rank": 1,
  "sentence": "Solar panels produce electricity.",
  "score": 0.875,
  "sentence_index": 1,
  "word_count": 4
}
```

Every row has the same five fields: output `rank` starts at 1, `sentence` is copied from the input with internal whitespace collapsed, `score` is the heuristic weight, `sentence_index` is the original **1-based** sentence position, and `word_count` counts words before stopword filtering. See `verification/dataset_items.json` for both actual example rows.

### Limits and honesty

- **Extractive only:** cannot invent coherent connecting text or produce a rewritten, factual, or human-quality summary. Higher-scored sentences are not necessarily important, complete, trustworthy, or representative.
- Scoring is based on repeated **words**, not meaning or context. There is no semantic similarity, translation, entity recognition, bias correction, or fact checking.
- The English stopword list is fixed. Non-English text and languages without spaces may give unreliable results.
- Abbreviations (e.g. `Dr.`), decimal points, ellipses, quotations, and punctuation without whitespace may split incorrectly or remain together. HTML/Markdown is **not** parsed.
- A sentence with no retained content tokens cannot score and is skipped. If the entire input has no scoreable tokens, the run ends with a readable error. A maximum of 2,000 detected sentences is accepted.
- Scores are rounded to six decimal places for display; ties are decided using unrounded scores and original sentence order. No network or external LLM is used for the ranking.

### Running locally

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

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

Output appears under `storage/datasets/default/000000001.json` and increments for additional items. Alternatively, set `ACTOR_INPUT_JSON` to a JSON object. The local storage root can be changed with `APIFY_LOCAL_STORAGE_DIR`. Errors appear as plain `Error: ...` messages on standard error, without tracebacks.

On **Apify cloud**, the Actor reads its input and saves its Dataset rows through the Apify REST API using the Apify-provided run storage IDs and runtime `APIFY_TOKEN`. Users do not supply credentials or LLM keys; the Apify SDK is not used.

### Verification (included with this Actor)

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

`tests/test_main.py` runs the real `python src/main.py` script with both local `INPUT.json` and `ACTOR_INPUT_JSON`, checks error messages, and uses a local HTTP stub to test the cloud storage call pattern. `verification/smoke_terminal.txt`, `verification/sample_input.json`, and `verification/dataset_items.json` contain evidence from the script-mode smoke run. The exact smoke invocation 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 local Dataset items. The `if __name__ == "__main__":` block is **the final statement** in `src/main.py`.

### Store categorization and pricing proposal

- **Intended Apify Store category:** `AI` (1 category; positioned as a deterministic text-preparation utility, not a chatbot). Store classification is controlled by the available Apify publishing interface.
- **Suggested billing model:** Pay-per-event, **one successful processing run** (up to 20 returned sentences) rather than per sentence. This makes a short extract predictable to price.
- **Current state:** No pay events, pricing setup, or publication is included or enabled.

# Actor input Schema

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

English prose with punctuation or line breaks.

## `topN` (type: `integer`):

Number of highest-scoring original sentences to return.

## Actor input object example

```json
{
  "text": "Solar panels produce electricity. Solar energy powers homes. Wind turbines produce electricity.",
  "topN": 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 powers homes. Wind turbines produce electricity."
};

// Run the Actor and wait for it to finish
const run = await client.actor("eichan/extractive-sentence-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 powers homes. Wind turbines produce electricity." }

# Run the Actor and wait for it to finish
run = client.actor("eichan/extractive-sentence-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 powers homes. Wind turbines produce electricity."
}' |
apify call eichan/extractive-sentence-ranker --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,eichan/extractive-sentence-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/F4s16lIg1hmwo6Xuc/builds/nD5lhph9egkOufo8l/openapi.json
