### Query Parser with Grammar Support Source: https://context7.com/sweedxd/currencypp/llms.txt The `make_parser()` function creates a parser instance that understands complex currency conversion queries with mathematical expressions, supporting custom separators, destination keywords, and arithmetic operations. ```APIDOC ## Query Parser with Grammar Support ### Description Creates a parser instance capable of interpreting complex currency conversion queries, including mathematical expressions, custom keywords, and currency aliases. ### Method `make_parser(properties: ParserProperties)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from currencyparser import make_parser, ParserProperties from parsy import ParseError props = ParserProperties() props.default_cur_in = "USD" props.default_curs_out = ["EUR", "JPY"] props.to_keywords = ["to", "in", ":", "."] props.sep_keywords = ["and", "&", ","] props.aliases = {"$": "USD", "€": "EUR", "¥": "JPY"} parser = make_parser(props) # Parse a simple conversion query result = parser.parse("100 usd to eur") # Example of a more complex query structure that the parser can handle: # parser.parse("5 USD + 2 GBP to EUR") ``` ### Response #### Success Response (200) Returns a dictionary representing the parsed query, detailing sources and destinations for conversion. - **sources** (list) - A list of dictionaries, each specifying a currency and amount. - **currency** (str) - The currency code. - **amount** (float) - The amount in the specified currency. - **destinations** (list) - A list of dictionaries, each specifying a target currency. - **currency** (str) - The target currency code. #### Response Example ```json { "sources": [{"currency": "USD", "amount": 100.0}], "destinations": [{"currency": "EUR"}] } ``` ``` -------------------------------- ### Fetch Exchange Rates via PrivateDomain (Cache) Source: https://context7.com/sweedxd/currencypp/llms.txt Loads exchange rate data from a free cache server using the `PrivateDomain` service. It returns a dictionary of currencies with their prices and a timestamp. This is the primary data source. ```python from webservice import PrivateDomain cache_service = PrivateDomain(plugin_ref) currencies, timestamp = cache_service.load_from_url() # Returns: ( # { # 'USD': {'name': 'USD', 'price': 1.0}, # 'EUR': {'name': 'EUR', 'price': 0.925}, # 'GBP': {'name': 'GBP', 'price': 0.783}, # ... # }, # 1700000000 # Unix timestamp # ) ``` -------------------------------- ### Manage Exchange Rates and Conversions with Python Source: https://context7.com/sweedxd/currencypp/llms.txt The `ExchangeRates` class manages fetching, caching, and calculating currency conversions. It supports automatic updates, currency code validation, custom aliases, and formatted output. Dependencies include `pathlib`. ```python from exchange import ExchangeRates, UpdateFreq from currency_error import CurrencyError from pathlib import Path # Initialize exchange rates broker cache_dir = Path("./cache") cache_dir.mkdir(exist_ok=True) app_id = "" # OpenExchangeRates API key (optional) plugin_ref = None # Plugin instance for logging broker = ExchangeRates(cache_dir, UpdateFreq.DAILY, app_id, plugin_ref) # Set default currencies broker.set_default_cur_in("USD") broker.set_default_curs_out("EUR GBP JPY") # Add custom aliases broker.add_alias("$", "USD") broker.add_alias("€", "EUR") broker.add_alias("£", "GBP") # Validate currency codes try: code = broker.validate_code("usd") # Returns "USD" print(f"Validated code: {code}") invalid = broker.validate_code("XYZ", raiseOnNone=True) except CurrencyError as e: print(f"Invalid currency: {e.currency}") # Perform currency conversion query = { 'sources': [{'currency': 'USD', 'amount': 100.0}], 'destinations': [ {'currency': 'EUR'}, {'currency': 'GBP'} ] } results = broker.convert(query) print(f"Conversion results: {results}") # Returns: # [ # {'amount': 92.5, 'title': '92.50 Euro', 'description': '100.00 US Dollar'}, # {'amount': 78.3, 'title': '78.30 British Pound', 'description': '100.00 US Dollar'} # ] # Check if rates need updating if broker.shouldUpdate(): success = broker.update() if success: print(f"Rates updated at {broker.last_update}") ``` -------------------------------- ### Currency Conversion Query Processing Source: https://context7.com/sweedxd/currencypp/llms.txt The `query()` method is the main entry point for processing user input and returning conversion results. It handles query validation, rate updates, currency conversion calculations, and error handling. ```APIDOC ## Currency Conversion Query Processing ### Description Processes user input for currency conversion, including validation, rate updates, calculations, and error handling. ### Method `plugin.query(user_input: str)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from currencypp import CurrencyPP plugin = CurrencyPP() # Convert 100 USD to EUR and JPY results = plugin.query("100 usd to eur, jpy") # Perform a simple conversion with default currencies results_default = plugin.query("50") # Use math expressions for conversion results_math = plugin.query("10 + 5 USD in EUR") # Multi-currency addition and conversion results_multi = plugin.query("5 USD + 2 GBP in EUR") # Handle invalid currency errors try: plugin.query("100 XYZ") except CurrencyError as e: print(f"Currency error: {e}") ``` ### Response #### Success Response (200) Returns a list of conversion results, typically including title and description for each converted currency. - **title** (str) - The converted amount and currency. - **description** (str) - The original amount and currency. #### Response Example ```json [ {'amount': 92.5, 'title': '92.50 Euro', 'description': '100.00 US Dollar'}, {'amount': 15234.00, 'title': '15,234.00 Japanese Yen', 'description': '100.00 US Dollar'} ] ``` ``` -------------------------------- ### Settings Management and Configuration Reload Source: https://context7.com/sweedxd/currencypp/llms.txt Manages user preferences loaded from `settings.json`, including default currencies, API keys, and separators. The `reload_settings()` method allows dynamic updates without restarting the plugin, preserving state. ```python # Example settings structure: settings = { "input_cur": "USD", "output_cur": "EUR GBP JPY", "app_id": "", "update_freq": "daily", # Options: "never", "hourly", "daily" "separators": "to in : .", "destination_separators": "and & ,", "aliases": "USD = $ dollar dollars bucks\nEUR = euro euros €\nGBP = pound pounds £" } # When settings are modified in Flow Launcher: plugin.reload_settings() # - Detects currency changes # - Forces rate update if currencies changed # - Reloads aliases and separators # - Updates parser with new configuration # - Preserves cached exchange rates ``` -------------------------------- ### Create Parsers for Currency Queries with Parsy in Python Source: https://context7.com/sweedxd/currencypp/llms.txt The `make_parser()` function from the `currencyparser` module creates a parser instance using the Parsy library. It supports custom separators, destination keywords, currency aliases, and arithmetic operations with proper operator precedence. ```python from currencyparser import make_parser, ParserProperties from parsy import ParseError # Configure parser properties props = ParserProperties() props.default_cur_in = "USD" props.default_curs_out = ["EUR", "JPY"] props.to_keywords = ["to", "in", ":", "."] props.sep_keywords = ["and", "&", ","] props.aliases = {"$": "USD", "€": "EUR", "¥": "JPY"} # Create parser instance parser = make_parser(props) # Parse simple conversion result = parser.parse("100 usd to eur") print(f"Parse result: {result}") # Returns: { # 'sources': [{'currency': 'USD', 'amount': 100.0}], # 'destinations': [{'currency': 'EUR'}] # } # Parse with alias and multiple destinations result_alias = parser.parse("50 $ to € and ¥") print(f"Parse result with alias: {result_alias}") # Returns: { # 'sources': [{'currency': 'USD', 'amount': 50.0}], # 'destinations': [{'currency': 'EUR'}, {'currency': 'JPY'}] # } # Parse with math expression result_math = parser.parse("10 + 5 USD in EUR") print(f"Parse result with math: {result_math}") # Returns: { # 'sources': [{'currency': 'USD', 'amount': 15.0}], # 'destinations': [{'currency': 'EUR'}] # } ``` -------------------------------- ### Process Currency Conversion Queries with Python Source: https://context7.com/sweedxd/currencypp/llms.txt The `query()` method in the CurrencyPP class handles user input for currency conversion. It validates queries, updates rates, performs calculations, and manages error handling, returning results formatted for Flow Launcher's UI. ```python from currencypp import CurrencyPP from currency_error import CurrencyError # Initialize the plugin (typically done by Flow Launcher) plugin = CurrencyPP() # Example: Convert 100 USD to EUR and JPY # User types in Flow Launcher: "100 usd to eur, jpy" print(plugin.query("100 usd to eur, jpy")) # Returns results showing: # - 92.50 Euro (title) # - 100.00 US Dollar (description) # - 15,234.00 Japanese Yen (title) # - 100.00 US Dollar (description) # Example: Simple conversion with default currencies print(plugin.query("50")) # Converts 50 of default input currency to all default output currencies # Example: Math expressions with currency conversion print(plugin.query("10 + 5 USD in EUR")) # First adds 10+5=15, then converts 15 USD to EUR # Example: Multi-currency addition print(plugin.query("5 USD + 2 GBP in EUR")) # Converts both amounts to EUR and sums them # Error handling example try: plugin.query("100 XYZ") # Invalid currency code except CurrencyError as e: print(f"Currency error: {e}") # Output: Unrecognized currency "XYZ". You can create aliases... ``` -------------------------------- ### Handle Parse Errors Source: https://context7.com/sweedxd/currencypp/llms.txt Demonstrates how to handle potential errors during query parsing using a try-except block. It catches `ParseError` exceptions, providing informative messages. ```python try: result = parser.parse("invalid query ###") except ParseError as e: print(f"Parse failed: {e}") ``` -------------------------------- ### Fetch Exchange Rates via OpenExchangeRates (Paid API) Source: https://context7.com/sweedxd/currencypp/llms.txt Fetches exchange rate data from the `OpenExchangeRates` paid API. It requires an `app_id` and can raise exceptions if the request fails. This serves as a fallback data source. ```python from webservice import OpenExchangeRates app_id = "your_openexchangerates_app_id" api_service = OpenExchangeRates(plugin_ref, app_id) try: currencies, timestamp = api_service.load_from_url() # Same return format as PrivateDomain except Exception as e: print(f"API request failed: {e}") ``` -------------------------------- ### Add Currency Aliases from Configuration Source: https://context7.com/sweedxd/currencypp/llms.txt This Python snippet demonstrates how to bulk add currency aliases to a broker object. It iterates through a predefined list of alias-currency pairs, validates each alias string, and then adds the valid alias to the broker, mapping it to its corresponding currency. ```python alias_config = [ ("$", "USD"), ("€", "EUR"), ("£", "GBP"), ("¥", "JPY"), ("dollar", "USD"), ("euro", "EUR"), ("pound", "GBP"), ("yen", "JPY") ] for alias_str, currency in alias_config: validated = broker.validate_alias(alias_str) if validated: broker.add_alias(validated, currency) # Use aliases in queries result = broker.convert({ 'sources': [{'currency': '$', 'amount': 100}], # Resolved to USD 'destinations': [{'currency': '€'}] # Resolved to EUR }) ``` -------------------------------- ### Exchange Rate Management Source: https://context7.com/sweedxd/currencypp/llms.txt The `ExchangeRates` class manages currency data fetching, caching, and conversion calculations. It supports automatic updates, validates currency codes, and handles custom aliases. ```APIDOC ## Exchange Rate Management ### Description Manages fetching, caching, and conversion of exchange rates, including support for automatic updates, currency validation, and custom aliases. ### Method `ExchangeRates(cache_dir: Path, update_freq: UpdateFreq, app_id: str, plugin_ref: Any)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from exchange import ExchangeRates, UpdateFreq from pathlib import Path cache_dir = Path("./cache") cache_dir.mkdir(exist_ok=True) app_id = "" plugin_ref = None broker = ExchangeRates(cache_dir, UpdateFreq.DAILY, app_id, plugin_ref) broker.set_default_cur_in("USD") broker.set_default_curs_out("EUR GBP JPY") broker.add_alias("$", "USD") broker.add_alias("€", "EUR") broker.add_alias("£", "GBP") try: code = broker.validate_code("usd") invalid = broker.validate_code("XYZ", raiseOnNone=True) except CurrencyError as e: print(f"Invalid currency: {e.currency}") query = { 'sources': [{'currency': 'USD', 'amount': 100.0}], 'destinations': [ {'currency': 'EUR'}, {'currency': 'GBP'} ] } results = broker.convert(query) if broker.shouldUpdate(): success = broker.update() ``` ### Response #### Success Response (200) The `convert` method returns a list of dictionaries, each representing a conversion result. - **amount** (float) - The converted amount. - **title** (str) - Formatted title of the conversion result (e.g., "92.50 Euro"). - **description** (str) - Formatted description of the conversion result (e.g., "100.00 US Dollar"). #### Response Example ```json [ {'amount': 92.5, 'title': '92.50 Euro', 'description': '100.00 US Dollar'}, {'amount': 78.3, 'title': '78.30 British Pound', 'description': '100.00 US Dollar'} ] ``` ``` -------------------------------- ### Format Currency Numbers with Precision Options Source: https://context7.com/sweedxd/currencypp/llms.txt This Python code illustrates the use of the `format_number()` method for currency display. It supports standard 2-decimal formatting for conversions and an 8-decimal precision mode for exchange rates, automatically handling thousand separators and removing trailing zeros for cleaner output. ```python from exchange import ExchangeRates broker = ExchangeRates(cache_dir, UpdateFreq.DAILY, "", plugin_ref) # Standard formatting (2 decimals) formatted = broker.format_number(1234567.89) # Returns: "1,234,567.89" formatted = broker.format_number(100.00) # Returns: "100" (trailing zeros and decimal removed) formatted = broker.format_number(0.99) # Returns: "0.99" # Full precision formatting (8 decimals, for exchange rates) formatted = broker.format_number(0.92345678, fullDigits=True) # Returns: "0.92345678" formatted = broker.format_number(0.92000000, fullDigits=True) # Returns: "0.92" (trailing zeros removed) formatted = broker.format_number(1.00000000, fullDigits=True) # Returns: "1" (decimal point removed if no fractional part) # Used in conversion results query = { 'sources': [{'currency': 'USD', 'amount': 1000000.50}], 'destinations': [{'currency': 'EUR'}] } results = broker.convert(query) # Result title: "925,046.96 Euro" (formatted with commas) # Result description: "1,000,000.50 US Dollar" ``` -------------------------------- ### Parse Multi-Currency Addition Source: https://context7.com/sweedxd/currencypp/llms.txt Enables parsing of conversion requests involving the addition or subtraction of multiple currencies, all converted to a single destination currency. This handles complex net conversions. ```python result = parser.parse("5 USD + 2 GBP - 1 EUR to JPY") # Returns: { # 'sources': [ # {'currency': 'USD', 'amount': 5.0}, # {'currency': 'GBP', 'amount': 2.0}, # {'currency': 'EUR', 'amount': -1.0} # ], # 'destinations': [{'currency': 'JPY'}] # } ``` -------------------------------- ### Parse with Post-Conversion Math Source: https://context7.com/sweedxd/currencypp/llms.txt Supports applying arithmetic operations to the converted amount after the initial conversion. This enables further calculations on the exchange result. ```python result = parser.parse("100 usd in eur / 2") # Returns: { # 'sources': [{'currency': 'USD', 'amount': 50.0}], # 100/2 = 50 # 'destinations': [{'currency': 'EUR'}] # } ``` -------------------------------- ### Parse Multi-Destination Conversion Source: https://context7.com/sweedxd/currencypp/llms.txt Parses a string to convert a single source currency to multiple destination currencies. It returns a dictionary with source and destination currency information. This is useful for batch conversions. ```python result = parser.parse("50 gbp to usd, eur & jpy") # Returns: { # 'sources': [{'currency': 'GBP', 'amount': 50.0}], # 'destinations': [ # {'currency': 'USD'}, # {'currency': 'EUR'}, # {'currency': 'JPY'} # ] # } ``` -------------------------------- ### Parse with Arithmetic Expressions Source: https://context7.com/sweedxd/currencypp/llms.txt Handles conversion requests that include arithmetic expressions within the source amount. The expression is evaluated before the conversion. This allows for complex input values. ```python result = parser.parse("10*(2+1) USD in EUR") # Returns: { # 'sources': [{'currency': 'USD', 'amount': 30.0}], # 10*(2+1) = 30 # 'destinations': [{'currency': 'EUR'}] # } ``` -------------------------------- ### Custom Currency Alias Validation and Addition Source: https://context7.com/sweedxd/currencypp/llms.txt Provides methods to validate and add custom aliases for currency codes. Validation checks for conflicts with existing codes, numbers, and duplicates. Aliases can be cleared, useful during reloads. ```python from exchange import ExchangeRates broker = ExchangeRates(cache_dir, UpdateFreq.DAILY, "", plugin_ref) # Validate alias before adding alias = broker.validate_alias("$") if alias: broker.add_alias(alias, "USD") print(f"Added alias: {alias} -> USD") else: print("Invalid alias") # Invalid alias examples broker.validate_alias("USD") # Returns None (conflicts with currency code) broker.validate_alias("123") # Returns None (contains digits) broker.validate_alias("$€") # Returns "$€" (valid, no conflicts) # Clear all aliases (useful during settings reload) broker.clear_aliases() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.