AccessibleTranslator python SDK - complete demoΒΆ

This notebook demonstrates the complete functionality of the AccessibleTranslator Python SDK.

Features covered:ΒΆ

  • βœ… API key authentication
  • βœ… Health check
  • βœ… Available transformations
  • βœ… Target languages
  • βœ… Word balance management
  • βœ… Text translation examples
  • βœ… Error handling
  • βœ… Common use cases
  • βœ… Performance testing

InstallationΒΆ

First, install the SDK from TestPyPI:

pip install -i https://test.pypi.org/simple/ accessibletranslator

Or from production PyPI:

pip install accessibletranslator

1. Setup and configurationΒΆ

⚠️ Important: Replace 'sk_your_api_key_here' with your actual API key from AccessibleTranslator.

InΒ [Β ]:
import asyncio
import json
import time
from datetime import datetime

# Import the SDK
import accessibletranslator
from accessibletranslator.models.translation_request import TranslationRequest
from accessibletranslator.exceptions import ApiException

# ⚠️ SET YOUR API KEY HERE
# It would be more secure to store this in an environment variable, but for demo purposes it's kept here
API_KEY = 'sk_your_api_key_here'  # Replace with your actual API key

# Configure the SDK with Bearer authentication
configuration = accessibletranslator.Configuration(
    api_key={'ApiKeyAuth': API_KEY},
    api_key_prefix={'ApiKeyAuth': 'Bearer'},
    retries=10 # Enable retries in case of API rate limiting
)

print("βœ… SDK configured successfully!")
print(f"πŸ“‘ API host: {configuration.host}")
print(f"πŸ”‘ API key: {API_KEY[:20]}..." if len(API_KEY) > 20 else f"πŸ”‘ API Key: {API_KEY}")
print("πŸ” Authentication: Bearer token configured")
βœ… SDK configured successfully!
πŸ“‘ API host: https://api.accessibletranslator.com
πŸ”‘ API key: sk_d1a55df3f244a9385...
πŸ” Authentication: Bearer token configured

2. Health checkΒΆ

Let's start by checking if the API is healthy and accessible.

InΒ [Β ]:
async def check_api_health():
    """Check API health status"""
    async with accessibletranslator.ApiClient(configuration) as api_client:
        system_api = accessibletranslator.SystemApi(api_client)
        
        try:
            health = await system_api.check()
            print(f"🟒 API Status: {health.status}")
            print(f"⏰ Timestamp: {health.timestamp}")
            return health
        except Exception as e:
            print(f"πŸ”΄ Health check failed: {e}")
            return None
InΒ [3]:
# Run health check
health_result = await check_api_health()
🟒 API Status: ok
⏰ Timestamp: 2025-07-16T16:28:16.424591Z

3. Authentication & word balanceΒΆ

Check your account's word balance and verify authentication.

InΒ [Β ]:
async def check_word_balance():
    """Check remaining word balance"""
    async with accessibletranslator.ApiClient(configuration) as api_client:
        user_api = accessibletranslator.UserManagementApi(api_client)
        
        try:
            balance = await user_api.word_balance()
            print(f"πŸ’° Word balance: {balance.word_balance:,} words")
            
            if balance.word_balance > 1000:
                print("βœ… Sufficient balance for demos")
            elif balance.word_balance > 100:
                print("⚠️ Low balance - consider topping up")
            else:
                    print("πŸ”΄ Very low balance - demos may fail")
                
            return balance
        except ApiException as e:
            if e.status == 401:
                print("πŸ”΄ Authentication failed - check your API key")
            else:
                print(f"πŸ”΄ Error checking balance: {e.status} - {e.reason}")
            return None
InΒ [5]:
# Check balance
balance_result = await check_word_balance()
πŸ’° Word balance: 239,458 words
βœ… Sufficient balance for demos

4. Available transformationsΒΆ

Whenever you want to make a text more accessible, you need to specify a list of transformations that you want to apply to that text. There are 50+ possible transformations that you can combine into your preferred combination. This function can be used to show a list of available transformations.

