tanjinadnanabir commited on
Commit
1c2e2cf
ยท
verified ยท
1 Parent(s): 289691c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +314 -0
app.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import os
5
+ import re
6
+
7
+ # API Configuration
8
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
9
+ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
10
+
11
+ # Problem themes and topics
12
+ THEMES = {
13
+ "๐ŸŽฎ Gaming": ["video games", "esports", "streaming", "game development"],
14
+ "โšฝ Sports": ["soccer", "basketball", "olympics", "skateboarding"],
15
+ "๐Ÿš€ Space": ["astronauts", "planets", "rockets", "aliens"],
16
+ "๐Ÿ• Food": ["pizza party", "baking", "restaurant", "food truck"],
17
+ "๐ŸŽต Music": ["concert", "band", "playlist", "music festival"],
18
+ "๐Ÿพ Animals": ["zoo", "pets", "wildlife", "ocean creatures"],
19
+ "๐Ÿ’ป Tech": ["coding", "robots", "apps", "social media"],
20
+ "๐ŸŽจ Art": ["painting", "museum", "crafts", "design"],
21
+ }
22
+
23
+ GRADE_LEVELS = {
24
+ "Elementary (1-5)": "simple addition, subtraction, multiplication, division",
25
+ "Middle School (6-8)": "fractions, decimals, percentages, basic algebra",
26
+ "High School (9-12)": "algebra, geometry, trigonometry, basic calculus",
27
+ "College+": "advanced calculus, linear algebra, differential equations"
28
+ }
29
+
30
+ def call_groq_api(prompt: str):
31
+ """Call Groq API"""
32
+ if not GROQ_API_KEY:
33
+ return None
34
+
35
+ url = "https://api.groq.com/openai/v1/chat/completions"
36
+ headers = {
37
+ "Authorization": f"Bearer {GROQ_API_KEY}",
38
+ "Content-Type": "application/json"
39
+ }
40
+
41
+ payload = {
42
+ "model": "llama-3.3-70b-versatile",
43
+ "messages": [{"role": "user", "content": prompt}],
44
+ "temperature": 0.7,
45
+ "max_tokens": 1500
46
+ }
47
+
48
+ try:
49
+ response = requests.post(url, headers=headers, json=payload, timeout=30)
50
+ response.raise_for_status()
51
+ return response.json()["choices"][0]["message"]["content"]
52
+ except Exception as e:
53
+ print(f"Groq error: {e}")
54
+ return None
55
+
56
+ def call_gemini_api(prompt: str):
57
+ """Fallback to Gemini"""
58
+ if not GEMINI_API_KEY:
59
+ return None
60
+
61
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key={GEMINI_API_KEY}"
62
+
63
+ payload = {
64
+ "contents": [{"parts": [{"text": prompt}]}],
65
+ "generationConfig": {"temperature": 0.7, "maxOutputTokens": 1500}
66
+ }
67
+
68
+ try:
69
+ response = requests.post(url, json=payload, timeout=30)
70
+ response.raise_for_status()
71
+ return response.json()["candidates"][0]["content"]["parts"][0]["text"]
72
+ except Exception as e:
73
+ print(f"Gemini error: {e}")
74
+ return None
75
+
76
+ def generate_problem(theme: str, grade: str, custom_topic: str = ""):
77
+ """Generate a story problem"""
78
+
79
+ topic = custom_topic if custom_topic else THEMES.get(theme, ["general math"])[0]
80
+ math_level = GRADE_LEVELS.get(grade, "basic arithmetic")
81
+
82
+ prompt = f"""Create an engaging math story problem for {grade} students.
83
+
84
+ Theme: {topic}
85
+ Math concepts: {math_level}
86
+
87
+ Requirements:
88
+ 1. Write a fun, relatable story (2-3 sentences)
89
+ 2. Include specific numbers that make sense
90
+ 3. Ask 2-3 questions of increasing difficulty
91
+ 4. Make it realistic and age-appropriate
92
+ 5. Use emojis to make it engaging
93
+
94
+ Format your response as:
95
+ TITLE: [Catchy title with emoji]
96
+ STORY: [The scenario]
97
+ QUESTIONS:
98
+ 1. [Question 1 - easiest]
99
+ 2. [Question 2 - medium]
100
+ 3. [Question 3 - hardest]
101
+
102
+ Example for reference:
103
+ TITLE: ๐ŸŽฎ The Streaming Marathon
104
+ STORY: Alex is streaming a gaming marathon to raise money for charity. They stream for 6 hours on Saturday and 4 hours on Sunday. Their average viewership is 250 people per hour, and each viewer donates $0.50 per hour watched.
105
+ QUESTIONS:
106
+ 1. How many total hours did Alex stream?
107
+ 2. How many total viewer-hours did they get?
108
+ 3. How much money did they raise for charity?"""
109
+
110
+ response = call_groq_api(prompt) or call_gemini_api(prompt)
111
+
112
+ if not response:
113
+ return "โŒ **Error**: Please add GROQ_API_KEY or GEMINI_API_KEY in Space settings.", ""
114
+
115
+ return format_problem_html(response), response
116
+
117
+ def solve_problem(problem_text: str):
118
+ """Solve a given problem with step-by-step explanation"""
119
+
120
+ prompt = f"""Solve this math problem with detailed step-by-step explanations.
121
+
122
+ Problem:
123
+ {problem_text}
124
+
125
+ Provide:
126
+ 1. A clear breakdown of what's being asked
127
+ 2. Step-by-step solution for each question
128
+ 3. Visual aids (use ASCII art, diagrams if helpful)
129
+ 4. Final answers clearly marked
130
+ 5. A "Check your work" tip
131
+
132
+ Format with markdown for readability. Use emojis to make it engaging."""
133
+
134
+ response = call_groq_api(prompt) or call_gemini_api(prompt)
135
+
136
+ if not response:
137
+ return "โŒ **Error**: Please add API key in Space settings."
138
+
139
+ return format_solution_html(response)
140
+
141
+ def format_problem_html(text: str):
142
+ """Format problem in nice HTML"""
143
+ html = f"""
144
+ <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
145
+ padding: 30px; border-radius: 15px; color: white; font-family: 'Segoe UI', sans-serif;">
146
+ <div style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px);
147
+ padding: 25px; border-radius: 12px; margin-bottom: 20px;">
148
+ <pre style="color: white; font-size: 16px; line-height: 1.8; white-space: pre-wrap; font-family: inherit;">
149
+ {text}
150
+ </pre>
151
+ </div>
152
+ <div style="text-align: center; margin-top: 15px; color: rgba(255,255,255,0.8); font-size: 14px;">
153
+ โœจ Scroll down to see the solution! โœจ
154
+ </div>
155
+ </div>
156
+ """
157
+ return html
158
+
159
+ def format_solution_html(text: str):
160
+ """Format solution in nice HTML"""
161
+ html = f"""
162
+ <div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
163
+ padding: 30px; border-radius: 15px; color: white; font-family: 'Segoe UI', sans-serif;">
164
+ <div style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px);
165
+ padding: 25px; border-radius: 12px;">
166
+ <h2 style="margin-top: 0; color: white;">๐Ÿ“ Step-by-Step Solution</h2>
167
+ <div style="color: white; font-size: 15px; line-height: 1.8;">
168
+ {text.replace(chr(10), '<br>')}
169
+ </div>
170
+ </div>
171
+ </div>
172
+ """
173
+ return html
174
+
175
+ # Gradio Interface
176
+ with gr.Blocks(
177
+ theme=gr.themes.Soft(),
178
+ css="""
179
+ .gradio-container {max-width: 900px !important;}
180
+ .generate-btn {background: linear-gradient(90deg, #667eea, #764ba2) !important;
181
+ color: white !important; font-weight: 600 !important; border: none !important;}
182
+ .solve-btn {background: linear-gradient(90deg, #11998e, #38ef7d) !important;
183
+ color: white !important; font-weight: 600 !important; border: none !important;}
184
+ """,
185
+ title="๐Ÿงฎ Math Story Problem Generator"
186
+ ) as demo:
187
+
188
+ gr.Markdown("""
189
+ # ๐Ÿงฎ Math Story Problem Generator & Solver
190
+ ### Transform boring math into exciting stories! ๐ŸŽ‰
191
+
192
+ **Generate** personalized word problems based on your interests, or **paste** any problem to get a detailed solution.
193
+ """)
194
+
195
+ with gr.Tabs():
196
+ # GENERATE TAB
197
+ with gr.Tab("โœจ Generate Problem"):
198
+ with gr.Row():
199
+ with gr.Column():
200
+ theme_choice = gr.Dropdown(
201
+ choices=list(THEMES.keys()),
202
+ value="๐ŸŽฎ Gaming",
203
+ label="๐Ÿ“š Choose Theme",
204
+ info="Pick what interests you!"
205
+ )
206
+
207
+ grade_choice = gr.Dropdown(
208
+ choices=list(GRADE_LEVELS.keys()),
209
+ value="Middle School (6-8)",
210
+ label="๐ŸŽ“ Grade Level"
211
+ )
212
+
213
+ custom_topic = gr.Textbox(
214
+ label="๐ŸŽฏ Custom Topic (Optional)",
215
+ placeholder="e.g., 'TikTok followers', 'Minecraft building', 'sneaker collection'",
216
+ lines=1
217
+ )
218
+
219
+ generate_btn = gr.Button(
220
+ "๐Ÿš€ Generate Story Problem",
221
+ variant="primary",
222
+ size="lg",
223
+ elem_classes="generate-btn"
224
+ )
225
+
226
+ problem_output = gr.HTML(label="Generated Problem")
227
+ problem_text_state = gr.State()
228
+
229
+ with gr.Row():
230
+ show_solution_btn = gr.Button(
231
+ "๐Ÿ“ Show Solution",
232
+ variant="secondary",
233
+ size="lg",
234
+ elem_classes="solve-btn"
235
+ )
236
+
237
+ solution_output = gr.HTML(label="Solution", visible=False)
238
+
239
+ # SOLVE TAB
240
+ with gr.Tab("๐Ÿ” Solve Problem"):
241
+ gr.Markdown("""
242
+ ### Paste any math problem and get a detailed solution!
243
+ Works with story problems, equations, geometry, algebra, and more.
244
+ """)
245
+
246
+ paste_problem = gr.Textbox(
247
+ label="๐Ÿ“‹ Paste Your Math Problem",
248
+ placeholder="Example: A train leaves Chicago at 60 mph. Another train leaves NYC (800 miles away) at 40 mph. When do they meet?",
249
+ lines=5
250
+ )
251
+
252
+ solve_btn = gr.Button(
253
+ "๐Ÿง  Solve It!",
254
+ variant="primary",
255
+ size="lg",
256
+ elem_classes="solve-btn"
257
+ )
258
+
259
+ solve_output = gr.HTML(label="Solution")
260
+
261
+ gr.Markdown("""
262
+ ---
263
+ ## ๐ŸŽฏ Features
264
+ - โœ… **Personalized**: Choose themes you love
265
+ - โœ… **Adaptive**: Problems match your grade level
266
+ - โœ… **Step-by-Step**: Detailed solutions with explanations
267
+ - โœ… **Visual**: ASCII art and diagrams when helpful
268
+ - โœ… **Free**: Powered by free AI APIs!
269
+
270
+ ## ๐Ÿ”‘ Setup
271
+ Add **GROQ_API_KEY** (from console.groq.com) as a HuggingFace Secret to enable generation.
272
+ Gemini API also supported as fallback!
273
+
274
+ ## ๐Ÿ’ก Tips
275
+ - Try custom topics that match your interests
276
+ - Generate multiple problems to practice
277
+ - Challenge yourself with harder grade levels
278
+ - Use the solver to check your own work
279
+
280
+ ---
281
+ *Built with โค๏ธ for math learners everywhere*
282
+ """)
283
+
284
+ # Event handlers
285
+ def generate_and_show(theme, grade, custom):
286
+ html, text = generate_problem(theme, grade, custom)
287
+ return html, text, gr.update(visible=False)
288
+
289
+ def show_solution_for_problem(problem_text):
290
+ if not problem_text:
291
+ return gr.update(visible=False)
292
+ solution = solve_problem(problem_text)
293
+ return gr.update(value=solution, visible=True)
294
+
295
+ generate_btn.click(
296
+ fn=generate_and_show,
297
+ inputs=[theme_choice, grade_choice, custom_topic],
298
+ outputs=[problem_output, problem_text_state, solution_output]
299
+ )
300
+
301
+ show_solution_btn.click(
302
+ fn=show_solution_for_problem,
303
+ inputs=[problem_text_state],
304
+ outputs=[solution_output]
305
+ )
306
+
307
+ solve_btn.click(
308
+ fn=solve_problem,
309
+ inputs=[paste_problem],
310
+ outputs=[solve_output]
311
+ )
312
+
313
+ if __name__ == "__main__":
314
+ demo.launch()