vishwakayireddi1234 commited on
Commit
bfa49d6
Β·
verified Β·
1 Parent(s): c6be2bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -56
app.py CHANGED
@@ -4,11 +4,9 @@ import os
4
  from io import BytesIO
5
  from huggingface_hub import InferenceClient
6
 
7
- # Space owner can pre-set a token as a Secret named HF_TOKEN
8
- # If not set, users provide their own below
9
  SPACE_TOKEN = os.environ.get("HF_TOKEN", "")
10
 
11
- # Mistral is open-licensed, no gate, works with any valid HF token
12
  TEXT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
13
 
14
  SYSTEM_PROMPT = """You are a warm, patient math tutor for students from Grade 1 through High School.
@@ -53,18 +51,22 @@ def image_to_base64(pil_image):
53
  return None
54
 
55
 
 
 
 
 
 
56
  def solve_math(image_input, text_input, grade_level, user_token):
57
- # Decide which token to use
58
  token = user_token.strip() if user_token and user_token.strip() else SPACE_TOKEN
59
 
60
  if not token:
61
  yield (
62
- "πŸ”‘ **A HuggingFace token is required to use this app.**\n\n"
63
  "It's free and takes 30 seconds:\n"
64
  "1. Go to [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)\n"
65
- "2. Click **New token** β†’ choose **Read** access β†’ copy it\n"
66
- "3. Paste it in the **HuggingFace Token** box on the left\n\n"
67
- "Your token is never stored β€” it's only used for this session."
68
  )
69
  return
70
 
@@ -79,23 +81,19 @@ def solve_math(image_input, text_input, grade_level, user_token):
79
 
80
  grade_note = f"Grade level: {grade_level}."
81
 
82
- # Build problem text
83
  if has_image and has_text:
84
- problem_text = (
85
- f"I have a worksheet image with a math problem. "
86
- f"Here is what it says (typed by me): {text_input.strip()}\n"
87
- f"Please teach me how to solve it step by step."
88
- )
89
  elif has_image:
90
  problem_text = (
91
- "I have a worksheet image with a math problem. "
92
- "Please describe what kind of problem it likely is and teach me how to solve it step by step. "
93
- "If you cannot see the image content, ask me to type the problem."
94
  )
95
  else:
96
  problem_text = text_input.strip()
97
 
98
- full_prompt = f"{grade_note}\n\nProblem: {problem_text}"
 
99
 
100
  yield "⚑ Solving step by step..."
101
 
@@ -103,25 +101,20 @@ def solve_math(image_input, text_input, grade_level, user_token):
103
  client = InferenceClient(
104
  model=TEXT_MODEL,
105
  token=token,
106
- provider="hf-inference",
107
  )
108
 
109
- stream = client.chat.completions.create(
110
- messages=[
111
- {"role": "system", "content": SYSTEM_PROMPT},
112
- {"role": "user", "content": full_prompt},
113
- ],
114
- max_tokens=1200,
115
  temperature=0.3,
 
116
  stream=True,
117
- )
118
-
119
- output = ""
120
- for chunk in stream:
121
- token_text = chunk.choices[0].delta.content or ""
122
- if token_text:
123
- output += token_text
124
- yield output
125
 
126
  if not output:
127
  yield "⚠️ No response received. Please try again in a moment."
@@ -130,8 +123,8 @@ def solve_math(image_input, text_input, grade_level, user_token):
130
  err = str(e)
131
  if "401" in err:
132
  yield (
133
- "❌ **Invalid token.** Please check your HuggingFace token and try again.\n\n"
134
- "Get a free token at [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)"
135
  )
136
  elif "503" in err or "loading" in err.lower():
137
  yield "⏳ **Model is warming up.** Please wait ~30 seconds and try again."
@@ -151,7 +144,6 @@ CSS = """
151
  --accent: #58a6ff;
152
  --accent2: #bc8cff;
153
  --green: #3fb950;
154
- --red: #f85149;
155
  --text: #e6edf3;
156
  --muted: #7d8590;
157
  --border: #30363d;
@@ -205,14 +197,13 @@ GRADE_CHOICES = [
205
  ]
206
 
