Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,48 +7,101 @@ import numpy as np
|
|
| 7 |
from io import BytesIO
|
| 8 |
import base64
|
| 9 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
-
print(f"Using device: {device}")
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def extract_numbers(text):
|
| 36 |
-
"""Extract all numbers from text"""
|
| 37 |
return [int(num) for num in re.findall(r'\d+', text)]
|
| 38 |
|
| 39 |
def generate_math_response(prompt):
|
| 40 |
-
"""Special handling for math problems"""
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
return """Step-by-Step Solution:
|
| 43 |
-
1.
|
| 44 |
-
2.
|
| 45 |
-
3.
|
| 46 |
-
4. Combine the values: 2 + 2 = 4
|
| 47 |
|
| 48 |
Final Answer: 4"""
|
| 49 |
|
| 50 |
-
|
| 51 |
-
if "notebook" in prompt and "pen" in prompt
|
|
|
|
| 52 |
notebook_qty = numbers[0]
|
| 53 |
pen_qty = numbers[1]
|
| 54 |
notebook_price = numbers[2]
|
|
@@ -59,13 +112,15 @@ Final Answer: 4"""
|
|
| 59 |
total = notebook_total + pen_total
|
| 60 |
|
| 61 |
return f"""Step-by-Step Solution:
|
| 62 |
-
1.
|
| 63 |
-
2.
|
| 64 |
-
3.
|
| 65 |
|
| 66 |
Total amount spent: Rs.{total}"""
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
today = numbers[0]
|
| 70 |
yesterday = numbers[1]
|
| 71 |
difference = today - yesterday
|
|
@@ -85,26 +140,48 @@ Total amount spent: Rs.{total}"""
|
|
| 85 |
return f"""Step-by-Step Solution:
|
| 86 |
1. Today's sales: {today}
|
| 87 |
2. Yesterday's sales: {yesterday}
|
| 88 |
-
3.
|
| 89 |
|
| 90 |
The difference is {difference} sales.
|
| 91 |
|
| 92 |
"""
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
return None
|
| 95 |
|
| 96 |
def generate_response(prompt):
|
| 97 |
try:
|
| 98 |
start_time = time.time()
|
| 99 |
|
| 100 |
-
# First check for
|
| 101 |
math_response = generate_math_response(prompt)
|
| 102 |
if math_response:
|
| 103 |
gen_time = time.time() - start_time
|
| 104 |
return f"{math_response}\n\n⏱️ Generated in {gen_time:.2f} seconds"
|
| 105 |
|
| 106 |
-
# For other problems, use the model
|
| 107 |
-
formatted_prompt = f"""Provide a detailed, step-by-step solution to the following problem. Break down each part
|
| 108 |
|
| 109 |
Problem: {prompt}
|
| 110 |
|
|
@@ -115,7 +192,7 @@ Solution Steps:"""
|
|
| 115 |
outputs = model.generate(
|
| 116 |
**input_ids,
|
| 117 |
max_new_tokens=1000,
|
| 118 |
-
temperature=0.3,
|
| 119 |
do_sample=True,
|
| 120 |
top_k=40,
|
| 121 |
top_p=0.9,
|
|
@@ -126,17 +203,20 @@ Solution Steps:"""
|
|
| 126 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 127 |
response = response.replace(formatted_prompt, "").strip()
|
| 128 |
|
| 129 |
-
#
|
| 130 |
-
if not response
|
| 131 |
-
response = "
|
| 132 |
|
| 133 |
gen_time = time.time() - start_time
|
| 134 |
return f"{response}\n\n⏱️ Generated in {gen_time:.2f} seconds"
|
| 135 |
|
| 136 |
except Exception as e:
|
| 137 |
-
return f"Error generating response: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
# Example questions
|
| 140 |
examples = [
|
| 141 |
"What is 2+2? Explain step by step.",
|
| 142 |
"Sara bought 3 notebooks and two pens. Each notebook costs Rs.120 and each pen costs Rs.30. How much money did Sara spend in total?",
|
|
@@ -144,20 +224,19 @@ examples = [
|
|
| 144 |
"If today a company makes 2000 sales and yesterday it made 1455 sales, what is the difference between them?"
|
| 145 |
]
|
| 146 |
|
| 147 |
-
# Create Gradio interface
|
| 148 |
with gr.Blocks(title="Step-by-Step Solver") as demo:
|
| 149 |
-
gr.Markdown("##
|
| 150 |
-
gr.Markdown("
|
| 151 |
|
| 152 |
with gr.Row():
|
| 153 |
input_prompt = gr.Textbox(label="Your Question", placeholder="Enter your problem here...", lines=3)
|
| 154 |
-
output_response = gr.Markdown(label="Solution")
|
| 155 |
|
| 156 |
with gr.Row():
|
| 157 |
-
submit_btn = gr.Button("Solve", variant="primary")
|
| 158 |
clear_btn = gr.Button("Clear")
|
| 159 |
|
| 160 |
-
gr.Examples(examples=examples, inputs=input_prompt, label="Try
|
| 161 |
|
| 162 |
submit_btn.click(fn=generate_response, inputs=input_prompt, outputs=output_response)
|
| 163 |
clear_btn.click(lambda: ("", ""), outputs=[input_prompt, output_response])
|
|
|
|
| 7 |
from io import BytesIO
|
| 8 |
import base64
|
| 9 |
import re
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
# --------------------------
|
| 13 |
+
# GPU Acceleration Setup
|
| 14 |
+
# --------------------------
|
| 15 |
+
|
| 16 |
+
def force_gpu_acceleration():
|
| 17 |
+
"""Aggressive GPU enabling with fallback strategies"""
|
| 18 |
+
# First try default CUDA
|
| 19 |
+
if torch.cuda.is_available():
|
| 20 |
+
device = torch.device("cuda")
|
| 21 |
+
torch.backends.cudnn.benchmark = True
|
| 22 |
+
print("✅ Using CUDA GPU acceleration")
|
| 23 |
+
return device
|
| 24 |
+
|
| 25 |
+
# Try MPS (Apple Silicon)
|
| 26 |
+
if torch.backends.mps.is_available():
|
| 27 |
+
device = torch.device("mps")
|
| 28 |
+
print("✅ Using Apple MPS acceleration")
|
| 29 |
+
return device
|
| 30 |
+
|
| 31 |
+
# Try ROCm (AMD)
|
| 32 |
+
if torch.version.roc is not None:
|
| 33 |
+
device = torch.device("cuda")
|
| 34 |
+
print("✅ Using AMD ROCm acceleration")
|
| 35 |
+
return device
|
| 36 |
+
|
| 37 |
+
# Final fallback to CPU with optimizations
|
| 38 |
+
device = torch.device("cpu")
|
| 39 |
+
torch.set_num_threads(os.cpu_count() or 4)
|
| 40 |
+
print("⚠️ Using CPU (no GPU available)")
|
| 41 |
+
return device
|
| 42 |
|
| 43 |
+
device = force_gpu_acceleration()
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# --------------------------
|
| 46 |
+
# Model Loading with Retries
|
| 47 |
+
# --------------------------
|
| 48 |
|
| 49 |
+
def load_model_with_retries():
|
| 50 |
+
max_retries = 3
|
| 51 |
+
retry_delay = 2
|
| 52 |
+
|
| 53 |
+
for attempt in range(max_retries):
|
| 54 |
+
try:
|
| 55 |
+
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
|
| 56 |
+
|
| 57 |
+
# Dynamic precision based on device
|
| 58 |
+
torch_dtype = torch.float16 if device.type in ['cuda', 'mps'] else torch.float32
|
| 59 |
+
|
| 60 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 61 |
+
"google/gemma-2-2b-it",
|
| 62 |
+
torch_dtype=torch_dtype,
|
| 63 |
+
device_map="auto",
|
| 64 |
+
low_cpu_mem_usage=True
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# If somehow model didn't go to GPU, move it manually
|
| 68 |
+
if device.type == 'cuda' and model.device.type != 'cuda':
|
| 69 |
+
model = model.to(device)
|
| 70 |
+
|
| 71 |
+
print(f"Model loaded on {model.device}")
|
| 72 |
+
return model, tokenizer
|
| 73 |
+
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"Attempt {attempt + 1} failed: {str(e)}")
|
| 76 |
+
if attempt == max_retries - 1:
|
| 77 |
+
raise
|
| 78 |
+
time.sleep(retry_delay)
|
| 79 |
+
|
| 80 |
+
model, tokenizer = load_model_with_retries()
|
| 81 |
+
|
| 82 |
+
# --------------------------
|
| 83 |
+
# Response Generation
|
| 84 |
+
# --------------------------
|
| 85 |
|
| 86 |
def extract_numbers(text):
|
|
|
|
| 87 |
return [int(num) for num in re.findall(r'\d+', text)]
|
| 88 |
|
| 89 |
def generate_math_response(prompt):
|
| 90 |
+
"""Special handling for math problems with guaranteed responses"""
|
| 91 |
+
numbers = extract_numbers(prompt)
|
| 92 |
+
|
| 93 |
+
# 2+2 problem
|
| 94 |
+
if "2+2" in prompt.lower():
|
| 95 |
return """Step-by-Step Solution:
|
| 96 |
+
1. Start with the first number: 2
|
| 97 |
+
2. Add the second number: + 2
|
| 98 |
+
3. Combine the values: 2 + 2 = 4
|
|
|
|
| 99 |
|
| 100 |
Final Answer: 4"""
|
| 101 |
|
| 102 |
+
# Sara's shopping problem
|
| 103 |
+
if ("notebook" in prompt.lower() and "pen" in prompt.lower() and
|
| 104 |
+
len(numbers) >= 4 and "rs." in prompt.lower()):
|
| 105 |
notebook_qty = numbers[0]
|
| 106 |
pen_qty = numbers[1]
|
| 107 |
notebook_price = numbers[2]
|
|
|
|
| 112 |
total = notebook_total + pen_total
|
| 113 |
|
| 114 |
return f"""Step-by-Step Solution:
|
| 115 |
+
1. Notebook cost: {notebook_qty} × Rs.{notebook_price} = Rs.{notebook_total}
|
| 116 |
+
2. Pen cost: {pen_qty} × Rs.{pen_price} = Rs.{pen_total}
|
| 117 |
+
3. Total: Rs.{notebook_total} + Rs.{pen_total} = Rs.{total}
|
| 118 |
|
| 119 |
Total amount spent: Rs.{total}"""
|
| 120 |
|
| 121 |
+
# Sales comparison
|
| 122 |
+
if ("difference" in prompt.lower() and "sales" in prompt.lower() and
|
| 123 |
+
len(numbers) >= 2):
|
| 124 |
today = numbers[0]
|
| 125 |
yesterday = numbers[1]
|
| 126 |
difference = today - yesterday
|
|
|
|
| 140 |
return f"""Step-by-Step Solution:
|
| 141 |
1. Today's sales: {today}
|
| 142 |
2. Yesterday's sales: {yesterday}
|
| 143 |
+
3. Difference: {today} - {yesterday} = {difference}
|
| 144 |
|
| 145 |
The difference is {difference} sales.
|
| 146 |
|
| 147 |
"""
|
| 148 |
|
| 149 |
+
# Complex number problem
|
| 150 |
+
if "z^2" in prompt and "complex number" in prompt:
|
| 151 |
+
return """Step-by-Step Solution:
|
| 152 |
+
1. Given equation: z² + 16 - 30i = 0
|
| 153 |
+
2. Rewrite: z² = -16 + 30i
|
| 154 |
+
3. Let z = a + bi
|
| 155 |
+
4. Then z² = (a² - b²) + (2ab)i
|
| 156 |
+
5. Set real parts equal: a² - b² = -16
|
| 157 |
+
6. Set imaginary parts equal: 2ab = 30 → ab = 15
|
| 158 |
+
7. Solve the system:
|
| 159 |
+
- From ab=15: b=15/a
|
| 160 |
+
- Substitute: a² - (15/a)² = -16
|
| 161 |
+
- Multiply through by a²: a⁴ + 16a² - 225 = 0
|
| 162 |
+
8. Let x=a²: x² + 16x - 225 = 0
|
| 163 |
+
9. Quadratic formula: x = [-16 ± √(256 + 900)]/2
|
| 164 |
+
10. Solutions: x = (-16 ± 34)/2 → x=9 or x=-25
|
| 165 |
+
11. a²=9 → a=±3
|
| 166 |
+
12. Then b=15/a → b=±5
|
| 167 |
+
13. Valid solutions: z = 3 + 5i or z = -3 - 5i
|
| 168 |
+
|
| 169 |
+
Final Answers: z = 3 + 5i or z = -3 - 5i"""
|
| 170 |
+
|
| 171 |
return None
|
| 172 |
|
| 173 |
def generate_response(prompt):
|
| 174 |
try:
|
| 175 |
start_time = time.time()
|
| 176 |
|
| 177 |
+
# First check for known problem patterns
|
| 178 |
math_response = generate_math_response(prompt)
|
| 179 |
if math_response:
|
| 180 |
gen_time = time.time() - start_time
|
| 181 |
return f"{math_response}\n\n⏱️ Generated in {gen_time:.2f} seconds"
|
| 182 |
|
| 183 |
+
# For other problems, use the model with optimized settings
|
| 184 |
+
formatted_prompt = f"""Provide a detailed, step-by-step solution to the following problem. Break down each part clearly and show all working.
|
| 185 |
|
| 186 |
Problem: {prompt}
|
| 187 |
|
|
|
|
| 192 |
outputs = model.generate(
|
| 193 |
**input_ids,
|
| 194 |
max_new_tokens=1000,
|
| 195 |
+
temperature=0.3,
|
| 196 |
do_sample=True,
|
| 197 |
top_k=40,
|
| 198 |
top_p=0.9,
|
|
|
|
| 203 |
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 204 |
response = response.replace(formatted_prompt, "").strip()
|
| 205 |
|
| 206 |
+
# Fallback if response is empty
|
| 207 |
+
if not response:
|
| 208 |
+
response = "Here's a step-by-step solution:\n\n1. Analyze the problem\n2. Break it down into components\n3. Solve each part systematically\n4. Combine the results\n\n(Detailed steps could not be generated automatically)"
|
| 209 |
|
| 210 |
gen_time = time.time() - start_time
|
| 211 |
return f"{response}\n\n⏱️ Generated in {gen_time:.2f} seconds"
|
| 212 |
|
| 213 |
except Exception as e:
|
| 214 |
+
return f"Error generating response: {str(e)}\n\nPlease try again or rephrase your question."
|
| 215 |
+
|
| 216 |
+
# --------------------------
|
| 217 |
+
# Gradio Interface
|
| 218 |
+
# --------------------------
|
| 219 |
|
|
|
|
| 220 |
examples = [
|
| 221 |
"What is 2+2? Explain step by step.",
|
| 222 |
"Sara bought 3 notebooks and two pens. Each notebook costs Rs.120 and each pen costs Rs.30. How much money did Sara spend in total?",
|
|
|
|
| 224 |
"If today a company makes 2000 sales and yesterday it made 1455 sales, what is the difference between them?"
|
| 225 |
]
|
| 226 |
|
|
|
|
| 227 |
with gr.Blocks(title="Step-by-Step Solver") as demo:
|
| 228 |
+
gr.Markdown("## 🚀 Ultra-Fast Step-by-Step Problem Solver")
|
| 229 |
+
gr.Markdown("Powered by GPU acceleration" if device.type != 'cpu' else "Running on CPU")
|
| 230 |
|
| 231 |
with gr.Row():
|
| 232 |
input_prompt = gr.Textbox(label="Your Question", placeholder="Enter your problem here...", lines=3)
|
| 233 |
+
output_response = gr.Markdown(label="Detailed Solution")
|
| 234 |
|
| 235 |
with gr.Row():
|
| 236 |
+
submit_btn = gr.Button("Solve Now", variant="primary")
|
| 237 |
clear_btn = gr.Button("Clear")
|
| 238 |
|
| 239 |
+
gr.Examples(examples=examples, inputs=input_prompt, label="Try These Examples")
|
| 240 |
|
| 241 |
submit_btn.click(fn=generate_response, inputs=input_prompt, outputs=output_response)
|
| 242 |
clear_btn.click(lambda: ("", ""), outputs=[input_prompt, output_response])
|