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.
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.
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
# 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.
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
# 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.
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
# 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.
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
# 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.
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
# 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
# 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
# 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)
# 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
# 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.
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}")
# 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.
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.
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.
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!")
# 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!