207
  EXAMPLES = [
208
- [None, "What is 24 Γ· 6 + 3 Γ— 2?", "Grade 3–4 (Multiplication, Division, Fractions Intro)"],
209
- [None, "If I have 3/4 of a pizza and eat 1/3, how much is left?", "Grade 5–6 (Fractions, Decimals, Geometry Basics)"],
210
- [None, "Solve for x: 2x + 5 = 17", "Grade 7–8 (Algebra, Ratios, Percentages)"],
211
- [None, "Find the area of a circle with radius 7 cm", "Grade 9–10 (Algebra II, Geometry, Trigonometry)"],
212
- [None, "Differentiate f(x) = 3xΒ³ βˆ’ 2x + 7", "Grade 11–12 (Pre-Calculus, Statistics, Calculus)"],
213
  ]
214
 
215
- # Whether space owner has pre-configured a token
216
  OWNER_TOKEN_SET = bool(SPACE_TOKEN)
217
 
218
  with gr.Blocks(css=CSS, title="Interactive Math Tutor") as demo:
@@ -235,32 +226,23 @@ with gr.Blocks(css=CSS, title="Interactive Math Tutor") as demo:
235
  with gr.Row(equal_height=False):
236
  with gr.Column(scale=4, min_width=300):
237
 
238
- # Only show token box if owner hasn't pre-set one
239
  if not OWNER_TOKEN_SET:
240
  gr.HTML('<div class="panel-label">πŸ”‘ HuggingFace Token (free)</div>')
241
  user_token = gr.Textbox(
242
- label="",
243
- placeholder="hf_xxxxxxxxxxxxxxxxxxxx",
244
- type="password",
245
- lines=1,
246
- elem_classes=["token-box"],
247
  )
248
  gr.HTML("""
249
  <div class="token-info">
250
  <strong>Get your free token in 30 seconds:</strong><br>
251
  1. Go to <a href="https://huggingface.co/settings/tokens" target="_blank">huggingface.co/settings/tokens</a><br>
252
  2. Click <strong>New token</strong> β†’ <strong>Read</strong> access β†’ Copy<br>
253
- 3. Paste it above Β· Never stored, session-only
254
  </div>
255
  """)
256
  else:
257
  user_token = gr.Textbox(value="", visible=False)
258
- gr.HTML("""
259
- <div class="info-box">
260
- <strong>βœ… Ready to use β€” no setup needed!</strong><br>
261
- Token pre-configured by the Space owner.
262
- </div>
263
- """)
264
 
265
  gr.HTML('<div class="panel-label" style="margin-top:16px">πŸ“Ž Upload Worksheet (optional)</div>')
266
  image_input = gr.Image(type="pil", label="", height=180)
@@ -281,7 +263,7 @@ with gr.Blocks(css=CSS, title="Interactive Math Tutor") as demo:
281
 
282
  gr.HTML('<div class="panel-label" style="margin-top:16px">πŸ’‘ Try an example</div>')
283
  gr.Examples(
284
- examples=[[None, p, g, ""] for (_, p, g) in EXAMPLES],
285
  inputs=[image_input, text_input, grade_dropdown, user_token],
286
  label=""
287
  )
 
4
  from io import BytesIO
5
  from huggingface_hub import InferenceClient
6
 
 
 
7
  SPACE_TOKEN = os.environ.get("HF_TOKEN", "")
8
 
9
+ # Models confirmed to work with free HF inference text_generation task
10
  TEXT_MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
11
 
