# Language Heuristic Detector (`eichan/language-heuristic-detector`) Actor

- **URL**: https://apify.com/eichan/language-heuristic-detector.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

## Language Heuristic Detector

**One job:** make a small, deterministic **heuristic guess** about the language of one supplied text block, and show why that guess was made. No website fetching, machine learning, LLM or external API.

### Who it is for

Developers, content organizers and RAG data-preparation pipelines that want a lightweight first-pass routing label for text that may need more careful language identification later.

### How it works

1. Count letters in Unicode writing systems: Hiragana, Katakana, Han, Hangul, Cyrillic, Arabic, Devanagari and Latin.
2. If a non-Latin script is sufficiently prominent, make a script-based candidate guess: Japanese (`ja`, kana), Korean (`ko`, Hangul), Chinese (`zh`, Han-only), Russian (`ru`, Cyrillic), Arabic (`ar`, Arabic script) or Hindi (`hi`, Devanagari).
3. Otherwise compare common-word patterns for English (`en`), Spanish (`es`), French (`fr`), German (`de`), Portuguese (`pt`) and Italian (`it`) with small hand-coded word lists. Weight more distinctive terms twice, select the highest score, and report a runner-up.
4. Emit a qualitative **heuristic confidence label** (`high`, `medium`, `low`, `insufficient`) representing the strength of these few signals, **not a calibrated probability**. `und` means insufficient evidence, not an error.

### Example input

```json
{"text":"The library is open today, and the books are ready."}
```

### Example output (one dataset item)

```json
{
  "heuristic_language_code": "en",
  "heuristic_confidence_label": "high",
  "signals": [
    "Latin letters: 40",
    "en common-word hits: 5 (weighted score 9)",
    "de runner-up weighted score: 0"
  ],
  "dominant_script_signal": "Latin",
  "characters_analyzed": 51,
  "method": "deterministic_script_and_common_word_heuristic"
}
```

The **actual values** are generated by code; see `tests/smoke_dataset.json` for the exact item from the runnable example.

### Input and output

- Input: `text` (required, nonempty string, max 50,000 characters).
- Output: exactly one item with these stable fields: `heuristic_language_code`, `heuristic_confidence_label`, `signals` (list of plain-language evidence), `dominant_script_signal`, `characters_analyzed`, and `method`.

### Honest limitations

- **This is not an ML detector and never reports a statistical accuracy or probability.** The label `high` means clear support in a tiny fixed rule set, not 90%, 95%, or any other confidence percentage.
- Scripts are shared: Cyrillic does not uniquely mean Russian, Arabic script does not uniquely mean Arabic, Devanagari does not uniquely mean Hindi, and Han-only text can be Japanese, Chinese or another language. Such guesses are explicitly capped in heuristic strength.
- Spanish, French, Italian and Portuguese share many common words; short texts, titles, names, code, emojis, mixed languages, transliterations and dialects are often ambiguous. The detector may return `und` or misclassify them.
- No sentence-level multilingual segmentation. Latin word lists cover only six languages; many other languages are not represented.
- All operations are deterministic and offline; results should be independently checked before consequential use.

### Local execution and verification

Python 3.12+; **only the standard library**, no dependencies to install:

```bash
ACTOR_INPUT_JSON='{"text":"The library is open today, and the books are ready."}' python src/main.py
python -m unittest discover -s tests -v
python tests/run_smoke.py
```

The test runner actually executes `python src/main.py`, saves the terminal output and JSON dataset item into `tests/`, and checks them. Local output is under `storage/datasets/default/`; on the Apify platform it uses Apify's internal REST storage API with the injected runtime token, not an API key provided by a user.

### Store category and pricing suggestion

- Intended category: **AI** (deterministic text pre-processing).
- Suggested price: **$0.005 per completed run** (one text, one output item). Suggestion only — **no platform billing configured**, no publishing performed.
- See `store_metadata.json`.

### Deployment status

Script-mode execution and offline tests are included. Docker construction and real Apify platform execution have **not** been performed.

# Actor input Schema

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

One block of text to inspect (no network calls).

## Actor input object example

```json
{
  "text": "The library is open today, and the books are ready."
}
```

# 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": "The library is open today, and the books are ready."
};

// Run the Actor and wait for it to finish
const run = await client.actor("eichan/language-heuristic-detector").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": "The library is open today, and the books are ready." }

# Run the Actor and wait for it to finish
run = client.actor("eichan/language-heuristic-detector").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": "The library is open today, and the books are ready."
}' |
apify call eichan/language-heuristic-detector --silent --output-dataset

```

## MCP server setup

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

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/5G9KjfB2iAnW0UFGQ/builds/n0MVdmdWVtgYbZhcA/openapi.json
