Advanced Multilingual Exception Handler for Python
Complete documentation for translating Python errors into 11+ languages in real-time
pip install PolyglotX
git clone https://github.com/6x-u/polyglotx.git
cd polyglotx
pip install -e .
PolyglotX automatically installs the following dependencies:
from PolyglotX import arbe
# This will automatically catch and translate errors to Arabic
x = undefined_variable
# Output:
# خطأ في الاسم: name 'undefined_variable' is not defined
# MERO tele QP4RM
from PolyglotX import tr
result = 10 / 0
# Output:
# Sıfıra Bölme Hatası: division by zero
# MERO tele QP4RM
from PolyglotX import ja
my_list = [1, 2, 3]
value = my_list[10]
# Output:
# インデックスエラー: list index out of range
# MERO tele QP4RM
from PolyglotX import (
arbe, # Arabic - العربية
tr, # Turkish - Türkçe
ja, # Japanese - 日本語
zh, # Chinese - 中文
ku, # Kurdish - کوردی
es, # Spanish - Español
hi, # Hindi - हिन्दी
fr, # French - Français
ru, # Russian - Русский
de, # German - Deutsch
pt # Portuguese - Português
)
PolyglotX provides a comprehensive set of classes and functions organized into several modules. This section details every class, method, and function available in the library.
Core functionality including exception handlers, translators, error processors, and language detection
Error formatters, output handlers, signal handlers, and hook managers
Helper functions, decorators, validators, converters, and analyzers
Language-specific modules for 11 supported languages
Translation engine managers and adapters for multiple translation services
Command-line interface tools and commands
PolyglotX provides multiple exception handler classes, each designed for specific use cases. All handlers translate errors in real-time to your chosen language.
The base exception handler class. Use this for standard error handling with translation.
class ExceptionHandler(language: str = 'ar',
show_credits: bool = True,
auto_exit: bool = True)
| Parameter | Type | Default | Description |
|---|---|---|---|
| language | str | 'ar' | Target language code for translation (ar, tr, ja, zh, ku, es, hi, fr, ru, de, pt) |
| show_credits | bool | True | Whether to display "MERO tele QP4RM" message after error |
| auto_exit | bool | True | Whether to exit the program after handling exception |
| Method | Description |
|---|---|
| install() | Activates the exception handler globally |
| uninstall() | Deactivates the exception handler |
| get_error_stats() | Returns statistics about caught errors |
from PolyglotX.core.exception_handler import ExceptionHandler
# Create handler instance
handler = ExceptionHandler(
language='ar', # Arabic translation
show_credits=True, # Show credits
auto_exit=False # Don't exit after error
)
# Activate the handler
handler.install()
# Your code here - errors will be translated
try:
x = undefined_variable
except:
pass
# Get error statistics
stats = handler.get_error_stats()
print(f"Total errors: {stats['total_errors']}")
# Deactivate when done
handler.uninstall()
A singleton exception handler that ensures only one global instance exists. Useful for application-wide error handling.
from PolyglotX.core.exception_handler import GlobalExceptionHandler
# First instance
handler1 = GlobalExceptionHandler(language='ar')
# Second call returns the same instance
handler2 = GlobalExceptionHandler(language='tr')
# handler1 and handler2 are the same object
print(handler1 is handler2) # True
Translates individual errors without installing a global handler.
from PolyglotX.core.exception_handler import ErrorTranslator
translator = ErrorTranslator(language='ar')
try:
result = 10 / 0
except Exception as e:
translated = translator.translate_error(e)
print(translated)
# خطأ في القسمة على صفر: division by zero
Translates complete tracebacks including file locations and line numbers.
from PolyglotX.core.exception_handler import TracebackTranslator
import sys
translator = TracebackTranslator(language='ar')
try:
undefined_variable
except:
exc_info = sys.exc_info()
formatted = translator.format_traceback(exc_info)
print(formatted)
Includes local and global variables in error output for debugging.
from PolyglotX.core.exception_handler import ContextualErrorHandler
handler = ContextualErrorHandler(
language='ar',
include_locals=True, # Show local variables
include_globals=False # Don't show globals
)
handler.install()
Handles exceptions in async/await code.
from PolyglotX.core.exception_handler import AsyncExceptionHandler
import asyncio
handler = AsyncExceptionHandler(language='ar')
async def my_async_function():
await handler.handle_async_exception(
some_async_operation()
)
asyncio.run(my_async_function())
Thread-safe handler for multi-threaded applications.
from PolyglotX.core.exception_handler import ThreadSafeExceptionHandler
import threading
handler = ThreadSafeExceptionHandler(language='ar')
handler.install()
def worker():
# Errors in threads will be handled safely
x = undefined_variable
threads = [threading.Thread(target=worker) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
Chains multiple handlers together for complex error processing.
from PolyglotX.core.exception_handler import ChainedExceptionHandler
handler = ChainedExceptionHandler(language='ar')
handler.add_handler(custom_handler_1)
handler.add_handler(custom_handler_2)
handler.install()
Filters exceptions by type, allowing selective handling.
from PolyglotX.core.exception_handler import FilteredExceptionHandler
handler = FilteredExceptionHandler(
language='ar',
exception_types=[ValueError, TypeError] # Only handle these
)
handler.install()
Integrates with Python's logging module.
from PolyglotX.core.exception_handler import LoggingExceptionHandler
import logging
logging.basicConfig(level=logging.ERROR)
handler = LoggingExceptionHandler(
language='ar',
logger_name='my_app'
)
handler.install()
PolyglotX provides a powerful translation system with multiple engines and caching mechanisms.
The base translator class with automatic engine fallback.
from PolyglotX.core.translator import Translator
translator = Translator(
target_language='ar', # Target language
source_language='auto' # Auto-detect source
)
# Translate text
result = translator.translate("Error: File not found")
print(result) # خطأ: الملف غير موجود
# Translate with parts preservation
result = translator.translate_parts("File 'config.json' not found")
print(result) # Preserves 'config.json' while translating rest
Uses multiple translation engines with priority ordering.
from PolyglotX.core.translator import MultiEngineTranslator
translator = MultiEngineTranslator(
target_language='ar',
engines=['google', 'mymemory', 'libre'] # Priority order
)
result = translator.translate("ValueError")
Advanced caching with persistent storage.
from PolyglotX.core.translator import CachedTranslator
translator = CachedTranslator(
target_language='ar',
cache_file='translation_cache.json',
max_cache_size=10000
)
# First call: translates and caches
result1 = translator.translate("Error")
# Second call: retrieved from cache (instant)
result2 = translator.translate("Error")
# Get cache statistics
stats = translator.get_cache_stats()
print(f"Cache hit rate: {stats['hit_rate']}")
Efficient batch translation with parallel processing.
from PolyglotX.core.translator import BatchTranslator
translator = BatchTranslator(
target_language='ar',
batch_size=100,
parallel=True
)
errors = [
"TypeError: invalid type",
"ValueError: invalid value",
"NameError: name not defined",
# ... hundreds more
]
# Translate all at once
translated = translator.translate_batch(errors)
# Auto-batch with optimization
translated = translator.auto_translate_batch(errors)
Works offline using pre-downloaded dictionaries.
from PolyglotX.core.translator import OfflineTranslator
translator = OfflineTranslator(
target_language='ar',
dictionary_file='ar_dict.json'
)
# Works without internet
result = translator.translate("Error")
AI-powered translator with context awareness and quality checking.
from PolyglotX.core.translator import SmartTranslator
translator = SmartTranslator(
target_language='ar',
quality_threshold=0.8, # Minimum quality score
enable_ai=True # Use AI enhancement
)
result = translator.translate("Complex error message")
# Get translation quality score
quality = translator.get_quality_score(result)
| Engine | Languages | Speed | Quality | Requires API Key |
|---|---|---|---|---|
| Google Translate | 100+ | Fast | Excellent | No |
| MyMemory | 80+ | Medium | Good | No |
| LibreTranslate | 30+ | Medium | Good | Optional |
| DeepL | 26 | Fast | Excellent | Yes |
| Yandex | 90+ | Fast | Good | Yes |
Format translated errors in various output formats.
Colored console output with ANSI codes.
from PolyglotX.handlers.error_formatter import ColoredErrorFormatter
formatter = ColoredErrorFormatter(
language='ar',
color_scheme='dark' # 'dark' or 'light'
)
try:
x = 10 / 0
except Exception as e:
formatted = formatter.format(e)
print(formatted) # Colored output
HTML formatted errors for web display.
from PolyglotX.handlers.error_formatter import HTMLErrorFormatter
formatter = HTMLErrorFormatter(
language='ar',
style='bootstrap' # 'bootstrap', 'tailwind', or 'custom'
)
try:
x = undefined_variable
except Exception as e:
html = formatter.format(e)
# Returns complete HTML with styling
JSON formatted errors for API responses.
from PolyglotX.handlers.error_formatter import JSONErrorFormatter
import json
formatter = JSONErrorFormatter(
language='ar',
pretty=True # Pretty print JSON
)
try:
result = 10 / 0
except Exception as e:
json_output = formatter.format(e)
error_dict = json.loads(json_output)
print(error_dict['error_type'])
print(error_dict['error_message'])
print(error_dict['traceback'])
from PolyglotX.handlers.error_formatter import XMLErrorFormatter
formatter = XMLErrorFormatter(language='ar')
try:
my_list[100]
except Exception as e:
xml = formatter.format(e)
# Returns XML structure
from PolyglotX.handlers.error_formatter import MarkdownErrorFormatter
formatter = MarkdownErrorFormatter(language='ar')
try:
import nonexistent_module
except Exception as e:
markdown = formatter.format(e)
# Perfect for documentation
Direct error output to various destinations.
from PolyglotX.handlers.output_handler import ConsoleOutputHandler
handler = ConsoleOutputHandler(
language='ar',
colored=True
)
handler.handle(exception_object)
from PolyglotX.handlers.output_handler import FileOutputHandler
handler = FileOutputHandler(
language='ar',
file_path='errors.log',
mode='a', # Append mode
encoding='utf-8'
)
handler.handle(exception_object)
from PolyglotX.handlers.output_handler import EmailOutputHandler
handler = EmailOutputHandler(
language='ar',
smtp_server='smtp.gmail.com',
smtp_port=587,
sender='errors@myapp.com',
recipients=['admin@myapp.com'],
username='your_email',
password='your_password'
)
handler.handle(exception_object)
from PolyglotX.handlers.output_handler import WebhookOutputHandler
handler = WebhookOutputHandler(
language='ar',
webhook_url='https://hooks.slack.com/services/...',
method='POST',
headers={'Content-Type': 'application/json'}
)
handler.handle(exception_object)
from PolyglotX.handlers.output_handler import DatabaseOutputHandler
handler = DatabaseOutputHandler(
language='ar',
connection_string='postgresql://user:pass@localhost/db',
table_name='errors'
)
handler.handle(exception_object)
Simplify error handling with powerful decorators.
from PolyglotX.utils.decorators import handle_exceptions
@handle_exceptions(language='ar', show_credits=True)
def my_function():
x = undefined_variable
return x
# Errors are automatically caught and translated
my_function()
from PolyglotX.utils.decorators import translate_errors
@translate_errors(language='ar')
def divide(a, b):
return a / b
result = divide(10, 0) # Error translated to Arabic
from PolyglotX.utils.decorators import retry_on_error
@retry_on_error(max_retries=3, delay=1.0, language='ar')
def unreliable_operation():
# May fail, will retry up to 3 times
import random
if random.random() < 0.5:
raise ValueError("Random failure")
return "Success"
result = unreliable_operation()
from PolyglotX.utils.decorators import fallback_on_error
@fallback_on_error(fallback_value=None, language='ar')
def risky_operation():
x = undefined_variable
return x
result = risky_operation() # Returns None instead of crashing
from PolyglotX.utils.decorators import log_exceptions
import logging
logging.basicConfig(level=logging.ERROR)
@log_exceptions(language='ar', logger_name='my_app')
def my_function():
x = 10 / 0
my_function() # Error logged in Arabic
from PolyglotX.utils.decorators import measure_exception_time
@measure_exception_time(language='ar')
def slow_operation():
import time
time.sleep(2)
raise ValueError("Error after 2 seconds")
slow_operation() # Shows error + execution time
from PolyglotX.utils.decorators import suppress_exceptions
@suppress_exceptions(exception_types=[ValueError])
def my_function():
raise ValueError("This will be suppressed")
my_function() # No error raised
from PolyglotX.utils.decorators import notify_on_exception
@notify_on_exception(
language='ar',
email='admin@example.com',
webhook='https://hooks.slack.com/...'
)
def critical_operation():
# If error occurs, send notifications
raise RuntimeError("Critical error")
critical_operation()
from PolyglotX.utils.helpers import (
detect_language,
extract_error_info,
format_stack_trace,
parse_exception,
sanitize_error_message,
get_error_context,
calculate_error_hash,
group_similar_errors,
suggest_fixes,
find_error_documentation
)
# Detect language of text
lang = detect_language("مرحبا") # Returns 'ar'
# Extract error information
error_info = extract_error_info(exception_object)
# Format stack trace
formatted = format_stack_trace(traceback_object)
# Parse exception details
details = parse_exception(exception_object)
# Sanitize error message
clean_msg = sanitize_error_message("Error with sensitive data: API_KEY_123")
# Get error context
context = get_error_context(exception_object, lines_before=5, lines_after=5)
# Calculate unique hash for error
error_hash = calculate_error_hash(exception_object)
# Group similar errors
groups = group_similar_errors([error1, error2, error3])
# Get fix suggestions
suggestions = suggest_fixes(exception_object)
# Find documentation for error
docs = find_error_documentation("ValueError")
# Translate single text
polyglotx translate "Error occurred" --language ar
# Translate from file
polyglotx translate --file errors.txt --language ar --output translated.txt
# Interactive mode
polyglotx translate --interactive --language ar
# Test translation engine
polyglotx test --language ar
# Test specific errors
polyglotx test --errors ValueError TypeError --language ar
# Test all languages
polyglotx test --all-languages
# Benchmark translation speed
polyglotx benchmark --language ar --count 100
# Compare engines
polyglotx benchmark --compare-engines --language ar
# Set default language
polyglotx config set language ar
# Show configuration
polyglotx config show
# Reset to defaults
polyglotx config reset
from flask import Flask, jsonify
from PolyglotX.handlers.error_formatter import JSONErrorFormatter
from PolyglotX.core.exception_handler import ExceptionHandler
app = Flask(__name__)
formatter = JSONErrorFormatter(language='ar')
@app.errorhandler(Exception)
def handle_error(error):
json_error = formatter.format(error)
return jsonify(json_error), 500
@app.route('/api/data')
def get_data():
# Errors are automatically formatted in Arabic JSON
result = 10 / 0
return jsonify(result)
from PolyglotX.core.translator import Translator
class MultiLangErrorHandler:
def __init__(self):
self.translators = {
'ar': Translator('ar'),
'tr': Translator('tr'),
'ja': Translator('ja'),
'zh': Translator('zh-CN')
}
def translate_error(self, error, user_language):
translator = self.translators.get(user_language)
if translator:
return translator.translate(str(error))
return str(error)
handler = MultiLangErrorHandler()
translated = handler.translate_error(exception, 'ar')
from PolyglotX.core.context_manager import translated_errors
with translated_errors(language='ar', show_credits=True):
# All errors in this block are translated
x = undefined_variable
y = 10 / 0
# Outside the context, errors are normal
z = normal_error # Regular Python error
from PolyglotX.core.exception_handler import ChainedExceptionHandler
from PolyglotX.handlers.output_handler import (
FileOutputHandler,
EmailOutputHandler,
WebhookOutputHandler
)
# Create processing pipeline
handler = ChainedExceptionHandler(language='ar')
# Add file logging
handler.add_handler(FileOutputHandler(
language='ar',
file_path='errors.log'
))
# Add email notifications for critical errors
handler.add_handler(EmailOutputHandler(
language='ar',
smtp_server='smtp.gmail.com',
recipients=['admin@example.com']
))
# Add Slack webhook
handler.add_handler(WebhookOutputHandler(
language='ar',
webhook_url='https://hooks.slack.com/...'
))
handler.install()
| Language | Code | Native Name | Import Module | Direction |
|---|---|---|---|---|
| Arabic | ar | العربية | from PolyglotX import arbe | RTL |
| Turkish | tr | Türkçe | from PolyglotX import tr | LTR |
| Japanese | ja | 日本語 | from PolyglotX import ja | LTR |
| Chinese | zh / zh-CN | 中文 | from PolyglotX import zh | LTR |
| Kurdish | ku | کوردی | from PolyglotX import ku | RTL |
| Spanish | es | Español | from PolyglotX import es | LTR |
| Hindi | hi | हिन्दी | from PolyglotX import hi | LTR |
| French | fr | Français | from PolyglotX import fr | LTR |
| Russian | ru | Русский | from PolyglotX import ru | LTR |
| German | de | Deutsch | from PolyglotX import de | LTR |
| Portuguese | pt | Português | from PolyglotX import pt | LTR |
import PolyglotX
# Set global defaults
PolyglotX.set_default_language('ar')
PolyglotX.set_show_credits(True)
PolyglotX.set_auto_exit(False)
# Configure caching
PolyglotX.set_cache_enabled(True)
PolyglotX.set_cache_size(10000)
PolyglotX.set_cache_ttl(3600) # 1 hour
# Configure translation engines
PolyglotX.set_preferred_engine('google')
PolyglotX.set_engine_timeout(10.0)
PolyglotX.set_retry_attempts(3)
# Create polyglotx.yaml
default:
language: ar
show_credits: true
auto_exit: false
cache:
enabled: true
size: 10000
ttl: 3600
engines:
preferred: google
timeout: 10.0
retry: 3
fallback: [mymemory, libre]
output:
format: colored
file: errors.log
translation:
quality_threshold: 0.8
preserve_variables: true
translate_stack_trace: true
# Check internet connection
import requests
try:
requests.get('https://translate.google.com', timeout=5)
print("Connection OK")
except:
print("Connection failed")
# Test translator directly
from PolyglotX.core.translator import Translator
translator = Translator('ar')
result = translator.translate("test")
print(result)
# Ensure UTF-8 encoding
import sys
sys.stdout.reconfigure(encoding='utf-8')
# For file output
with open('errors.log', 'w', encoding='utf-8') as f:
f.write(translated_error)
# Clear cache
from PolyglotX.core.translator import CachedTranslator
translator = CachedTranslator('ar')
translator.clear_cache()
# Disable cache temporarily
translator.set_cache_enabled(False)
مكتبة قوية لترجمة أخطاء بايثون لأي لغة
دليل كامل يشرح طريقة ترجمة أخطاء بايثون إلى 11 لغة مختلفة
pip install PolyglotX
git clone https://github.com/6x-u/polyglotx.git
cd polyglotx
pip install -e .
تثبت تلقائياً مع المكتبة:
from PolyglotX import arbe
# سيتم التقاط وترجمة الأخطاء تلقائياً إلى العربية
x = undefined_variable
# النتيجة:
# خطأ في الاسم: name 'undefined_variable' is not defined
# MERO tele QP4RM
from PolyglotX import (
arbe, # العربية
tr, # التركية
ja, # اليابانية
zh, # الصينية
ku, # الكردية
es, # الإسبانية
hi, # الهندية
fr, # الفرنسية
ru, # الروسية
de, # الألمانية
pt # البرتغالية
)
المكتبة توفر عدة أنواع لمعالجة الأخطاء، كل نوع له استخدام معين. جميعها تترجم الأخطاء مباشرة للغة اللي تختارها.
النوع الأساسي لمعالجة الأخطاء. استخدمه لمعالجة الأخطاء العادية مع الترجمة.
class ExceptionHandler(language: str = 'ar',
show_credits: bool = True,
auto_exit: bool = True)
| المعامل | النوع | الافتراضي | الوصف |
|---|---|---|---|
| language | str | 'ar' | اللغة اللي تبي تترجم لها (ar, tr, ja, zh, ku, es, hi, fr, ru, de, pt) |
| show_credits | bool | True | يعرض رسالة "MERO tele QP4RM" بعد الخطأ أو لا |
| auto_exit | bool | True | يطفي البرنامج بعد الخطأ أو لا |
| الطريقة | الوصف |
|---|---|
| install() | يشغل معالج الأخطاء |
| uninstall() | يوقف معالج الأخطاء |
| get_error_stats() | يعطيك معلومات عن الأخطاء اللي صارت |
from PolyglotX.core.exception_handler import ExceptionHandler
# إنشاء نسخة من المعالج
handler = ExceptionHandler(
language='ar', # ترجمة عربية
show_credits=True, # إظهار الاعتمادات
auto_exit=False # عدم الخروج بعد الخطأ
)
# تنشيط المعالج
handler.install()
# الكود الخاص بك هنا - سيتم ترجمة الأخطاء
try:
x = undefined_variable
except:
pass
# الحصول على إحصائيات الأخطاء
stats = handler.get_error_stats()
print(f"إجمالي الأخطاء: {stats['total_errors']}")
# إلغاء التنشيط عند الانتهاء
handler.uninstall()
المكتبة فيها نظام ترجمة يستخدم عدة محركات مع حفظ الترجمات.
المترجم الأساسي، يستخدم محركات مختلفة تلقائياً.
from PolyglotX.core.translator import Translator
translator = Translator(
target_language='ar', # اللغة المستهدفة
source_language='auto' # اكتشاف المصدر تلقائياً
)
# ترجمة النص
result = translator.translate("Error: File not found")
print(result) # خطأ: الملف غير موجود
# ترجمة مع الحفاظ على الأجزاء
result = translator.translate_parts("File 'config.json' not found")
print(result) # يحفظ 'config.json' مع ترجمة الباقي
مترجم يحفظ الترجمات في ملف بحيث ما يترجم نفس الشيء مرتين.
from PolyglotX.core.translator import CachedTranslator
translator = CachedTranslator(
target_language='ar',
cache_file='translation_cache.json',
max_cache_size=10000
)
# المكالمة الأولى: يترجم ويخزن مؤقتاً
result1 = translator.translate("Error")
# المكالمة الثانية: استرداد من ذاكرة التخزين المؤقت (فوري)
result2 = translator.translate("Error")
# الحصول على إحصائيات ذاكرة التخزين المؤقت
stats = translator.get_cache_stats()
print(f"معدل إصابة ذاكرة التخزين المؤقت: {stats['hit_rate']}")
يترجم مجموعة أخطاء مرة وحدة بسرعة.
from PolyglotX.core.translator import BatchTranslator
translator = BatchTranslator(
target_language='ar',
batch_size=100,
parallel=True
)
errors = [
"TypeError: invalid type",
"ValueError: invalid value",
"NameError: name not defined",
# ... مئات أكثر
]
# ترجمة الكل دفعة واحدة
translated = translator.translate_batch(errors)
# دفعة تلقائية مع التحسين
translated = translator.auto_translate_batch(errors)
| اللغة | الرمز | الاسم الأصلي | وحدة الاستيراد | الاتجاه |
|---|---|---|---|---|
| العربية | ar | العربية | from PolyglotX import arbe | RTL |
| التركية | tr | Türkçe | from PolyglotX import tr | LTR |
| اليابانية | ja | 日本語 | from PolyglotX import ja | LTR |
| الصينية | zh / zh-CN | 中文 | from PolyglotX import zh | LTR |
| الكردية | ku | کوردی | from PolyglotX import ku | RTL |
| الإسبانية | es | Español | from PolyglotX import es | LTR |
| الهندية | hi | हिन्दी | from PolyglotX import hi | LTR |
| الفرنسية | fr | Français | from PolyglotX import fr | LTR |
| الروسية | ru | Русский | from PolyglotX import ru | LTR |
| الألمانية | de | Deutsch | from PolyglotX import de | LTR |
| البرتغالية | pt | Português | from PolyglotX import pt | LTR |