InΒ [Β ]:
async def get_available_transformations():
    """Get all available transformations"""
    async with accessibletranslator.ApiClient(configuration) as api_client:
        translation_api = accessibletranslator.TranslationApi(api_client)
        
        try:
            transformations = await translation_api.transformations()
            
            print(f"πŸ“‹ Available Transformations: {transformations.total_transformations}")
            print("=" * 80)
            
            # Group transformations by category
            language_transforms = []
            clarity_transforms = []
            structure_transforms = []
            other_transforms = []
            
            for t in transformations.transformations:
                if t.name.startswith('language_'):
                    language_transforms.append(t)
                elif t.name.startswith('clarity_'):
                    clarity_transforms.append(t)
                elif t.name.startswith('structure_'):
                    structure_transforms.append(t)
                else:
                    other_transforms.append(t)
            
            # Display by category
            categories = [
                ("πŸ—£οΈ Language Transformations", language_transforms),
                ("πŸ” Clarity Transformations", clarity_transforms),
                ("πŸ“ Structure Transformations", structure_transforms),
                ("πŸ”§ Other Transformations", other_transforms)
            ]
            
            for category_name, transforms in categories:
                if transforms:
                    print(f"\n{category_name}:")
                    for t in transforms:
                        print(f"  β€’ {t.name}")
                        print(f"    {t.description}")
                        print("")
            return transformations
        except Exception as e:
            print(f"πŸ”΄ Error getting transformations: {e}")
            return None
InΒ [7]:
# Get transformations
transformations_result = await get_available_transformations()
πŸ“‹ Available Transformations: 52
================================================================================

πŸ—£οΈ Language Transformations:
  β€’ language_add_synonyms
    Add simple synonyms in parentheses: "recommend (suggest)".

  β€’ language_child_words
    Use extremely simple vocabulary (child-level words).

  β€’ language_common_words
    Use common words.

  β€’ language_direct
    Use direct language.

  β€’ language_literal
    Use literal, straightforward language. Do not use idioms, metaphors, sarcasm or irony.

  β€’ language_no_abbreviations
    Write out abbreviations in full.

  β€’ language_no_ambiguous
    Avoid ambiguous phrases with multiple interpretations.

  β€’ language_no_complex_clauses
    Do not use complex grammatical clauses.

  β€’ language_no_complex_grammar
    Do not use complex grammar.

  β€’ language_no_jargon
    Avoid all jargon and technical terms, or explain what they mean.

  β€’ language_no_loan_words
    Do not use loanwords (e.g. do not use English words in an otherwise Dutch text)

  β€’ language_no_oversimplification
    Do not make vocabulary too simple.

  β€’ language_older_age
    Use appropriate language, references and examples for someone who is 60+ years old.

  β€’ language_one_idea
    Use a maximum of 1 idea per sentence.

  β€’ language_positive
    Use positive phrasing: "Remember to drink water" not "Do not forget to drink water".

  β€’ language_short_sentences
    Use short sentences.

  β€’ language_simple_sentences
    Use simple sentences.

  β€’ language_very_simple_sentences
    Use very short sentences with subject-verb-object only.


πŸ” Clarity Transformations:
  β€’ clarity_concrete_examples
    Provide concrete examples with difficult concepts, instead of abstract concepts.

  β€’ clarity_consistency
    Use consistent terminology throughout the text.

  β€’ clarity_context_brackets
    Provide context in brackets: "groceries (food like bread and milk)".

  β€’ clarity_correct_incorrect
    Give correct/incorrect examples when helpful for understanding.

  β€’ clarity_everyday_examples
    Use only familiar, everyday, real-life examples.

  β€’ clarity_explain_difficult_words
    Explain unfamiliar words immediately: "Receipt (paper showing what you bought)".

  β€’ clarity_extremely_specific
    Be extremely specific: "Bus comes at 3 PM" not "approximately".

  β€’ clarity_mental_image
    Use only literal descriptions that create clear mental images.

  β€’ clarity_no_abstract
    Avoid abstract concepts and "what if" scenarios.

  β€’ clarity_no_vague
    Replace vague terms like "soon" or "later" if possible.

  β€’ clarity_only_essential_examples
    Do not add examples unless essential.

  β€’ clarity_pronouns
    Clarify pronouns: "Maria gave Lisa the book. Lisa liked the book" not "She gave it to her and she liked it"


