Khoi1234210 commited on
Commit
bbd8ccb
·
verified ·
1 Parent(s): 6d37435

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -34
app.py CHANGED
@@ -1,6 +1,57 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def respond(
6
  message,
@@ -12,59 +63,203 @@ def respond(
12
  hf_token: gr.OAuthToken,
13
  ):
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
18
 
 
19
  messages = [{"role": "system", "content": system_message}]
20
-
21
  messages.extend(history)
22
-
23
  messages.append({"role": "user", "content": message})
24
 
25
  response = ""
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  chatbot = gr.ChatInterface(
47
  respond,
48
  type="messages",
 
 
 
 
 
 
 
49
  additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  gr.Slider(
54
  minimum=0.1,
55
  maximum=1.0,
56
- value=0.95,
57
  step=0.05,
58
- label="Top-p (nucleus sampling)",
59
  ),
60
  ],
 
 
 
 
 
 
 
 
 
 
 
 
61
  )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ from datasets import load_dataset
4
+ import random
5
 
6
+ # Load math datasets for sample problems
7
+ def load_sample_problems():
8
+ """Load sample problems from math datasets"""
9
+ try:
10
+ # Load GSM8K for sample problems
11
+ gsm8k = load_dataset("openai/gsm8k", "main", streaming=True)
12
+ samples = []
13
+ for i, item in enumerate(gsm8k["train"]):
14
+ samples.append(item["question"])
15
+ if i >= 50: # Load 50 samples
16
+ break
17
+ return samples
18
+ except:
19
+ return [
20
+ "What is the derivative of f(x) = 3x² + 2x - 1?",
21
+ "A triangle has sides of length 5, 12, and 13. What is its area?",
22
+ "If log₂(x) + log₂(x+6) = 4, find the value of x.",
23
+ "Find the limit: lim(x→0) (sin(x)/x)",
24
+ "Solve the system: x + 2y = 7, 3x - y = 4"
25
+ ]
26
+
27
+ # Initialize sample problems
28
+ math_samples = load_sample_problems()
29
+
30
+ def create_math_system_message():
31
+ """Create specialized system prompt for mathematics"""
32
+ return """You are Mathetics AI, an advanced mathematics tutor and problem solver.
33
+
34
+ 🧮 **Your Expertise:**
35
+ - Step-by-step problem solving with clear explanations
36
+ - Multiple solution approaches when applicable
37
+ - Proper mathematical notation and terminology
38
+ - Verification of answers through different methods
39
+
40
+ 📐 **Problem Domains:**
41
+ - Arithmetic, Algebra, and Number Theory
42
+ - Geometry, Trigonometry, and Coordinate Geometry
43
+ - Calculus (Limits, Derivatives, Integrals)
44
+ - Statistics, Probability, and Data Analysis
45
+ - Competition Mathematics (AMC, AIME level)
46
+
47
+ 💡 **Teaching Style:**
48
+ 1. **Understand the Problem** - Identify what's being asked
49
+ 2. **Plan the Solution** - Choose the appropriate method
50
+ 3. **Execute Step-by-Step** - Show all work clearly
51
+ 4. **Verify the Answer** - Check if the result makes sense
52
+ 5. **Alternative Methods** - Mention other possible approaches
53
+
54
+ Always be precise, educational, and encourage mathematical thinking."""
55
 
56
  def respond(
57
  message,
 
63
  hf_token: gr.OAuthToken,
64
  ):
65
  """
66
+ Enhanced response function for mathematical problem solving
67
  """
68
+ # Use Qwen Math model for better mathematical reasoning
69
+ client = InferenceClient(
70
+ token=hf_token.token if hf_token else None,
71
+ model="Qwen/Qwen2.5-Math-7B-Instruct" # Specialized math model
72
+ )
73
 
74
+ # Build message history
75
  messages = [{"role": "system", "content": system_message}]
 
76
  messages.extend(history)
 
