Spaces:
Sleeping
Sleeping
added calculator to gradio
Browse files- Gradio_UI.py +44 -1
Gradio_UI.py
CHANGED
|
@@ -292,5 +292,48 @@ class GradioUI:
|
|
| 292 |
|
| 293 |
demo.launch(debug=True, share=True, **kwargs)
|
| 294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
-
__all__ = ["stream_to_gradio", "GradioUI"]
|
|
|
|
| 292 |
|
| 293 |
demo.launch(debug=True, share=True, **kwargs)
|
| 294 |
|
| 295 |
+
# ADDED: Calculator function to evaluate arithmetic expressions safely.
|
| 296 |
+
def calculator(expression: str) -> str:
|
| 297 |
+
"""
|
| 298 |
+
Safely evaluate a basic arithmetic expression and return the result as a string.
|
| 299 |
+
|
| 300 |
+
This function uses Python's AST module to parse and evaluate the expression,
|
| 301 |
+
allowing only basic arithmetic operators.
|
| 302 |
+
"""
|
| 303 |
+
try:
|
| 304 |
+
import ast
|
| 305 |
+
import operator as op
|
| 306 |
+
|
| 307 |
+
# Define supported operators
|
| 308 |
+
operators = {
|
| 309 |
+
ast.Add: op.add,
|
| 310 |
+
ast.Sub: op.sub,
|
| 311 |
+
ast.Mult: op.mul,
|
| 312 |
+
ast.Div: op.truediv,
|
| 313 |
+
ast.Mod: op.mod,
|
| 314 |
+
ast.Pow: op.pow,
|
| 315 |
+
ast.USub: op.neg,
|
| 316 |
+
ast.UAdd: op.pos,
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
def eval_node(node):
|
| 320 |
+
if isinstance(node, ast.Num): # For Python < 3.8
|
| 321 |
+
return node.n
|
| 322 |
+
elif isinstance(node, ast.Constant): # For Python >= 3.8
|
| 323 |
+
return node.value
|
| 324 |
+
elif isinstance(node, ast.BinOp):
|
| 325 |
+
return operators[type(node.op)](eval_node(node.left), eval_node(node.right))
|
| 326 |
+
elif isinstance(node, ast.UnaryOp):
|
| 327 |
+
return operators[type(node.op)](eval_node(node.operand))
|
| 328 |
+
else:
|
| 329 |
+
raise TypeError(f"Unsupported expression: {node}")
|
| 330 |
+
|
| 331 |
+
# Parse the expression and evaluate
|
| 332 |
+
node = ast.parse(expression, mode='eval').body
|
| 333 |
+
result = eval_node(node)
|
| 334 |
+
return str(result)
|
| 335 |
+
except Exception as e:
|
| 336 |
+
return f"Error: {e}"
|
| 337 |
+
|
| 338 |
|
| 339 |
+
__all__ = ["stream_to_gradio", "GradioUI", "calculator"]
|