πŸ“ Structure Transformations:
  β€’ structure_bullet_points
    Introduce bullet points to the text if it makes the text more structured.

  β€’ structure_concise_explanations
    Keep explanations concise.

  β€’ structure_headers
    Introduce headers throughout the text.

  β€’ structure_main_point_first
    State the main point at the beginning of each section.

  β€’ structure_number_processes
    Break complex processes into numbered steps.

  β€’ structure_one_step
    Use maximum 1 step per sentence.

  β€’ structure_practical_benefits
    Explain practical benefits first: "Brushing teeth keeps them healthy. Brush twice daily."

  β€’ structure_predictable_flow
    Use a predictable information flow.

  β€’ structure_repeat_important
    Repeat essential information in different ways.

  β€’ structure_split_all_paragraphs
    Split all paragraphs into very small chunks.

  β€’ structure_split_long_paragraphs
    Split long paragraphs into smaller chunks.

  β€’ structure_steps
    Present information step-by-step in manageable chunks.


πŸ”§ Other Transformations:
  β€’ attention_no_distractions
    Remove or minimize distracting elements.

  β€’ content_maintain_all_information
    Maintain all information.

  β€’ content_maintain_essential_information
    Maintain all essential information.

  β€’ content_maintain_important_information
    Maintain all important information.

  β€’ content_practical
    Focus on practical, useful information.

  β€’ content_technical_definitions
    If technical terms needed, define simply: "Photosynthesis means how plants make food".

  β€’ meta_plain_text
    Do not use markdown formatting.

  β€’ meta_repeat
    After completing, apply all textual transformations again to simplify the text further.

  β€’ tone_encouraging
    Use encouraging, supportive language.

  β€’ tone_respectful
    Maintain a respectful, non-judgmental tone.

5. Target languagesΒΆ

Texts can also be made accessible in another language. Use this function to see what languages are supported for translation.

InΒ [Β ]:
async def get_target_languages():
    """Get available target languages"""
    async with accessibletranslator.ApiClient(configuration) as api_client:
        translation_api = accessibletranslator.TranslationApi(api_client)
        
        try:
            languages = await translation_api.target_languages()
            
            print(f"🌍 Supported Languages: {languages.total_languages}")
            print("=" * 50)
            
            for i, lang in enumerate(languages.languages, 1):
                if lang == "Same as input":
                    print(f"  {i}. {lang} ⭐ (Default)")
                else:
                    print(f"  {i}. {lang}")
            
            return languages
        except Exception as e:
            print(f"πŸ”΄ Error getting languages: {e}")
            return None
InΒ [9]:
# Get languages
languages_result = await get_target_languages()
🌍 Supported Languages: 10
==================================================
  1. Same as input ⭐ (Default)
  2. Dutch
  3. English
  4. French
  5. German
  6. Italian
  7. Polish
  8. Portuguese
  9. Spanish
  10. Turkish

6. Basic text translationΒΆ

Let's start with some basic text transformation examples.

InΒ [Β ]:
async def translate_text(text, transformations, target_language="Same as input", show_details=True):
    """Translate text using specified transformations"""
    async with accessibletranslator.ApiClient(configuration) as api_client:
        translation_api = accessibletranslator.TranslationApi(api_client)
        
        try:
            request = TranslationRequest(
                text=text,
                transformations=transformations,
                target_language=target_language
            )
            
            start_time = time.time()
            result = await translation_api.translate(request)
            end_time = time.time()
            
            if show_details:
                print(f"πŸ“ Original Text ({result.input_word_count} words):")
                print(f"   {text}")
                print(f"\n✨ Transformed Text:")
                print(f"   {result.translated_text}")
                print(f"\nπŸ“Š Statistics:")
                print(f"   β€’ Input Language: {result.input_language}")
                print(f"   β€’ Output Language: {result.output_language}")
                print(f"   β€’ Words Used: {result.words_used}")
                print(f"   β€’ Processing Time: {result.processing_time_ms}ms")
                print(f"   β€’ Local Time: {(end_time - start_time)*1000:.0f}ms")
                print(f"   β€’ Remaining Balance: {result.word_balance:,} words")
                
                if result.explanations:
                    print(f"\nπŸ’‘ Explanations:")
                    print(f"{result.explanations}")
            
            return result
        except ApiException as e:
            print(f"πŸ”΄ Translation failed: {e.status} - {e.reason}")
            return None
        except Exception as e:
            print(f"πŸ”΄ Unexpected error: {e}")
            return None

Simple sentence translation