77
  messages.append({"role": "user", "content": message})
78
 
79
  response = ""
80
 
81
+ try:
82
+ for message_chunk in client.chat_completion(
83
+ messages,
84
+ max_tokens=max_tokens,
85
+ stream=True,
86
+ temperature=temperature,
87
+ top_p=top_p,
88
+ ):
89
+ choices = message_chunk.choices
90
+ token = ""
91
+ if len(choices) and choices[0].delta.content:
92
+ token = choices[0].delta.content
93
+
94
+ response += token
95
+ yield response
96
+
97
+ except Exception as e:
98
+ error_msg = f"❌ **Error**: {str(e)}\n\n💡 **Troubleshooting**:\n- Make sure you're logged in with Hugging Face\n- Check if the model is accessible\n- Try a simpler problem first"
99
+ yield error_msg
100
+
101
+ def get_random_sample():
102
+ """Get a random sample problem"""
103
+ if math_samples:
104
+ return random.choice(math_samples)
105
+ return "Solve for x: 2x² + 5x - 3 = 0"
106
+
107
+ def set_difficulty_preset(difficulty):
108
+ """Set temperature and other params based on difficulty"""
109
+ presets = {
110
+ "Elementary": (0.2, 0.8, 512), # Low temp for accuracy
111
+ "High School": (0.3, 0.85, 768), # Balanced
112
+ "College": (0.4, 0.9, 1024), # More exploration
113
+ "Competition": (0.3, 0.8, 1536) # Detailed solutions
114
+ }
115
+ return presets.get(difficulty, (0.3, 0.85, 768))
116
+
117
+ # Create the enhanced ChatInterface
118
  chatbot = gr.ChatInterface(
119
  respond,
120
  type="messages",
121
+ title="🧮 **Mathetics AI** - Advanced Mathematics Solver",
122
+ description="""
123
+ **Powered by Qwen 2.5-Math** | **Specialized for Mathematical Problem Solving**
124
+
125
+ ✨ **Capabilities**: Algebra • Geometry • Calculus • Statistics • Competition Math
126
+ 📚 **Features**: Step-by-step solutions • Multiple approaches • Clear explanations
127
+ """,
128
  additional_inputs=[
129
+ gr.Textbox(
130
+ value=create_math_system_message(),
131
+ label="🧠 System Message (Math Tutor Personality)",
132
+ lines=3,
133
+ max_lines=10
134
+ ),
135
+ gr.Slider(
136
+ minimum=256,
137
+ maximum=2048,
138
+ value=768,
139
+ step=64,
140
+ label="📝 Max Tokens (Solution Length)"
141
+ ),
142
+ gr.Slider(
143
+ minimum=0.1,
144
+ maximum=1.0,
145
+ value=0.3,
146
+ step=0.1,
147
+ label="🎯 Temperature (Creativity vs Precision)"
148
+ ),
149
  gr.Slider(
150
  minimum=0.1,
151
  maximum=1.0,
152
+ value=0.85,
153
  step=0.05,
154
+ label="🔍 Top-p (Response Diversity)",
155
  ),
156
  ],
157
+ examples=[
158
+ ["What is the derivative of f(x) = 3x² + 2x - 1?"],
159
+ ["A triangle has sides of length 5, 12, and 13. What is its area?"],
160
+ ["If log₂(x) + log₂(x+6) = 4, find the value of x."],
161
+ ["A bag contains 5 red balls and 7 blue balls. What's the probability of drawing 2 red balls without replacement?"],
162
+ ["Find the limit: lim(x→0) (sin(x)/x)"],
163
+ ["Solve the system of equations: x + 2y = 7 and 3x - y = 4"],
164
+ ["What is the integral of ∫(2x³ - 5x + 3)dx?"],
165
+ ["In a right triangle, if one angle is 30° and the hypotenuse is 10, find the lengths of the other two sides."]
166
+ ],
167
+ cache_examples=False, # Don't cache for dynamic math problems
168
+ concurrency_limit=10,
169
  )
