PolyglotX

Advanced Multilingual Exception Handler for Python

PolyglotX Banner

Complete documentation for translating Python errors into 11+ languages in real-time

Installation

From PyPI (Recommended)

pip install PolyglotX

From GitHub Source

git clone https://github.com/6x-u/polyglotx.git
cd polyglotx
pip install -e .

System Requirements

  • Python 3.6 or higher
  • Internet connection for translation services
  • Minimum 512MB RAM
  • Works on Windows, macOS, Linux

Dependencies

PolyglotX automatically installs the following dependencies:

  • deep-translator >= 1.11.0
  • translatepy >= 2.3
  • requests >= 2.25.0
  • colorama >= 0.4.0
  • pyyaml >= 5.4.0
  • click >= 8.0.0

Quick Start Guide

Basic Usage - Language Specific Imports

Arabic Example

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

Turkish Example

from PolyglotX import tr

result = 10 / 0

# Output:
# Sıfıra Bölme Hatası: division by zero
# MERO tele QP4RM

Japanese Example

from PolyglotX import ja

my_list = [1, 2, 3]
value = my_list[10]

# Output:
# インデックスエラー: list index out of range
# MERO tele QP4RM

All Available Language Imports

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
)

Core Classes and Functions

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.

Module Structure

PolyglotX.core

Core functionality including exception handlers, translators, error processors, and language detection

PolyglotX.handlers

Error formatters, output handlers, signal handlers, and hook managers

PolyglotX.utils

Helper functions, decorators, validators, converters, and analyzers

PolyglotX.languages

Language-specific modules for 11 supported languages

PolyglotX.translators

Translation engine managers and adapters for multiple translation services

PolyglotX.cli

Command-line interface tools and commands

Exception Handlers

PolyglotX provides multiple exception handler classes, each designed for specific use cases. All handlers translate errors in real-time to your chosen language.

1. ExceptionHandler

The base exception handler class. Use this for standard error handling with translation.

Class Signature

class ExceptionHandler(language: str = 'ar', 
                       show_credits: bool = True, 
                       auto_exit: bool = True)

Parameters

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

Methods

Method Description
install() Activates the exception handler globally
uninstall() Deactivates the exception handler
get_error_stats() Returns statistics about caught errors

Complete Usage Example

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()

2. GlobalExceptionHandler

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

3. ErrorTranslator

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

4. TracebackTranslator

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)

5. ContextualErrorHandler

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()

6. AsyncExceptionHandler

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())

7. ThreadSafeExceptionHandler

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()

8. ChainedExceptionHandler

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()

9. FilteredExceptionHandler

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()

10. LoggingExceptionHandler

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()

Translation System

PolyglotX provides a powerful translation system with multiple engines and caching mechanisms.

1. Translator

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

2. MultiEngineTranslator

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")

3. CachedTranslator

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']}")

4. BatchTranslator

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)

5. OfflineTranslator

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")

6. SmartTranslator

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)

Translation Engine Support

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

Error Formatters

Format translated errors in various output formats.

Available Formatters

1. ColoredErrorFormatter

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

2. HTMLErrorFormatter

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

3. JSONErrorFormatter

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'])

4. XMLErrorFormatter

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

5. MarkdownErrorFormatter

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

Output Handlers

Direct error output to various destinations.

1. ConsoleOutputHandler

from PolyglotX.handlers.output_handler import ConsoleOutputHandler

handler = ConsoleOutputHandler(
    language='ar',
    colored=True
)

handler.handle(exception_object)

2. FileOutputHandler

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)

3. EmailOutputHandler

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)

4. WebhookOutputHandler

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)

5. DatabaseOutputHandler

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)

Decorators

Simplify error handling with powerful decorators.

1. @handle_exceptions

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()

2. @translate_errors

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

3. @retry_on_error

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()

4. @fallback_on_error

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

5. @log_exceptions

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

6. @measure_exception_time

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

7. @suppress_exceptions

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

8. @notify_on_exception

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()

Utility Functions

Helper Functions

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")

Command Line Tools

Available CLI Commands

1. Translate Command

# 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

2. Test Command

# Test translation engine
polyglotx test --language ar

# Test specific errors
polyglotx test --errors ValueError TypeError --language ar

# Test all languages
polyglotx test --all-languages

3. Benchmark Command

# Benchmark translation speed
polyglotx benchmark --language ar --count 100

# Compare engines
polyglotx benchmark --compare-engines --language ar

4. Config Command

# Set default language
polyglotx config set language ar

# Show configuration
polyglotx config show

# Reset to defaults
polyglotx config reset

Advanced Usage Examples

Example 1: Web Application Error Handling

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)

Example 2: Multi-Language Support

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')

Example 3: Context Manager Usage

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

Example 4: Custom Error Processing Pipeline

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()

Supported Languages

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

Configuration Options

Global Configuration

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)

Configuration File

# 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

Best Practices

Performance Optimization
  • Enable caching for production environments
  • Use CachedTranslator for frequently translated errors
  • Batch translate when processing multiple errors
  • Consider OfflineTranslator for offline applications
Security Considerations
  • Sanitize error messages before translation to remove sensitive data
  • Use FileOutputHandler instead of console in production
  • Encrypt error logs containing translated messages
  • Limit error context to avoid exposing internal code
Production Deployment
  • Set auto_exit=False for web applications
  • Use LoggingExceptionHandler for proper logging
  • Configure email notifications for critical errors
  • Monitor translation API usage and costs
  • Use CDN for offline dictionaries

Troubleshooting

Common Issues

Translation Not Working

# 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)

Character Encoding Issues

# 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)

Cache Issues

# Clear cache
from PolyglotX.core.translator import CachedTranslator
translator = CachedTranslator('ar')
translator.clear_cache()

# Disable cache temporarily
translator.set_cache_enabled(False)

PolyglotX

مكتبة قوية لترجمة أخطاء بايثون لأي لغة

لافتة PolyglotX

دليل كامل يشرح طريقة ترجمة أخطاء بايثون إلى 11 لغة مختلفة

التثبيت

من PyPI (موصى به)

pip install PolyglotX

من مصدر GitHub

git clone https://github.com/6x-u/polyglotx.git
cd polyglotx
pip install -e .

ما تحتاجه

  • بايثون 3.6 أو أحدث
  • إنترنت للترجمة
  • 512 ميجابايت رام
  • يعمل على ويندوز وماك ولينكس

المكتبات المطلوبة

تثبت تلقائياً مع المكتبة:

  • deep-translator >= 1.11.0
  • translatepy >= 2.3
  • requests >= 2.25.0
  • colorama >= 0.4.0
  • pyyaml >= 5.4.0
  • click >= 8.0.0

كيف تبدأ

طريقة الاستخدام البسيطة

مثال العربية

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     # البرتغالية
)

معالجات الأخطاء

المكتبة توفر عدة أنواع لمعالجة الأخطاء، كل نوع له استخدام معين. جميعها تترجم الأخطاء مباشرة للغة اللي تختارها.

1. ExceptionHandler

النوع الأساسي لمعالجة الأخطاء. استخدمه لمعالجة الأخطاء العادية مع الترجمة.

طريقة الاستخدام

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()

المترجم

المكتبة فيها نظام ترجمة يستخدم عدة محركات مع حفظ الترجمات.

1. Translator

المترجم الأساسي، يستخدم محركات مختلفة تلقائياً.

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' مع ترجمة الباقي

2. CachedTranslator

مترجم يحفظ الترجمات في ملف بحيث ما يترجم نفس الشيء مرتين.

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']}")

3. BatchTranslator

يترجم مجموعة أخطاء مرة وحدة بسرعة.

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