InΒ [11]:
# Example 1: Simple sentence translation
text = "The implementation of this algorithm requires substantial computational resources " \
    "and exhibits significant complexity in its operational parameters."
transformations = [
    "language_simple_sentences", 
    "language_common_words", 
    "language_add_synonyms", 
    "content_technical_definitions", 
    "language_no_jargon"
    ]

print("πŸ”„ Example 1: Simple sentence transformation")
print("=" * 60)
result1 = await translate_text(
    text=text,
    transformations=transformations
)
print("\n" + "="*60 + "\n")
πŸ”„ Example 1: Simple sentence transformation
============================================================
πŸ“ Original Text (17 words):
   The implementation of this algorithm requires substantial computational resources and exhibits significant complexity in its operational parameters.

✨ Transformed Text:
   The use of this computer program needs a lot of computer power and shows big difficulty (complexity) in how it works.

πŸ“Š Statistics:
   β€’ Input Language: English
   β€’ Output Language: English
   β€’ Words Used: 17
   β€’ Processing Time: 2721ms
   β€’ Local Time: 3208ms
   β€’ Remaining Balance: 239,441 words

============================================================

Simple sentence translation, removing metaphors and figurative speech

InΒ [12]:
# Example 2: Remove metaphors and figurative speech
text = "It's raining cats and dogs outside, so we should probably stay indoors and wait for it to pass." 
transformations = [
    "language_literal", 
    "language_direct", 
    "clarity_no_vague", 
    "clarity_mental_image",
    "clarity_no_abstract"
    ]

print("πŸ”„ Example 2: Remove metaphors and figurative speech")
print("=" * 60)
result2 = await translate_text(
    text=text,
    transformations=transformations
)
print("\n" + "="*60 + "\n")
πŸ”„ Example 2: Remove metaphors and figurative speech
============================================================
πŸ“ Original Text (18 words):
   It's raining cats and dogs outside, so we should probably stay indoors and wait for it to pass.

✨ Transformed Text:
   It is raining very heavily outside, so we should stay inside the building and wait for the rain to stop.

πŸ“Š Statistics:
   β€’ Input Language: English
   β€’ Output Language: English
   β€’ Words Used: 18
   β€’ Processing Time: 2078ms
   β€’ Local Time: 2610ms
   β€’ Remaining Balance: 239,423 words

============================================================

Longer text translation with more transformations

InΒ [13]:
# Example 3: Longer text
text = """
The recent implementation of our new customer relationship management system has resulted in
significant operational challenges that our team wasn't adequately prepared for. The primary
issue stems from integration difficulties with legacy databases that contain decades of
customer information, which have proven remarkably resistant to modern migration protocols.
Despite multiple attempts at synchronization by our IT department, these systems continue to
generate inconsistent data outputs that fundamentally undermine the reliability of our
quarterly reporting processes. This has created a cascading effect throughout the
organization, where department heads are increasingly questioning the validity of performance
metrics they've historically relied upon for strategic decision-making initiatives.
Simultaneously, our customer service representatives are experiencing substantial difficulties
accessing complete client histories during support interactions, which has resulted in
prolonged resolution times and measurably diminished customer satisfaction scores. These
interconnected issues could potentially compromise our competitive market positioning if not
addressed through a comprehensive overhaul of both our technical infrastructure and employee
training protocols, assuming we can secure the necessary budget allocation and executive
buy-in for such an extensive organizational undertaking.
"""
transformations = [
    "language_literal", 
    "language_direct", 
    "language_short_sentences",
    "language_simple_sentences",
    "language_common_words",
    "language_no_complex_grammar",
    "language_no_jargon",
    "language_add_synonyms",
    "clarity_consistency",
    "content_maintain_important_information",
    "structure_steps",
    "structure_split_long_paragraphs",
    "structure_predictable_flow",
    "structure_main_point_first",
    "meta_plain_text"
    ]

print("πŸ”„ Example 3: Longer text")
print("=" * 60)
result3 = await translate_text(
    text=text,
    transformations=transformations
)
print("\n" + "="*60 + "\n")
πŸ”„ Example 3: Longer text
============================================================
πŸ“ Original Text (175 words):
   
