Spaces:
Runtime error
Runtime error
Upload tool
Browse files- calculator.py +37 -7
- requirements.txt +0 -2
calculator.py
CHANGED
@@ -1,6 +1,40 @@
|
|
1 |
-
import re
|
2 |
from transformers import Tool
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
|
6 |
class SimpleCalculatorTool(Tool):
|
@@ -11,10 +45,6 @@ class SimpleCalculatorTool(Tool):
|
|
11 |
|
12 |
inputs = ["text"]
|
13 |
outputs = ["text"]
|
14 |
-
regex = r"(\d+(?:\.\d+)?)(\+|\-|\*|\/)(\d+(?:\.\d+)?)"
|
15 |
|
16 |
def __call__(self, input_str: str):
|
17 |
-
|
18 |
-
if match is None:
|
19 |
-
raise ValueError("Input string is not a valid mathematical expression.")
|
20 |
-
return eval(f"{match.group(1)} {match.group(2)} {match.group(3)}")
|
|
|
|
|
1 |
from transformers import Tool
|
2 |
+
|
3 |
+
def simple_calculator(expression):
|
4 |
+
# Find the index of the operator
|
5 |
+
operator_index = -1
|
6 |
+
for i, char in enumerate(expression):
|
7 |
+
if char in ('+', '-', '*', '/'):
|
8 |
+
operator_index = i
|
9 |
+
break
|
10 |
+
|
11 |
+
# Ensure that an operator was found
|
12 |
+
if operator_index == -1:
|
13 |
+
return "Invalid expression"
|
14 |
+
|
15 |
+
# Split the expression into the operator and operands
|
16 |
+
operator = expression[operator_index]
|
17 |
+
operand1 = float(expression[:operator_index])
|
18 |
+
operand2 = float(expression[operator_index + 1:])
|
19 |
+
|
20 |
+
# Perform the calculation based on the operator
|
21 |
+
if operator == '+':
|
22 |
+
result = operand1 + operand2
|
23 |
+
elif operator == '-':
|
24 |
+
result = operand1 - operand2
|
25 |
+
elif operator == '*':
|
26 |
+
result = operand1 * operand2
|
27 |
+
elif operator == '/':
|
28 |
+
result = operand1 / operand2
|
29 |
+
else:
|
30 |
+
raise ValueError("Input string is not a valid mathematical expression.")
|
31 |
+
|
32 |
+
# Convert the result to a string and return it
|
33 |
+
return str(result)
|
34 |
+
|
35 |
+
# Test the function
|
36 |
+
expression = "1+3"
|
37 |
+
result = simple_calculator(expression)
|
38 |
|
39 |
|
40 |
class SimpleCalculatorTool(Tool):
|
|
|
45 |
|
46 |
inputs = ["text"]
|
47 |
outputs = ["text"]
|
|
|
48 |
|
49 |
def __call__(self, input_str: str):
|
50 |
+
return simple_calculator(input_str)
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,3 +1 @@
|
|
1 |
transformers
|
2 |
-
re
|
3 |
-
huggingface_hub
|
|
|
1 |
transformers
|
|
|
|