### Install fluentogram Source: https://github.com/arustinal/fluentogram/blob/main/README.md Standard installation command for the library. ```bash pip install fluentogram ``` -------------------------------- ### Install CLI Dependencies Source: https://github.com/arustinal/fluentogram/blob/main/README.md Install the optional CLI tools for stub generation. ```sh pip install fluentogram[cli] ``` -------------------------------- ### Install NATS Support Source: https://github.com/arustinal/fluentogram/blob/main/README.md Install dependencies required for NATS KV storage integration. ```bash pip install fluentogram[nats] ``` -------------------------------- ### Handle KeyNotFoundError Source: https://context7.com/arustinal/fluentogram/llms.txt This error occurs when attempting to retrieve a translation key that does not exist in the provided bundles. Verify that all keys used in get() calls are defined in your Fluent files. ```python hub = TranslatorHub( {"en": "en"}, [FluentTranslator("en", FluentBundle.from_string("en-US", "hello = Hello"))], ) translator = hub.get_translator_by_locale("en") try: translator.get("nonexistent-key") except KeyNotFoundError as e: print(f"Key not found: {e.key}") ``` -------------------------------- ### Handle FormatError for Missing Variables Source: https://context7.com/arustinal/fluentogram/llms.txt Catch this error when a translation key requires variables (e.g., {$name}) but they are not provided during the get() call. Ensure all required variables are passed as keyword arguments. ```python hub = TranslatorHub( {"en": "en"}, [FluentTranslator("en", FluentBundle.from_string("en-US", "greet = Hello, { $name }!"))], ) translator = hub.get_translator_by_locale("en") try: translator.get("greet", wrong_param="value") # Missing $name variable except FormatError as e: print(f"Format error for key '{e.key}': {e.original_error}") ``` -------------------------------- ### Initialize TranslatorHub and Basic Usage Source: https://github.com/arustinal/fluentogram/blob/main/README.md Configure the TranslatorHub with FluentBundles and retrieve translations for a specific locale. ```python from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator, TranslatorHub # Create translators for different locales translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "welcome = Welcome, { $username }!\n" "items-count = You have { $count } items", ), ), ] # Configure locale mapping with fallbacks locales_map = { "en": "en", } # Create the translator hub hub = TranslatorHub(locales_map, translators) # Get a translator for a specific locale translator = hub.get_translator_by_locale("en") # Use translations print(translator.get("welcome", username="Alice")) # "Welcome, Alice!" ``` -------------------------------- ### Configure File Storage Source: https://github.com/arustinal/fluentogram/blob/main/README.md Use FileStorage to load translations from a directory structure. ```python from fluentogram import TranslatorHub from fluentogram.storage.file import FileStorage # Create FileStorage with custom path storage = FileStorage("my_translations/{locale}/") locales_map = { "en": "en", } hub = TranslatorHub(locales_map, storage=storage) translator = hub.get_translator_by_locale("en") print(translator.get("hello")) # Hello, world! ``` -------------------------------- ### Initialize In-Memory Translator Source: https://github.com/arustinal/fluentogram/blob/main/README.md Sets up a TranslatorHub using an in-memory FluentBundle for specific locales. ```python translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "welcome = Welcome, { $username }!\n" "items-count = You have { $count } items", ), ), ] hub = TranslatorHub(locales_map, translators) ``` -------------------------------- ### Run Stub Generator Source: https://github.com/arustinal/fluentogram/blob/main/README.md Generate type stubs from Fluent files using the CLI. ```sh fluentogram -f tests/assets/test.ftl -o test.pyi ``` -------------------------------- ### Load Translations from Files Source: https://context7.com/arustinal/fluentogram/llms.txt Uses FileStorage to automatically discover and load .ftl files from a directory structure. ```python from fluentogram import TranslatorHub from fluentogram.storage.file import FileStorage # Directory structure: # locales/ # en/ # main.ftl # errors.ftl # ru/ # main.ftl # errors.ftl # Create FileStorage with path pattern # {locale} placeholder is optional - will auto-detect locale directories storage = FileStorage("locales/{locale}/") # Or simply point to parent directory storage = FileStorage("locales/") # Configure locale mapping locales_map = { "en": "en", "ru": ("ru", "en"), } # Create hub with file storage hub = TranslatorHub(locales_map, storage=storage) # Get translator and use translations translator = hub.get_translator_by_locale("en") print(translator.get("hello")) # Uses translation from locales/en/*.ftl # Access all loaded translators print(hub.translators) # List of FluentTranslator instances print(hub.translators_map) # Dict mapping languages to translator chains ``` -------------------------------- ### Define and Access Hierarchical Translations Source: https://context7.com/arustinal/fluentogram/llms.txt Demonstrates defining Fluent bundles with hierarchical keys and accessing them via both direct method calls and attribute-based syntax. ```python translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", # Keys use hyphen separator for hierarchy "user-profile-title = User Profile\n" "user-profile-greeting = Hello, { $name }!\n" "menu-file-open = Open File\n" "menu-file-save = Save File\n" "button-submit = Submit", use_isolating=False, ), ), ] hub = TranslatorHub({"en": "en"}, translators) translator = hub.get_translator_by_locale("en") # Direct access with get() method print(translator.get("user-profile-title")) # Output: "User Profile" # Attribute-based access (translates to "user-profile-title") print(translator.user.profile.title()) # Output: "User Profile" # Attribute access with variables print(translator.user.profile.greeting(name="Alice")) # Output: "Hello, Alice!" # Nested menu items print(translator.menu.file.open()) # Output: "Open File" print(translator.menu.file.save()) # Output: "Save File" # Simple button translation print(translator.button.submit()) # Output: "Submit" ``` -------------------------------- ### TranslatorHub Initialization Signature Source: https://github.com/arustinal/fluentogram/blob/main/README.md Constructor definition for the TranslatorHub class. ```python def __init__( self, locales_map: dict[str, str | Iterable[str]], translators: list[FluentTranslator], root_locale: str = "en", ) -> None: ``` -------------------------------- ### Generate Translation Stubs via CLI Source: https://context7.com/arustinal/fluentogram/llms.txt Commands for generating type-safe .pyi stub files from Fluent translation files. ```bash # Install with CLI dependencies pip install fluentogram[cli] # Generate stubs from a single FTL file fluentogram -f locales/en/main.ftl -o translations.pyi # Generate stubs from a directory of FTL files fluentogram -d locales/en/ -o translations.pyi # Watch for changes and auto-regenerate (development mode) fluentogram -f locales/en/main.ftl -o translations.pyi -w true # Default output file is fluentogram.pyi if not specified fluentogram -f locales/en/main.ftl ``` -------------------------------- ### Implement NATS KV Storage Source: https://github.com/arustinal/fluentogram/blob/main/README.md Configure and use NATS KV storage for real-time translation updates. ```python import asyncio from fluent_compiler.bundle import FluentBundle from nats.js.api import KeyValueConfig, StorageType from fluentogram import FluentTranslator, TranslatorHub from fluentogram.nats.storage import NatsKvStorage async def main(): # Configure NATS KV storage kv_config = KeyValueConfig( bucket="fluentogram", storage=StorageType.FILE, ) # Create NATS storage storage = await NatsKvStorage.from_servers( servers=["nats://localhost:4222"], kv_config=kv_config, ) # Create translators translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "greeting = Hello, { $name }!", ), ), ] # Create hub with NATS storage hub = TranslatorHub( {"en": "en"}, translators, storage=storage, ) translator = hub.get_translator_by_locale("en") print(translator.get("greeting", name="World")) # "Hello, World!" # Update translation dynamically await storage.update_translation("en", "greeting", "Hi there, { $name }!") # Wait for the update to propagate await asyncio.sleep(1) # Get updated translation print(translator.get("greeting", name="World")) # "Hi there, World!" await storage.close() asyncio.run(main()) ``` -------------------------------- ### Real-Time Translation Updates with NATS Source: https://context7.com/arustinal/fluentogram/llms.txt Synchronizes translations across distributed instances using NATS JetStream KV store. ```python import asyncio from fluent_compiler.bundle import FluentBundle from nats.js.api import KeyValueConfig, StorageType from fluentogram import FluentTranslator, TranslatorHub from fluentogram.nats.storage import NatsKvStorage async def main(): # Configure NATS KV store kv_config = KeyValueConfig( bucket="translations", storage=StorageType.FILE, ) # Create NATS storage from server connection storage = await NatsKvStorage.from_servers( servers=["nats://localhost:4222"], kv_config=kv_config, separator=".", # Key separator for NATS subjects ) # Create initial translators translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "greeting = Hello, { $name }!", use_isolating=False, ), ), ] # Create hub with NATS storage hub = TranslatorHub({"en": "en"}, translators, storage=storage) translator = hub.get_translator_by_locale("en") print(translator.get("greeting", name="World")) # Output: "Hello, World!" # Update translation via NATS KV (propagates to all connected instances) await storage.update_translation("en", "greeting", "Hi there, { $name }!") # Wait for change to propagate await asyncio.sleep(1) # Get updated translation print(translator.get("greeting", name="World")) # Output: "Hi there, World!" # Clean up await storage.close() asyncio.run(main()) ``` -------------------------------- ### Dynamically Update Translations Source: https://context7.com/arustinal/fluentogram/llms.txt Demonstrates updating translations at runtime using TranslatorHub. This is useful for live content changes without restarting the application. Ensure the TranslatorHub is initialized with translators that can be updated. ```python import asyncio from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator, TranslatorHub async def main(): translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "welcome = Welcome to our app!\n" "cta = Click here to start", use_isolating=False, ), ), ] hub = TranslatorHub({"en": "en"}, translators) translator = hub.get_translator_by_locale("en") # Original translation print(translator.get("welcome")) # Update translation through hub (async) success = await hub.update_translation("en", "welcome", "Welcome back!") print(f"Update successful: {success}") # Translation is immediately updated print(translator.get("welcome")) # Update CTA for A/B testing await hub.update_translation("en", "cta", "Get started now - it's free!") print(translator.get("cta")) asyncio.run(main()) ``` -------------------------------- ### Handle Translation Exceptions Source: https://github.com/arustinal/fluentogram/blob/main/README.md Catch specific exceptions related to missing keys, formatting, or locale configuration. ```python from fluentogram.exceptions import KeyNotFoundError, FormatError, RootTranslatorNotFoundError try: translator = hub.get_translator_by_locale("fr") result = translator.get("nonexistent-key") except KeyNotFoundError as e: print(f"Translation key not found: {e.key}") except RootTranslatorNotFoundError as e: print(f"Root locale translator missing: {e.root_locale}") except FormatError as e: print(f"Formatting error for key {e.key}: {e.original_error}") ``` -------------------------------- ### TranslatorHub: Manage Multiple Locales and Fallbacks Source: https://context7.com/arustinal/fluentogram/llms.txt Use TranslatorHub to manage translators for different locales, including fallback chains. It requires a root locale and distributes TranslatorRunner instances. ```Python from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator, TranslatorHub # Define translation strings for multiple locales translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "welcome = Welcome, { $username }!\n" "items-count = You have { $count } items\n" "goodbye = Goodbye!", use_isolating=False, ), ), FluentTranslator( "ru", translator=FluentBundle.from_string( "ru-RU", "welcome = Привет, { $username }!\n" "items-count = У вас { $count } элементов", use_isolating=False, ), ), ] # Configure locale mapping with fallback chains # If "ru" locale doesn't have a translation, fall back to "en" locales_map = { "en": "en", "ru": ("ru", "en"), # Fallback chain: ru -> en "ua": ("ua", "ru", "en"), # Fallback chain: ua -> ru -> en } # Create the translator hub with root locale hub = TranslatorHub(locales_map, translators, root_locale="en") # Get translator for Russian locale translator = hub.get_translator_by_locale("ru") # Direct get() method for translations print(translator.get("welcome", username="Alex")) # Output: "Привет, Alex!" print(translator.get("items-count", count=5)) # Output: "У вас 5 элементов" # Fallback to English when Russian translation missing print(translator.get("goodbye")) # Output: "Goodbye!" (from English) ``` -------------------------------- ### Handle Fluentogram Exceptions Source: https://context7.com/arustinal/fluentogram/llms.txt Importing specific exception classes for error handling in translation workflows. ```python from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator, TranslatorHub from fluentogram.exceptions import ( FluentogramError, FormatError, KeyNotFoundError, LocalesNotFoundError, RootTranslatorNotFoundError, ) ``` -------------------------------- ### Format Currency with MoneyTransformer Source: https://context7.com/arustinal/fluentogram/llms.txt Converts Decimal amounts to locale-aware currency formats. ```python from decimal import Decimal from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator, MoneyTransformer, TranslatorHub translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "balance = Your balance: { $amount }\n" "price = Price: { $amount }", use_isolating=False, ), ), ] hub = TranslatorHub({"en": "en"}, translators) translator = hub.get_translator_by_locale("en") # Format with currency symbol amount = Decimal("1234.56") formatted = MoneyTransformer( amount, currency="USD", currency_display="symbol", # "code", "symbol", or "name" ) print(translator.get("balance", amount=formatted)) # Output: "Your balance: $1234.56" # Format with currency code formatted = MoneyTransformer( amount, currency="EUR", currency_display="code", use_grouping=True, # Enable thousand separators ) print(translator.get("price", amount=formatted)) # Output: "Price: EUR 1,234.56" # Control decimal places formatted = MoneyTransformer( Decimal("99.9"), currency="GBP", currency_display="symbol", minimum_fraction_digits=2, maximum_fraction_digits=2, ) print(translator.get("price", amount=formatted)) # Output: "Price: £99.90" ``` -------------------------------- ### Configure Locales Map Source: https://github.com/arustinal/fluentogram/blob/main/README.md Defines a fallback hierarchy for translations where the system searches through specified locales if a key is missing in the primary locale. ```python locales_map = { "ua": ("ua", "de", "en"), "de": ("de", "en"), "en": ("en",) } ``` -------------------------------- ### Access Translations via Attributes Source: https://github.com/arustinal/fluentogram/blob/main/README.md Use dot-notation syntax to access translation keys and nested structures. ```python print(translator.welcome(username="Alice")) # "Welcome, Alice!" print(translator.items.count(count=5)) # "You have 5 items" ``` -------------------------------- ### Format Dates with DateTimeTransformer Source: https://context7.com/arustinal/fluentogram/llms.txt Converts Python datetime objects to Fluent-compatible formats using ECMA-402 specifications. ```python from datetime import datetime, timezone from fluent_compiler.bundle import FluentBundle from fluentogram import DateTimeTransformer, FluentTranslator, TranslatorHub translators = [ FluentTranslator( "en", translator=FluentBundle.from_string( "en-US", "meeting = Meeting scheduled for { $date }\n" "event-date = Event on { $date }", use_isolating=False, ), ), ] hub = TranslatorHub({"en": "en"}, translators) translator = hub.get_translator_by_locale("en") # Create a datetime object meeting_date = datetime(2024, 1, 15, 14, 30, tzinfo=timezone.utc) # Full date and short time formatting formatted = DateTimeTransformer( meeting_date, dateStyle="full", # "full", "long", "medium", "short" timeStyle="short", # "full", "long", "medium", "short" ) print(translator.get("meeting", date=formatted)) # Output: "Meeting scheduled for Monday, January 15, 2024, 2:30 PM" # Custom format with specific components formatted = DateTimeTransformer( meeting_date, weekday="long", month="long", day="numeric", year="numeric", ) print(translator.get("event-date", date=formatted)) # Output: "Event on Monday, January 15, 2024" ``` -------------------------------- ### Handle LocalesNotFoundError Source: https://context7.com/arustinal/fluentogram/llms.txt This exception is raised if the specified directory for FileStorage contains no locale subdirectories. Ensure that the directory path provided to FileStorage contains valid locale folders (e.g., 'en', 'ru'). ```python from fluentogram.storage.file import FileStorage try: storage = FileStorage("empty_directory/") except LocalesNotFoundError as e: print(f"No locales in path: {e.path}") ``` -------------------------------- ### TranslatorRunner: Attribute-Based Translation Access Source: https://context7.com/arustinal/fluentogram/llms.txt TranslatorRunner offers a fluent API for accessing translations via Python attribute syntax. It chains attributes to build translation keys, which are resolved when called as a function. ```Python from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator, TranslatorHub ``` -------------------------------- ### FluentTranslator: Single Locale Translation Formatting Source: https://context7.com/arustinal/fluentogram/llms.txt Use FluentTranslator to wrap a FluentBundle for a specific locale. It handles message formatting with variables and supports runtime updates. Use the 'separator' argument for attribute-based access. ```Python from fluent_compiler.bundle import FluentBundle from fluentogram import FluentTranslator # Create a translator for English locale translator = FluentTranslator( locale="en", translator=FluentBundle.from_string( "en-US", "greeting = Hello, { $name }!\n" "user-profile = User: { $username }, Age: { $age }", use_isolating=False, # Disable Unicode isolation for cleaner output ), separator="-", # Key separator for attribute-based access ) # Get translation with variables result = translator.get("greeting", name="World") print(result) # Output: "Hello, World!" # Get translation with multiple variables result = translator.get("user-profile", username="john_doe", age=25) print(result) # Output: "User: john_doe, Age: 25" # Returns None if key not found (handled by TranslatorRunner in hub) result = translator.get("nonexistent-key") print(result) # Output: None # Update translation at runtime translator.update_translation("greeting", "Hi there, { $name }!") result = translator.get("greeting", name="World") print(result) # Output: "Hi there, World!" ``` -------------------------------- ### Generate Translation Stubs Programmatically Source: https://context7.com/arustinal/fluentogram/llms.txt Using the Generator class or generate function to create type stubs within Python code. ```python from fluentogram.stub_generator.generator import Generator, generate # Using the generate function generate( output_file="translations.pyi", file_path="locales/en/main.ftl", ) # Or using the Generator class for more control generator = Generator( output_file="translations.pyi", directory="locales/en/", # Process all .ftl files in directory ) generator.generate() # Generated stub provides type hints: # class TranslatorRunner: # def welcome(self, *, username: str) -> str: ... # @property # def user(self) -> _UserRunner: ... ``` -------------------------------- ### Handle RootTranslatorNotFoundError Source: https://context7.com/arustinal/fluentogram/llms.txt Catch this error when the root locale translator is not provided to TranslatorHub. Ensure all specified root locales have a corresponding translator. ```python try: hub = TranslatorHub( {"en": "en"}, [FluentTranslator("ru", FluentBundle.from_string("ru-RU", "hello = Привет"))], root_locale="en", # No "en" translator provided! ) except RootTranslatorNotFoundError as e: print(f"Missing root locale: {e.root_locale}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.