The recent implementation of our new customer relationship management system has resulted in
significant operational challenges that our team wasn't adequately prepared for. The primary
issue stems from integration difficulties with legacy databases that contain decades of
customer information, which have proven remarkably resistant to modern migration protocols.
Despite multiple attempts at synchronization by our IT department, these systems continue to
generate inconsistent data outputs that fundamentally undermine the reliability of our
quarterly reporting processes. This has created a cascading effect throughout the
organization, where department heads are increasingly questioning the validity of performance
metrics they've historically relied upon for strategic decision-making initiatives.
Simultaneously, our customer service representatives are experiencing substantial difficulties
accessing complete client histories during support interactions, which has resulted in
prolonged resolution times and measurably diminished customer satisfaction scores. These
interconnected issues could potentially compromise our competitive market positioning if not
addressed through a comprehensive overhaul of both our technical infrastructure and employee
training protocols, assuming we can secure the necessary budget allocation and executive
buy-in for such an extensive organizational undertaking.


✨ Transformed Text:
   We started using a new computer system to manage customer information. This has caused many problems. Our team was not ready for these problems.

The main problem is with old databases. These databases store customer information from many years. The old databases do not work well with the new system. We tried many times to move the information. Our computer team worked hard on this. But the systems still give wrong information.

This wrong information makes our reports unreliable (not trustworthy). We make reports every three months. These reports are now not accurate.

This problem affects the whole company. Department managers do not trust the numbers anymore. They used these numbers to make important business decisions. Now they question if the numbers are correct.

Our customer service workers also have problems. They cannot see complete customer history when helping customers. This makes it take longer to solve customer problems. Customers are less happy with our service now.

All these problems connect to each other. They could hurt our business compared to other companies. We need to fix our computer systems completely. We also need to train employees better.

To do this, we need money and support from company leaders. This will be a big project for the whole organization.

πŸ“Š Statistics:
   β€’ Input Language: English
   β€’ Output Language: English
   β€’ Words Used: 175
   β€’ Processing Time: 10868ms
   β€’ Local Time: 11339ms
   β€’ Remaining Balance: 239,248 words

============================================================

7. Advanced use casesΒΆ

Let's explore more advanced translation scenarios.

Simple sentence translation with explanations (explanations take longer)

InΒ [14]:
# Example 4: Simple sentence translation with explanations (explanations take longer)
text = "The CEO's strategic initiative to leverage synergistic opportunities will revolutionize our paradigm."
transformations = [
        "language_simple_sentences",
        "language_common_words",
        "language_direct",
        "language_no_jargon",
        "clarity_pronouns",
        "explain_changes"
    ]

print("πŸ“š Example 4: Simple sentence translation with explanations (explanations take longer)")
print("=" * 60)
result4 = await translate_text(
    text=text,
    transformations=transformations
)
print("\n" + "="*60 + "\n")
πŸ“š Example 4: Simple sentence translation with explanations (explanations take longer)
============================================================
πŸ“ Original Text (12 words):
   The CEO's strategic initiative to leverage synergistic opportunities will revolutionize our paradigm.

✨ Transformed Text:
   The CEO's plan to use teamwork opportunities will completely change how we work.

πŸ“Š Statistics:
   β€’ Input Language: English
   β€’ Output Language: English
   β€’ Words Used: 12
   β€’ Processing Time: 12125ms
   β€’ Local Time: 12647ms
   β€’ Remaining Balance: 239,236 words

πŸ’‘ Explanations:
The original text contained several complex business terms that were simplified to make the content more accessible for people with cognitive disabilities. "Strategic initiative" was changed to "plan" because this is a more common, everyday word that most people understand immediately. "Leverage" was replaced with "use" as it's a simpler, more direct verb that doesn't require specialized business knowledge. "Synergistic opportunities" was simplified to "teamwork opportunities" because "synergistic" is technical jargon that may not be familiar to all readers, while "teamwork" is a concept most people understand from daily life.

The word "revolutionize" was changed to "completely change" to use more common vocabulary that clearly expresses the meaning without requiring knowledge of more sophisticated terms. "Paradigm" was replaced with "how we work" because "paradigm" is an abstract concept that can be confusing, while "how we work" directly explains what aspect of the organization will change.

The sentence structure was kept relatively simple as a single sentence, which aligns with accessibility guidelines for cognitive disabilities. The meaning remained exactly the same - a company leader has a plan that will significantly change the organization's approach. No technical terms were left unexplained, and all vocabulary was chosen to be familiar to people in everyday contexts rather than specialized business environments.