170
 
171
+ # Enhanced interface with additional features
172
+ with gr.Blocks(
173
+ title="🧮 Mathetics AI",
174
+ theme=gr.themes.Soft(),
175
+ css="""
176
+ .math-highlight {
177
+ background-color: #f0f8ff;
178
+ padding: 10px;
179
+ border-left: 4px solid #4CAF50;
180
+ margin: 10px 0;
181
+ border-radius: 5px;
182
+ }
183
+ .difficulty-selector {
184
+ background-color: #fff3e0;
185
+ padding: 15px;
186
+ border-radius: 10px;
187
+ margin: 10px 0;
188
+ }
189
+ """
190
+ ) as demo:
191
+
192
+ gr.Markdown("""
193
+ # 🧮 **Mathetics AI** - Advanced Mathematics Solver
194
+
195
+ **Your Personal AI Math Tutor** | Specialized in step-by-step problem solving across all mathematical domains
196
+ """)
197
+
198
+ with gr.Row():
199
+ with gr.Column(scale=4):
200
+ # Main chat interface
201
+ chatbot.render()
202
+
203
+ with gr.Column(scale=1):
204
+ # Sidebar with additional features
205
+ with gr.Accordion("🎲 **Quick Actions**", open=True):
206
+
207
+ difficulty_preset = gr.Dropdown(
208
+ choices=["Elementary", "High School", "College", "Competition"],
209
+ value="High School",
210
+ label="🎯 Problem Difficulty",
211
+ elem_classes=["difficulty-selector"]
212
+ )
213
+
214
+ sample_btn = gr.Button("🎯 Get Sample Problem", variant="secondary", size="sm")
215
+ help_btn = gr.Button("❓ Math Help Tips", variant="secondary", size="sm")
216
+
217
+ # Quick math tools
218
+ gr.Markdown("### 🔧 **Quick Tools**")
219
+ gr.Markdown("""
220
+ - **Algebra**: Equations, inequalities, factoring
221
+ - **Geometry**: Area, volume, trigonometry
222
+ - **Calculus**: Derivatives, integrals, limits
223
+ - **Statistics**: Probability, distributions
224
+ - **Number Theory**: Prime factorization, GCD/LCM
225
+ """)
226
+
227
+ # Footer with information
228
+ gr.Markdown("""
229
+ ---
230
+ **🔧 Technical Details:**
231
+ - **Model**: Qwen/Qwen2.5-Math-7B-Instruct (Specialized for Mathematics)
232
+ - **Authentication**: Automatic via Hugging Face OAuth
233
+ - **Features**: Real-time streaming responses, step-by-step solutions
234
+
235
+ **💡 Usage Tips:**
236
+ - Be specific about what you want to find or solve
237
+ - Mention if you want step-by-step solutions
238
+ - Ask for alternative solution methods
239
+ - Request verification of your own solutions
240
+ """)
241
+
242
+ # Event handlers for additional functionality
243
+ def insert_sample(difficulty):
244
+ sample = get_random_sample()
245
+ return sample
246
+
247
+ def show_help():
248
+ return """**Math Help Tips:**
249
+
250
+ 1. **Be Specific**: "Find the derivative of..." instead of "Help with calculus"
251
+ 2. **Show Your Work**: "I got x=5, is this correct?"
252
+ 3. **Ask for Steps**: "Show me step-by-step how to solve..."
253
+ 4. **Request Verification**: "Check my solution to this problem"
254
+ 5. **Alternative Methods**: "What's another way to solve this?"
255
+ """
256
+
257
+ # Connect sample button (this would need to be integrated with the chat properly)
258
+ sample_btn.click(
259
+ lambda x: get_random_sample(),
260
+ inputs=[difficulty_preset],
261
+ outputs=[] # Would need proper integration with chat input
262
+ )
263
 
264
  if __name__ == "__main__":
265
+ demo.launch()