Skip to main content

A CLI tool that explains Python errors in simple human language.

Project description

Error Translator

PyPI Version Python Version License Build Status

Translate raw Python tracebacks into clear explanations and actionable fixes. Built for local-first developer workflows: CLI, import-hook auto mode, Python API, and FastAPI.

✨ Key Features

  • CLI-first workflow: run a script, paste an error, or pipe logs directly into explain-error.
  • Auto mode: import error_translator.auto installs a custom sys.excepthook for unhandled crashes.
  • HTTP API: expose the same engine through FastAPI for service integrations.
  • Rules engine: regex-based matching from rules.json for deterministic, offline translations.
  • AST analysis hooks: error-type-specific handlers (via registry) can add deeper typo/context insight.

Installation

Install from PyPI

pip install error-translator-cli-v2

Local development setup

git clone https://github.com/gourabanandad/error-translator.git
cd error-translator
python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS/Linux
source .venv/bin/activate

pip install -r requirements.txt
pip install -e .
pytest

Usage

1) CLI usage

Run a Python script and translate unhandled errors:

explain-error run script.py

Translate a raw error string directly:

explain-error "NameError: name 'usr_count' is not defined"

Translate piped traceback logs:

cat error.log | explain-error

2) Python auto-import mode

import error_translator.auto

# Any unhandled exception in this process is intercepted
# and rendered as a translated, colorized explanation.

def main():
    total = "Users: " + 42

main()

3) FastAPI server usage

Start server:

uvicorn error_translator.server:app --host 127.0.0.1 --port 8000 --reload

Health check:

curl http://127.0.0.1:8000/

Translate via API:

curl -X POST http://127.0.0.1:8000/translate \
  -H "Content-Type: application/json" \
  -d "{\"traceback_setting\":\"Traceback (most recent call last):\\n  File 'app.py', line 14, in <module>\\n    total = 'Users: ' + 42\\nTypeError: can only concatenate str (not 'int') to str\"}"

Real-World Input → Output Examples

Example A: Type mismatch

Input traceback:

Traceback (most recent call last):
  File "app.py", line 14, in <module>
    total = "Users: " + 42
TypeError: can only concatenate str (not "int") to str

Translated output (CLI render):

Error Detected:
TypeError: can only concatenate str (not "int") to str

Location: app.py (Line 14)

Explanation:
You are trying to add a string to an int, which Python cannot do.

Suggested Fix:
Convert the int to a string first using str() before concatenating.

Example B: Missing variable typo

Input error line:

NameError: name 'usr_count' is not defined

Translated output:

Explanation:
You tried to use a variable or function named 'usr_count', but Python doesn't recognize it.

Suggested Fix:
Check if 'usr_count' is spelled correctly, or ensure you defined/imported it before using it.

Architecture

Error Translator uses one core engine with multiple entry points.

  1. Input ingestion: traceback text from CLI, API, or auto-hook.
  2. Rule matching: core.py checks the last error line against compiled regex rules from rules.json.
  3. Context extraction: file path, line number, and source line are extracted when available.
  4. Optional AST insight: for selected error types, handlers from ast_handlers.py can add extra hints.
  5. Structured output: returns a stable dictionary (explanation, fix, file, line, code, matched_error, optional ast_insight).

How It Works Internally

  • load_rules() reads rules.json once and caches it.
  • compiled_rules() compiles regex patterns once for fast repeated matching.
  • translate_error():
    • normalizes traceback input,
    • finds the terminal error line,
    • applies first matching rule,
    • formats placeholders ({0}, {1}, ...),
    • enriches with file/line/code context,
    • dispatches to AST_REGISTRY by error type when applicable.
  • If no rule matches, a safe fallback explanation/fix from default is returned.

Project Structure

error-translator/
├─ error_translator/
│  ├─ core.py           # Translation pipeline, rule loading, context extraction
│  ├─ rules.json        # Regex patterns + explanations + fixes
│  ├─ ast_handlers.py   # AST handler registry and insight plugins
│  ├─ cli.py            # `explain-error` command and colorized terminal renderer
│  ├─ auto.py           # Auto mode via sys.excepthook override
│  └─ server.py         # FastAPI app and /translate endpoint
├─ tests/
│  └─ test_core.py      # Core translation and regex extraction tests
└─ docs/
   ├─ ARCHITECTURE.md
   └─ CONTRIBUTING.md

How To Add New Rules

Add a new object to error_translator/rules.json under rules:

{
  "pattern": "ValueError: invalid literal for int\\(\\) with base 10: '(.*)'",
  "explanation": "You tried to convert '{0}' to an integer, but it is not a valid whole number.",
  "fix": "Ensure '{0}' contains only digits, or parse it as float if decimals are expected."
}

Guidelines:

  • Keep regex patterns specific to avoid false positives.
  • Use capture groups for dynamic values and reference them with {0}, {1}, etc.
  • Keep explanations beginner-friendly and fixes immediately actionable.
  • Add/extend tests in tests/test_core.py for each new rule.

Contributing

Contributions are welcome, from first-time contributors to maintainers.

Typical workflow:

  1. Fork and clone the repository.
  2. Create a feature branch.
  3. Add or improve rules/tests/docs.
  4. Run pytest.
  5. Open a PR with a sample traceback and expected translation.

Please see:

  • docs/CONTRIBUTING.md
  • docs/ARCHITECTURE.md

Maintainer

Built and maintained by Gourabananda Datta and contributors.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

error_translator_cli_v2-1.1.1.tar.gz (8.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

error_translator_cli_v2-1.1.1-py3-none-any.whl (8.9 kB view details)

Uploaded Python 3

File details

Details for the file error_translator_cli_v2-1.1.1.tar.gz.

File metadata

  • Download URL: error_translator_cli_v2-1.1.1.tar.gz
  • Upload date:
  • Size: 8.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for error_translator_cli_v2-1.1.1.tar.gz
Algorithm Hash digest
SHA256 e4d4c5c0399d87b83497f15aef7d64be374846252b8d5e57a72e134f470d2d29
MD5 6b5342676c34cf269044e693e4f8acec
BLAKE2b-256 a4313f614c7e3de4f84267c1cc79d72055a15f966c94270421443f4b46df5d2e

See more details on using hashes here.

File details

Details for the file error_translator_cli_v2-1.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for error_translator_cli_v2-1.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d3bbd6eb92804bdf956738cbf01553f89335d1b7115c55c734213a1af4bc1fef
MD5 8dce3311a9067dbcb658c68cda271918
BLAKE2b-256 055bbc7b827da35f486526c9d914c6080a158844e0a9e137d8ba36b29c2ecc66

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page