The transformation followed principles of plain language by using active voice, common vocabulary, and direct expression while maintaining the core message about organizational change through collaborative efforts.

============================================================

Simple sentence translation, output language is Spanish

InΒ [15]:
# Example 5: Simple sentence translation, output language is Spanish
text = "The CEO's strategic initiative to leverage synergistic opportunities will revolutionize our paradigm."
transformations = [
        "language_simple_sentences",
        "language_common_words",
        "language_direct",
        "language_no_jargon",
        "clarity_pronouns",
    ]
target_language="Spanish"

print("πŸ“š Example 5: Simple sentence translation, output language is Spanish")
print("=" * 60)
result4 = await translate_text(
    text=text,
    transformations=transformations,
    target_language=target_language
)
print("\n" + "="*60 + "\n")
πŸ“š Example 5: Simple sentence translation, output language is Spanish
============================================================
πŸ“ Original Text (12 words):
   The CEO's strategic initiative to leverage synergistic opportunities will revolutionize our paradigm.

✨ Transformed Text:
   El director ejecutivo tiene un plan para usar las oportunidades de trabajo en equipo. Este plan cambiarΓ‘ la forma en que la empresa trabaja.

πŸ“Š Statistics:
   β€’ Input Language: English
   β€’ Output Language: Spanish
   β€’ Words Used: 12
   β€’ Processing Time: 3160ms
   β€’ Local Time: 3702ms
   β€’ Remaining Balance: 239,224 words

============================================================

8. Error handling demonstrationΒΆ

Let's see how the SDK handles various error scenarios.

InΒ [Β ]:
async def demonstrate_error_handling():
    """Demonstrate various error scenarios"""
    async with accessibletranslator.ApiClient(configuration) as api_client:
        translation_api = accessibletranslator.TranslationApi(api_client)
        
        print("πŸ”΄ Error Handling Examples")
        print("=" * 60)
        
        # Test 1: Invalid transformation
        print("\n1. Invalid Transformation Test:")
        try:
            request = TranslationRequest(
                text="Test text",
                transformations=["invalid_transformation_name"]
            )
            result = await translation_api.translate(request)
            print(result.translated_text)
        except ApiException as e:
            print(f"   βœ… Caught expected error: {e.status} - {e.reason}")
        except Exception as e:
            print(f"   ❌ Unexpected error: {e}")
        
        # Test 2: Empty text
        print("\n2. Empty Text Test:")
        try:
            request = TranslationRequest(
                text="",
                transformations=["language_simple_sentences"]
            )
            result = await translation_api.translate(request)
        except ApiException as e:
            print(f"   βœ… Caught expected error: {e.status} - {e.reason}")
        except Exception as e:
            print(f"   ❌ Unexpected error: {e}")
        
        # Test 3: Empty transformations
        print("\n3. Empty Transformations Test:")
        try:
            request = TranslationRequest(
                text="Test text",
                transformations=[]
            )
            result = await translation_api.translate(request)
        except ApiException as e:
            print(f"   βœ… Caught expected error: {e.status} - {e.reason}")
        except Exception as e:
            print(f"   ❌ Unexpected error: {e}")
InΒ [17]:
# Run error handling demo
await demonstrate_error_handling()
print("\n" + "="*60 + "\n")
πŸ”΄ Error Handling Examples
============================================================

1. Invalid Transformation Test:
   βœ… Caught expected error: 400 - Bad Request

2. Empty Text Test:
   βœ… Caught expected error: 422 - Unprocessable Entity

3. Empty Transformations Test:
   βœ… Caught expected error: 400 - Bad Request

============================================================

9. Performance testingΒΆ

Test the SDK's performance with different text sizes.

