Skip to content

Commit a035c21

Browse files
committed
v0.75054 - calc module fixes
1 parent ee569a8 commit a035c21

File tree

4 files changed

+40
-8
lines changed

4 files changed

+40
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ If you run into any issues, consult the logs or reach out on the repository's [I
236236
---
237237

238238
# Changelog
239+
- v0.75054 - small fixes and more error catching in `calc_module.py`
239240
- v0.75053 - only include eligible territories in U.S. NWS queries
240241
- list of queried / eligible territories can be set in `config.ini` under the `NWS` section
241242
- v0.75052 - include the details from U.S. National Weather Service on alerts

src/calc_module.py

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
# calc_module.py
2+
#
3+
# From:
4+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5+
# https://github.com/FlyingFathead/TelegramBot-OpenAI-API
6+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7+
# (updated Oct 13, 2024)
28

39
import ast
410
import operator
511
import logging
12+
import re
613

714
# Initialize the logger
815
logger = logging.getLogger(__name__)
@@ -12,8 +19,21 @@
1219
MAX_OUTPUT_LENGTH = 500 # Adjust as necessary
1320
MAX_MAGNITUDE = 1e100 # Example maximum magnitude
1421

15-
def safe_eval(expression):
22+
def preprocess_expression(expression: str) -> str:
23+
"""
24+
Preprocess the input expression to handle natural language constructs like 'of' and percentages.
25+
For example, convert '0.1% of 200000000' to '0.1 / 100 * 200000000'.
26+
"""
27+
# Handle 'of' by replacing it with '*'
28+
expression = re.sub(r'\bof\b', '*', expression, flags=re.IGNORECASE)
29+
30+
# Handle percentages: convert 'X%' to '(X/100)'
31+
expression = re.sub(r'(\d+(\.\d+)?)\s*%', r'(\1/100)', expression)
32+
33+
logger.debug(f"Preprocessed expression: {expression}")
34+
return expression
1635

36+
def safe_eval(expression: str):
1737
# Replace '^' with '**' for exponentiation
1838
expression = expression.replace('^', '**')
1939

@@ -53,6 +73,12 @@ def _eval(node):
5373
return node.n
5474
elif isinstance(node, ast.Expression):
5575
return _eval(node.body)
76+
elif isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
77+
operand = _eval(node.operand)
78+
if isinstance(node.op, ast.UAdd):
79+
return +operand
80+
elif isinstance(node.op, ast.USub):
81+
return -operand
5682
else:
5783
error_msg = f"Unsupported type: {type(node).__name__}"
5884
logger.error(error_msg)
@@ -69,7 +95,10 @@ def _eval(node):
6995
async def calculate_expression(expression: str):
7096
logger.info(f"Calculating expression: {expression}")
7197
try:
72-
result = safe_eval(expression)
98+
# Preprocess the expression to handle 'of' and '%'
99+
processed_expression = preprocess_expression(expression)
100+
101+
result = safe_eval(processed_expression)
73102

74103
# Check if the result length is within limits
75104
result_str = str(result)
@@ -79,7 +108,7 @@ async def calculate_expression(expression: str):
79108
return error_message
80109

81110
# Construct the success message
82-
result_message = f"[NOTE: If using i.e. Finnish, you can word it i.e. with: 'Tulos laskutoimitukselle:'] The result of {expression} is {result}."
111+
result_message = f"The result of {expression} is {result}."
83112
logger.info(f"Calculation successful: {result_message}")
84113
return result_message
85114
except ValueError as ve:
@@ -92,4 +121,3 @@ async def calculate_expression(expression: str):
92121
error_message = f"An unexpected error occurred while evaluating `{expression}`: {str(e)}"
93122
logger.error(error_message)
94123
return error_message
95-

src/main.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@
22
#
33
# by FlyingFathead ~*~ https://github.com/FlyingFathead
44
# ghostcode: ChaosWhisperer
5+
#
6+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
57
# https://github.com/FlyingFathead/TelegramBot-OpenAI-API
8+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
69
#
710
# version of this program
8-
version_number = "0.75053"
11+
version_number = "0.75054"
912

1013
# Add the project root directory to Python's path
1114
import sys

src/text_message_handler.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,12 +394,12 @@ async def handle_message(bot, update: Update, context: CallbackContext, logger)
394394
else:
395395
# Proper result was returned, log and format it
396396
# calc_result = f"`{calc_result}`" # Wrap the result in backticks for code formatting in Markdown.
397-
calc_result = f"<code>{calc_result}</code>" # Wrap the result in <code> tags for HTML formatting.
397+
calc_result = f"{calc_result}" # Wrap the result in <code> tags for HTML formatting.
398398
system_message = (
399399
f"[Calculator result, explain to the user in their language if needed. "
400400
"IMPORTANT: Do not translate or simplify the mathematical expressions themselves. "
401-
"NOTE: Telegram doesn't support LaTeX. Use simple HTML formatting, note that <pre> or <br> are NOT allowed HTML tags. If the user explicitly asks for LaTeX or mentions LaTeX, use LaTeX formatting; "
402-
"otherwise, use plain text or Unicode with simple HTML.]:\n{calc_result}\n\n"
401+
"NOTE: Telegram doesn't support LaTeX. Use simple HTML formatting, i.e. <code></code> if need be, note that <pre> or <br> are NOT allowed HTML tags. If the user explicitly asks for LaTeX or mentions LaTeX, use LaTeX formatting; "
402+
f"otherwise, use plain text or Unicode with simple HTML.] Result:\n{calc_result}\n\n"
403403
"[NOTE: format your response appropriately, possibly incorporating additional context or user intent, TRANSLATE it to the user's language if needed.]"
404404
).format(calc_result=calc_result) # This ensures the result is inserted correctly
405405

0 commit comments

Comments
 (0)