12
  SYSTEM_PROMPT = """You are a warm, patient math tutor for students from Grade 1 through High School.
 
51
  return None
52
 
53
 
54
+ def build_mistral_prompt(system, user_msg):
55
+ """Mistral instruct format: <s>[INST] ... [/INST]"""
56
+ return f"<s>[INST] {system}\n\n{user_msg} [/INST]"
57
+
58
+
59
  def solve_math(image_input, text_input, grade_level, user_token):
 
60
  token = user_token.strip() if user_token and user_token.strip() else SPACE_TOKEN
61
 
62
  if not token:
63
  yield (
64
+ "πŸ”‘ **A HuggingFace token is required.**\n\n"
65
  "It's free and takes 30 seconds:\n"
66
  "1. Go to [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)\n"
67
+ "2. Click **New token** β†’ **Read** access β†’ Copy\n"
68
+ "3. Paste it in the **HuggingFace Token** box\n\n"
69
+ "Your token is never stored β€” session only."
70
  )
71
  return
72
 
 
81
 
82
  grade_note = f"Grade level: {grade_level}."
83
 
 
84
  if has_image and has_text:
85
+ problem_text = text_input.strip()
 
 
 
 
86
  elif has_image:
87
  problem_text = (
88
+ "There is a math problem in the uploaded image. "
89
+ "Please solve it step by step as a math tutor. "
90
+ "If you cannot determine the exact problem, explain the general method for the type of problem shown."
91
  )
92
  else:
93
  problem_text = text_input.strip()
94
 
95
+ user_msg = f"{grade_note}\n\nProblem: {problem_text}\n\nPlease teach me how to solve this step by step."
96
+ prompt = build_mistral_prompt(SYSTEM_PROMPT, user_msg)
97
 
98
  yield "⚑ Solving step by step..."
99
 
 
101
  client = InferenceClient(
102
  model=TEXT_MODEL,
103
  token=token,
 
104
  )
105
 
106
+ output = ""
107
+ # Use text_generation with streaming β€” works on free HF inference
108
+ for chunk in client.text_generation(
109
+ prompt,
110
+ max_new_tokens=1000,
 
111
  temperature=0.3,
112
+ do_sample=True,
113
  stream=True,
114
+ stop_sequences=["</s>", "[INST]"],
115
+ ):
116
+ output += chunk
117
+ yield output
 
 
 
 
118
 
119
  if not output:
120
  yield "⚠️ No response received. Please try again in a moment."
 
123
  err = str(e)
124
  if "401" in err:
125
  yield (
126
+ "❌ **Invalid token.** Please check your HuggingFace token.\n\n"
127
+ "Get one free at [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)"
128
  )
129
  elif "503" in err or "loading" in err.lower():
130
  yield "⏳ **Model is warming up.** Please wait ~30 seconds and try again."
 
144
  --accent: #58a6ff;
145
  --accent2: #bc8cff;
146
  --green: #3fb950;
 
147
  --text: #e6edf3;
148
  --muted: #7d8590;
149
  --border: #30363d;
 
197
  ]
198
 
199
  EXAMPLES = [
200
+ [None, "What is 24 Γ· 6 + 3 Γ— 2?", "Grade 3–4 (Multiplication, Division, Fractions Intro)", ""],
201
+ [None, "If I have 3/4 of a pizza and eat 1/3, how much is left?", "Grade 5–6 (Fractions, Decimals, Geometry Basics)", ""],
202
+ [None, "Solve for x: 2x + 5 = 17", "Grade 7–8 (Algebra, Ratios, Percentages)", ""],
203
+ [None, "Find the area of a circle with radius 7 cm", "Grade 9–10 (Algebra II, Geometry, Trigonometry)", ""],
204
+ [None, "Differentiate f(x) = 3xΒ³ βˆ’ 2x + 7", "Grade 11–12 (Pre-Calculus, Statistics, Calculus)", ""],
205
  ]
206
 
 
207
  OWNER_TOKEN_SET = bool(SPACE_TOKEN)
208
 
209
  with gr.Blocks(css=CSS, title="Interactive Math Tutor") as demo:
 
226
  with gr.Row(equal_height=False):
227
  with gr.Column(scale=4, min_width=300):
228
 
 
229
  if not OWNER_TOKEN_SET:
230
  gr.HTML('<div class="panel-label">πŸ”‘ HuggingFace Token (free)</div>')
231
  user_token = gr.Textbox(
232
+ label="", placeholder="hf_xxxxxxxxxxxxxxxxxxxx",
233
+ type="password", lines=1, elem_classes=["token-box"],
 
 
 
234
  )
235
  gr.HTML("""
236
  <div class="token-info">
237
  <strong>Get your free token in 30 seconds:</strong><br>
238
  1. Go to <a href="https://huggingface.co/settings/tokens" target="_blank">huggingface.co/settings/tokens</a><br>
239
  2. Click <strong>New token</strong> β†’ <strong>Read</strong> access β†’ Copy<br>
240
+ 3. Paste above Β· Never stored, session-only
241
  </div>
242
  """)
243
  else:
244
  user_token = gr.Textbox(value="", visible=False)
245
+ gr.HTML('<div class="info-box"><strong>βœ… Ready to use β€” no setup needed!</strong></div>')
 
 
 
 
 
246
 
247
  gr.HTML('<div class="panel-label" style="margin-top:16px">πŸ“Ž Upload Worksheet (optional)</div>')
248
  image_input = gr.Image(type="pil", label="", height=180)
 
263
 
264
  gr.HTML('<div class="panel-label" style="margin-top:16px">πŸ’‘ Try an example</div>')
265
  gr.Examples(
266
+ examples=EXAMPLES,
267
  inputs=[image_input, text_input, grade_dropdown, user_token],
268
  label=""
269
  )