InΒ [18]:
async def performance_test():
    """Test performance with different text sizes"""
    print("⚑ Performance Testing")
    print("=" * 60)
    
    test_cases = [
        {
            "name": "small text",
            "text": "Hello world",
            "expected_time": 30000  # 10 seconds
        },
        {
            "name": "medium text",
            "text": " ".join([
                "The implementation of machine learning algorithms requires careful consideration of various factors.",
                "Data preprocessing steps include normalization, feature selection, and dimensionality reduction.",
                "Model training involves iterative optimization using gradient descent techniques."
            ]),
            "expected_time": 60000  # 10 seconds
        },
        {
            "name": "large text",
            "text": " ".join([
                "The comprehensive implementation of advanced machine learning algorithms in contemporary software development environments requires meticulous consideration of numerous interdependent factors.",
                "Data preprocessing methodologies encompass sophisticated normalization techniques, strategic feature selection processes, and complex dimensionality reduction algorithms.",
                "Training procedures involve iterative optimization mechanisms utilizing gradient descent algorithms or analogous mathematical techniques.",
                "Evaluation frameworks incorporate multiple metrics including accuracy measurements, precision calculations, and recall assessments.",
                "Deployment architectures must accommodate scalability requirements, maintainability considerations, and real-time processing constraints."
            ]),
            "expected_time": 120000  # 10 seconds
        }
    ]
    
    for test_case in test_cases:
        print(f"\nπŸ§ͺ Testing {test_case['name']}:")
        
        result = await translate_text(
            text=test_case['text'],
            transformations=["language_simple_sentences"],
            show_details=False
        )
        
        if result:
            processing_time = result.processing_time_ms
            expected_time = test_case['expected_time']
            
            print(f"   πŸ“Š Words: {result.input_word_count}")
            print(f"   ⏱️ Processing Time: {processing_time}ms")
            
            if processing_time < expected_time:
                print(f"   βœ… Performance: Good ({processing_time/1000:.1f}s)")
            else:
                print(f"   ⚠️ Performance: Slow ({processing_time/1000:.1f}s)")
            
            # Calculate words per second
            wps = result.input_word_count / (processing_time / 1000)
        else:
            print(f"   ❌ Test failed")

# Run performance test
await performance_test()
print("\n" + "="*60 + "\n")
⚑ Performance Testing
============================================================

πŸ§ͺ Testing small text:
   πŸ“Š Words: 2
   ⏱️ Processing Time: 1678ms
   βœ… Performance: Good (1.7s)

πŸ§ͺ Testing medium text:
   πŸ“Š Words: 31
   ⏱️ Processing Time: 3397ms
   βœ… Performance: Good (3.4s)

πŸ§ͺ Testing large text:
   πŸ“Š Words: 75
   ⏱️ Processing Time: 5996ms
   βœ… Performance: Good (6.0s)

============================================================

10. Batch processing exampleΒΆ

Process multiple texts in sequence. Handle retries in case of API rate limiting automatically when properly configured.

InΒ [19]:
async def batch_processing_demo():
    """Demonstrate batch processing of multiple texts"""
    print("πŸ“¦ Batch Processing Demo")
    print("=" * 60)
    
    texts = [
        "The algorithm's computational complexity exhibits exponential growth patterns.",
        "We need to optimize our database queries for better performance.",
        "The user interface should be intuitive and accessible to everyone.",
        "Machine learning models require extensive training data for accuracy.",
        "Security vulnerabilities must be addressed immediately."
    ]
    
    transformations = ["language_simple_sentences", "language_common_words"]
    
    total_start_time = time.time()
    results = []
    
    for i, text in enumerate(texts, 1):
        print(f"\nπŸ”„ Processing {i}/{len(texts)}:")
        print(f"   Original: {text}")
        
        result = await translate_text(
            text=text,
            transformations=transformations,
            show_details=False
        )
        
        if result:
            print(f"   ✨ Accessible: {result.translated_text}")
            print(f"   πŸ“Š {result.input_word_count} words, {result.processing_time_ms}ms")
            results.append(result)
        else:
            print(f"   ❌ Failed to process")
    
    total_end_time = time.time()
    total_time = (total_end_time - total_start_time) * 1000
    
    print(f"\nπŸ“ˆ Batch Summary:")
    print(f"   β€’ Total Texts: {len(texts)}")
    print(f"   β€’ Successful: {len(results)}")
    print(f"   β€’ Failed: {len(texts) - len(results)}")
    print(f"   β€’ Total Time: {total_time:.0f}ms")
    print(f"   β€’ Average Time: {total_time/len(results):.0f}ms per text")
    
    if results:
        total_words = sum(r.input_word_count for r in results)
        total_used = sum(r.words_used for r in results)
        print(f"   β€’ Total Words: {total_words}")
        print(f"   β€’ Words Used: {total_used}")
        print(f"   β€’ Final Balance: {results[-1].word_balance:,}")

# Run batch processing demo
await batch_processing_demo()
print("\n" + "="*60 + "\n")
πŸ“¦ Batch Processing Demo
============================================================

