spagestic commited on
Commit
46ee226
·
1 Parent(s): c49667f

Refactor and expand math tools application with new features and improved documentation

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **/__pycache__
README.md CHANGED
@@ -1,14 +1,99 @@
1
  ---
2
- title: Counting
3
- emoji: 🐨
4
- colorFrom: red
5
- colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.32.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: simple counting mcp server
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Math Tools
3
+ emoji: 🧮
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 5.32.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: Mathematics tools for different educational levels
12
+ ---
13
+
14
+ # Math Education Tools
15
+
16
+ This web application provides various mathematical tools organized by educational level, from elementary school to university. The application is built using Gradio and provides interactive interfaces for different mathematical operations.
17
+
18
+ ## Features
19
+
20
+ ### Text Utils
21
+
22
+ - Letter Counter: Count occurrences of a specific letter in a word
23
+
24
+ ### Elementary School Math
25
+
26
+ - Addition: Add two numbers
27
+ - Subtraction: Subtract one number from another
28
+ - Multiplication: Multiply two numbers
29
+ - Division: Divide one number by another
30
+
31
+ ### Middle School Math
32
+
33
+ - Linear Equation Solver: Solve equations of the form ax = b
34
+ - Quadratic Expression Evaluator: Calculate the value of ax² + bx + c for a given x
35
+
36
+ ### High School Math
37
+
38
+ - Trigonometry Calculator: Calculate sine, cosine, and tangent values for angles in degrees
39
+
40
+ ### University Math
41
+
42
+ - Polynomial Derivative: Find the derivative of a polynomial function
43
+ - Polynomial Integration: Find the indefinite integral of a polynomial function
44
+
45
+ ## Project Structure
46
+
47
+ ```
48
+ ├── app.py # Main application file
49
+ ├── maths/ # Mathematics modules
50
+ │ ├── __init__.py
51
+ │ ├── elementary/ # Elementary school level
52
+ │ │ ├── __init__.py
53
+ │ │ └── arithmetic.py # Basic operations (add, subtract, multiply, divide)
54
+ │ ├── middleschool/ # Middle school level
55
+ │ │ ├── __init__.py
56
+ │ │ └── algebra.py # Algebra operations
57
+ │ ├── highschool/ # High school level
58
+ │ │ ├── __init__.py
59
+ │ │ └── trigonometry.py # Trigonometric functions
60
+ │ └── university/ # University level
61
+ │ ├── __init__.py
62
+ │ └── calculus.py # Calculus operations
63
+ └── utils/ # Utility functions
64
+ ├── __init__.py
65
+ └── text_utils.py # Text processing utilities
66
+ ```
67
+
68
+ ## Getting Started
69
+
70
+ 1. Install the required packages:
71
+
72
+ ```
73
+ pip install gradio
74
+ ```
75
+
76
+ 2. Run the application:
77
+
78
+ ```
79
+ python app.py
80
+ ```
81
+
82
+ 3. Open your browser and navigate to the displayed URL (typically http://127.0.0.1:7860)
83
+
84
+ ## Extending the Project
85
+
86
+ To add new mathematical functions:
87
+
88
+ 1. Choose the appropriate educational level folder
89
+ 2. Add your function to an existing file or create a new module
90
+ 3. Import the function in app.py
91
+ 4. Create a new Gradio interface for the function
92
+
93
+ ## License
94
+
95
+ MIT
96
+
97
  ---
98
 
99
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,18 +1,12 @@
1
  import gradio as gr
 
 
 
 
 
2
 
3
- def letter_counter(word, letter):
4
- """Count the occurrences of a specific letter in a word.
5
-
6
- Args:
7
- word: The word or phrase to analyze
8
- letter: The letter to count occurrences of
9
-
10
- Returns:
11
- The number of times the letter appears in the word
12
- """
13
- return word.lower().count(letter.lower())
14
-
15
- demo = gr.Interface(
16
  fn=letter_counter,
17
  inputs=["text", "text"],
18
  outputs="number",
@@ -20,4 +14,131 @@ demo = gr.Interface(
20
  description="Count how many times a letter appears in a word"
21
  )
22
 
23
- demo.launch(mcp_server=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from utils.text_utils import letter_counter
3
+ from maths.elementary.arithmetic import add, subtract, multiply, divide
4
+ from maths.middleschool.algebra import solve_linear_equation, evaluate_expression
5
+ from maths.highschool.trigonometry import sin_degrees, cos_degrees, tan_degrees
6
+ from maths.university.calculus import derivative_polynomial, integral_polynomial
7
 
8
+ # Text Utils Tab
9
+ letter_counter_interface = gr.Interface(
 
 
 
 
 
 
 
 
 
 
 
10
  fn=letter_counter,
11
  inputs=["text", "text"],
12
  outputs="number",
 
14
  description="Count how many times a letter appears in a word"
15
  )
16
 
17
+ # Elementary Math Tab
18
+ add_interface = gr.Interface(
19
+ fn=add,
20
+ inputs=[gr.Number(label="A"), gr.Number(label="B")],
21
+ outputs="number",
22
+ title="Addition",
23
+ description="Add two numbers"
24
+ )
25
+
26
+ subtract_interface = gr.Interface(
27
+ fn=subtract,
28
+ inputs=[gr.Number(label="A"), gr.Number(label="B")],
29
+ outputs="number",
30
+ title="Subtraction",
31
+ description="Subtract two numbers"
32
+ )
33
+
34
+ multiply_interface = gr.Interface(
35
+ fn=multiply,
36
+ inputs=[gr.Number(label="A"), gr.Number(label="B")],
37
+ outputs="number",
38
+ title="Multiplication",
39
+ description="Multiply two numbers"
40
+ )
41
+
42
+ divide_interface = gr.Interface(
43
+ fn=divide,
44
+ inputs=[gr.Number(label="A"), gr.Number(label="B")],
45
+ outputs="text",
46
+ title="Division",
47
+ description="Divide two numbers"
48
+ )
49
+
50
+ # Middle School Math Tab
51
+ solve_linear_equation_interface = gr.Interface(
52
+ fn=solve_linear_equation,
53
+ inputs=[
54
+ gr.Number(label="Coefficient (a)"),
55
+ gr.Number(label="Constant (b)")
56
+ ],
57
+ outputs="text",
58
+ title="Linear Equation Solver",
59
+ description="Solve the equation ax = b for x"
60
+ )
61
+
62
+ evaluate_expression_interface = gr.Interface(
63
+ fn=evaluate_expression,
64
+ inputs=[
65
+ gr.Number(label="a (coefficient of x²)"),
66
+ gr.Number(label="b (coefficient of x)"),
67
+ gr.Number(label="c (constant)"),
68
+ gr.Number(label="x (value)")
69
+ ],
70
+ outputs="number",
71
+ title="Quadratic Expression Evaluator",
72
+ description="Evaluate ax² + bx + c for a given value of x"
73
+ )
74
+
75
+ # High School Math Tab
76
+ trig_interface = gr.Interface(
77
+ fn=lambda angle, function: {
78
+ "sin": sin_degrees(angle),
79
+ "cos": cos_degrees(angle),
80
+ "tan": tan_degrees(angle)
81
+ }[function],
82
+ inputs=[
83
+ gr.Number(label="Angle (degrees)"),
84
+ gr.Radio(["sin", "cos", "tan"], label="Trigonometric Function")
85
+ ],
86
+ outputs="number",
87
+ title="Trigonometry Calculator",
88
+ description="Calculate trigonometric functions for angles in degrees"
89
+ )
90
+
91
+ # University Math Tab
92
+ derivative_interface = gr.Interface(
93
+ fn=lambda coefficients: derivative_polynomial([float(c) for c in coefficients.split(',')]),
94
+ inputs=gr.Textbox(label="Polynomial Coefficients (comma-separated, highest degree first)"),
95
+ outputs="json",
96
+ title="Polynomial Derivative",
97
+ description="Find the derivative of a polynomial function"
98
+ )
99
+
100
+ integral_interface = gr.Interface(
101
+ fn=lambda coefficients, c: integral_polynomial([float(x) for x in coefficients.split(',')], float(c)),
102
+ inputs=[
103
+ gr.Textbox(label="Polynomial Coefficients (comma-separated, highest degree first)"),
104
+ gr.Number(label="Integration Constant (c)", value=0)
105
+ ],
106
+ outputs="json",
107
+ title="Polynomial Integration",
108
+ description="Find the indefinite integral of a polynomial function"
109
+ )
110
+
111
+ # Group interfaces by education level
112
+ elementary_tab = gr.TabbedInterface(
113
+ [add_interface, subtract_interface, multiply_interface, divide_interface],
114
+ ["Addition", "Subtraction", "Multiplication", "Division"],
115
+ title="Elementary School Math"
116
+ )
117
+
118
+ middleschool_tab = gr.TabbedInterface(
119
+ [solve_linear_equation_interface, evaluate_expression_interface],
120
+ ["Linear Equations", "Evaluate Expressions"],
121
+ title="Middle School Math"
122
+ )
123
+
124
+ highschool_tab = gr.TabbedInterface(
125
+ [trig_interface],
126
+ ["Trigonometry"],
127
+ title="High School Math"
128
+ )
129
+
130
+ university_tab = gr.TabbedInterface(
131
+ [derivative_interface, integral_interface],
132
+ ["Derivatives", "Integrals"],
133
+ title="University Math"
134
+ )
135
+
136
+ # Main demo with tabs for each education level
137
+ demo = gr.TabbedInterface(
138
+ [letter_counter_interface, elementary_tab, middleschool_tab, highschool_tab, university_tab],
139
+ ["Text Utils", "Elementary", "Middle School", "High School", "University"]
140
+ )
141
+
142
+ # Launch the Gradio app
143
+ if __name__ == "__main__":
144
+ demo.launch(mcp_server=True)
letter_counter.py ADDED
File without changes
maths/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Mathematics tools organized by educational levels.
3
+ """
maths/elementary/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Elementary school level mathematics tools.
3
+ """
maths/elementary/arithmetic.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enhanced arithmetic operations for elementary level with visualization capabilities.
3
+ """
4
+ import numpy as np
5
+ import matplotlib.pyplot as plt
6
+ from typing import Union, Tuple, Any
7
+
8
+ def add(a: float, b: float) -> float:
9
+ """Add two numbers."""
10
+ try:
11
+ return float(a) + float(b)
12
+ except (ValueError, TypeError):
13
+ raise ValueError("Both inputs must be valid numbers")
14
+
15
+ def subtract(a: float, b: float) -> float:
16
+ """Subtract b from a."""
17
+ try:
18
+ return float(a) - float(b)
19
+ except (ValueError, TypeError):
20
+ raise ValueError("Both inputs must be valid numbers")
21
+
22
+ def multiply(a: float, b: float) -> float:
23
+ """Multiply two numbers."""
24
+ try:
25
+ return float(a) * float(b)
26
+ except (ValueError, TypeError):
27
+ raise ValueError("Both inputs must be valid numbers")
28
+
29
+ def divide(a: float, b: float) -> Union[float, str]:
30
+ """Divide a by b."""
31
+ try:
32
+ a, b = float(a), float(b)
33
+ if b == 0:
34
+ return "Error: Division by zero"
35
+ return a / b
36
+ except (ValueError, TypeError):
37
+ return "Error: Both inputs must be valid numbers"
38
+
39
+ def create_number_line_visualization(numbers: list, operation: str, result: float) -> plt.Figure:
40
+ """Create a number line visualization for arithmetic operations."""
41
+ fig, ax = plt.subplots(figsize=(10, 4))
42
+
43
+ # Determine range for number line
44
+ all_nums = numbers + [result]
45
+ min_val = min(all_nums) - 2
46
+ max_val = max(all_nums) + 2
47
+
48
+ # Draw number line
49
+ ax.axhline(y=0, color='black', linewidth=2)
50
+ ax.set_xlim(min_val, max_val)
51
+ ax.set_ylim(-1, 1)
52
+
53
+ # Add tick marks and labels
54
+ tick_range = np.arange(int(min_val), int(max_val) + 1)
55
+ ax.set_xticks(tick_range)
56
+ for tick in tick_range:
57
+ ax.axvline(x=tick, ymin=0.4, ymax=0.6, color='black', linewidth=1)
58
+
59
+ # Highlight the numbers involved in the operation
60
+ colors = ['red', 'blue', 'green']
61
+ for i, num in enumerate(numbers):
62
+ ax.plot(num, 0, 'o', markersize=10, color=colors[i % len(colors)],
63
+ label=f'Number {i+1}: {num}')
64
+
65
+ # Highlight the result
66
+ ax.plot(result, 0, 's', markersize=12, color='purple', label=f'Result: {result}')
67
+
68
+ # Add operation description
69
+ if len(numbers) == 2:
70
+ op_symbol = {'add': '+', 'subtract': '-', 'multiply': '×', 'divide': '÷'}.get(operation, '?')
71
+ title = f"{numbers[0]} {op_symbol} {numbers[1]} = {result}"
72
+ else:
73
+ title = f"Result: {result}"
74
+
75
+ ax.set_title(title, fontsize=14, fontweight='bold')
76
+ ax.legend(loc='upper right')
77
+ ax.set_ylabel('')
78
+ ax.set_xlabel('Number Line')
79
+ ax.grid(True, alpha=0.3)
80
+
81
+ return fig
82
+
83
+ def arithmetic_with_visualization(a: float, b: float, operation: str) -> Tuple[Any, plt.Figure]:
84
+ """Perform arithmetic operation and return result with visualization."""
85
+ try:
86
+ a, b = float(a), float(b)
87
+
88
+ if operation == 'add':
89
+ result = add(a, b)
90
+ elif operation == 'subtract':
91
+ result = subtract(a, b)
92
+ elif operation == 'multiply':
93
+ result = multiply(a, b)
94
+ elif operation == 'divide':
95
+ result = divide(a, b)
96
+ if isinstance(result, str): # Error case
97
+ return result, None
98
+ else:
99
+ return "Error: Unknown operation", None
100
+
101
+ # Create visualization
102
+ fig = create_number_line_visualization([a, b], operation, result)
103
+
104
+ return result, fig
105
+
106
+ except Exception as e:
107
+ return f"Error: {str(e)}", None
108
+
109
+ def create_multiplication_table(number: int, max_multiplier: int = 12) -> plt.Figure:
110
+ """Create a visual multiplication table."""
111
+ fig, ax = plt.subplots(figsize=(8, 6))
112
+
113
+ multipliers = np.arange(1, max_multiplier + 1)
114
+ results = number * multipliers
115
+
116
+ # Create bar chart
117
+ bars = ax.bar(multipliers, results, color='skyblue', alpha=0.7, edgecolor='navy')
118
+
119
+ # Add value labels on bars
120
+ for bar, result in zip(bars, results):
121
+ height = bar.get_height()
122
+ ax.text(bar.get_x() + bar.get_width()/2., height + max(results) * 0.01,
123
+ f'{result}', ha='center', va='bottom', fontweight='bold')
124
+
125
+ ax.set_xlabel('Multiplier', fontsize=12)
126
+ ax.set_ylabel('Result', fontsize=12)
127
+ ax.set_title(f'Multiplication Table for {number}', fontsize=14, fontweight='bold')
128
+ ax.grid(True, alpha=0.3)
129
+ ax.set_xticks(multipliers)
130
+
131
+ return fig
maths/highschool/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Highschool level mathematics tools.
3
+ """
maths/highschool/trigonometry.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Trigonometry operations for high school level.
3
+ """
4
+ import math
5
+
6
+ def sin_degrees(angle):
7
+ """Calculate the sine of an angle in degrees."""
8
+ return math.sin(math.radians(angle))
9
+
10
+ def cos_degrees(angle):
11
+ """Calculate the cosine of an angle in degrees."""
12
+ return math.cos(math.radians(angle))
13
+
14
+ def tan_degrees(angle):
15
+ """Calculate the tangent of an angle in degrees."""
16
+ return math.tan(math.radians(angle))
maths/middleschool/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Middle school level mathematics tools.
3
+ """
maths/middleschool/algebra.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Basic algebra operations for middle school level.
3
+ """
4
+
5
+ def solve_linear_equation(a, b):
6
+ """
7
+ Solve the equation ax = b for x.
8
+ Returns the value of x.
9
+ """
10
+ if a == 0:
11
+ if b == 0:
12
+ return "Infinite solutions"
13
+ return "No solution"
14
+ return b / a
15
+
16
+ def evaluate_expression(a, b, c, x):
17
+ """
18
+ Evaluate the expression ax² + bx + c for a given value of x.
19
+ """
20
+ return a * (x ** 2) + b * x + c
maths/university/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ University level mathematics tools.
3
+ """
maths/university/calculus.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Calculus operations for university level.
3
+ """
4
+
5
+ def derivative_polynomial(coefficients):
6
+ """
7
+ Calculate the derivative of a polynomial function.
8
+
9
+ Args:
10
+ coefficients (list): List of coefficients from highest to lowest degree
11
+
12
+ Returns:
13
+ list: Coefficients of the derivative polynomial
14
+ """
15
+ if len(coefficients) <= 1:
16
+ return [0]
17
+
18
+ result = []
19
+ for i, coef in enumerate(coefficients[:-1]):
20
+ power = len(coefficients) - i - 1
21
+ result.append(coef * power)
22
+
23
+ return result
24
+
25
+ def integral_polynomial(coefficients, c=0):
26
+ """
27
+ Calculate the indefinite integral of a polynomial function.
28
+
29
+ Args:
30
+ coefficients (list): List of coefficients from highest to lowest degree
31
+ c (float): Integration constant
32
+
33
+ Returns:
34
+ list: Coefficients of the integral polynomial including constant term
35
+ """
36
+ result = []
37
+ for i, coef in enumerate(coefficients):
38
+ power = len(coefficients) - i
39
+ result.append(coef / power)
40
+
41
+ result.append(c) # Add integration constant
42
+ return result
utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """
2
+ Utility functions for general purposes.
3
+ """
utils/text_utils.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for text processing.
3
+ """
4
+
5
+ def letter_counter(word, letter):
6
+ """Count the occurrences of a specific letter in a word."""
7
+ return word.lower().count(letter.lower())