πŸ”„ Processing 1/5:
   Original: The algorithm's computational complexity exhibits exponential growth patterns.
   ✨ Accessible: The computer program gets much slower when it has more work to do.
   πŸ“Š 8 words, 2667ms

πŸ”„ Processing 2/5:
   Original: We need to optimize our database queries for better performance.
   ✨ Accessible: We need to make our database searches work faster.
   πŸ“Š 10 words, 1819ms

πŸ”„ Processing 3/5:
   Original: The user interface should be intuitive and accessible to everyone.
   ✨ Accessible: The user screen should be easy to use for all people.
   πŸ“Š 10 words, 1953ms

πŸ”„ Processing 4/5:
   Original: Machine learning models require extensive training data for accuracy.
   ✨ Accessible: Machine learning models need lots of training data to work well.
   πŸ“Š 9 words, 1584ms

πŸ”„ Processing 5/5:
   Original: Security vulnerabilities must be addressed immediately.
   ✨ Accessible: Security problems must be fixed right away.
   πŸ“Š 6 words, 2430ms

πŸ“ˆ Batch Summary:
   β€’ Total Texts: 5
   β€’ Successful: 5
   β€’ Failed: 0
   β€’ Total Time: 13111ms
   β€’ Average Time: 2622ms per text
   β€’ Total Words: 43
   β€’ Words Used: 43
   β€’ Final Balance: 239,073

============================================================

11. Final SummaryΒΆ

Let's check our final word balance and summarize the demo.

InΒ [20]:
async def final_summary():
    """Provide a final summary of the demo"""
    print("πŸ“Š Demo Summary")
    print("=" * 60)
    
    # Check final balance
    final_balance = await check_word_balance()
    
    print(f"\n🎯 Features Demonstrated:")
    features = [
        "βœ… API health check",
        "βœ… Authentication & word balance",
        "βœ… Available transformations",
        "βœ… Target languages",
        "βœ… Basic text translation",
        "βœ… Advanced use cases",
        "βœ… Error handling",
        "βœ… Performance testing",
        "βœ… Batch processing"
        ]
    
    for feature in features:
        print(f"   {feature}")
    
    print(f"\nπŸ”§ SDK Capabilities Shown:")
    capabilities = [
        "πŸ”„ Async/await support",
        "πŸ” API key authentication",
        "🎯 Multiple transformation types",
        "🌍 Multi-language support",
        "πŸ›‘οΈ Comprehensive error handling",
        "πŸ“Š Detailed response metadata",
        "πŸ”„ Batch processing capabilities"
    ]
    
    for capability in capabilities:
        print(f"   {capability}")
    
    print(f"\nπŸŽ‰ Demo Complete!")
    print(f"\nπŸ“š Next Steps:")
    print(f"   β€’ Visit https://www.accessibletranslator.com/resources/api-docs for full documentation")
    print(f"   β€’ Try different transformation combinations")
    print(f"   β€’ Integrate the SDK into your applications")
    print(f"   β€’ Explore advanced features like custom prompts")
    
    print(f"\n⭐ Thank you for trying the AccessibleTranslator Python SDK!")
InΒ [21]:
# Run final summary
await final_summary()
πŸ“Š Demo Summary
============================================================
πŸ’° Word balance: 239,073 words
βœ… Sufficient balance for demos

🎯 Features Demonstrated:
   βœ… API health check
   βœ… Authentication & word balance
   βœ… Available transformations
   βœ… Target languages
   βœ… Basic text translation
   βœ… Advanced use cases
   βœ… Error handling
   βœ… Performance testing
   βœ… Batch processing

πŸ”§ SDK Capabilities Shown:
   πŸ”„ Async/await support
   πŸ” API key authentication
   🎯 Multiple transformation types
   🌍 Multi-language support
   πŸ›‘οΈ Comprehensive error handling
   πŸ“Š Detailed response metadata
   πŸ”„ Batch processing capabilities

πŸŽ‰ Demo Complete!

πŸ“š Next Steps:
   β€’ Visit https://www.accessibletranslator.com/resources/api-docs for full documentation
   β€’ Try different transformation combinations
   β€’ Integrate the SDK into your applications
   β€’ Explore advanced features like custom prompts

⭐ Thank you for trying the AccessibleTranslator Python SDK!