|
|
import gradio as gr |
|
|
import os |
|
|
from huggingface_hub import InferenceClient |
|
|
from datasets import load_dataset |
|
|
import random |
|
|
import re |
|
|
|
|
|
|
|
|
fw = load_dataset("HuggingFaceFW/fineweb-edu", name="sample-10BT", split="train", streaming=True) |
|
|
ds = load_dataset("HuggingFaceH4/ultrachat_200k", streaming=True) |
|
|
|
|
|
def load_sample_problems(): |
|
|
"""Load sample problems from math datasets""" |
|
|
try: |
|
|
gsm8k = load_dataset("openai/gsm8k", "main", streaming=True) |
|
|
samples = [] |
|
|
for i, item in enumerate(gsm8k["train"]): |
|
|
samples.append(item["question"]) |
|
|
if i >= 50: |
|
|
break |
|
|
return samples |
|
|
except: |
|
|
return [ |
|
|
"What is the derivative of f(x) = 3x² + 2x - 1?", |
|
|
"A triangle has sides of length 5, 12, and 13. What is its area?", |
|
|
"If log₂(x) + log₂(x+6) = 4, find the value of x.", |
|
|
"Find the limit: lim(x→0) (sin(x)/x)", |
|
|
"Solve the system: x + 2y = 7, 3x - y = 4" |
|
|
] |
|
|
|
|
|
math_samples = load_sample_problems() |
|
|
|
|
|
def create_math_system_message(): |
|
|
"""Create specialized system prompt for mathematics""" |
|
|
return """You are Mathetics AI, an advanced mathematics tutor and problem solver. |
|
|
|
|
|
🧮 **Your Expertise:** |
|
|
- Step-by-step problem solving with clear explanations |
|
|
- Multiple solution approaches when applicable |
|
|
- Proper mathematical notation and terminology |
|
|
- Verification of answers through different methods |
|
|
|
|
|
📐 **Problem Domains:** |
|
|
- Arithmetic, Algebra, and Number Theory |
|
|
- Geometry, Trigonometry, and Coordinate Geometry |
|
|
- Calculus (Limits, Derivatives, Integrals) |
|
|
- Statistics, Probability, and Data Analysis |
|
|
- Competition Mathematics (AMC, AIME level) |
|
|
|
|
|
💡 **Teaching Style:** |
|
|
1. **Understand the Problem** - Identify what's being asked |
|
|
2. **Plan the Solution** - Choose the appropriate method |
|
|
3. **Execute Step-by-Step** - Show all work clearly |
|
|
4. **Verify the Answer** - Check if the result makes sense |
|
|
5. **Alternative Methods** - Mention other possible approaches |
|
|
|
|
|
Always be precise, educational, and encourage mathematical thinking.""" |
|
|
|
|
|
def render_latex(text): |
|
|
"""Format math expressions for LaTeX rendering""" |
|
|
if not text: |
|
|
return text |
|
|
|
|
|
text = re.sub(r'\b([a-zA-Z]+)\^?(\d*)\b', r'$\1^{\2}$', text) |
|
|
|
|
|
text = re.sub(r'([a-zA-Z]+)\(([^)]+)\)', r'$\1(\2)$', text) |
|
|
|
|
|
text = re.sub(r'lim\(([a-z])→([0-9.]+)\)', r'$\lim_{ \1 \to \2}$', text) |
|
|
return text |
|
|
|
|
|
def respond(message, history, system_message, max_tokens, temperature, top_p): |
|
|
|
|
|
yield "🤔 Thinking for the suitable answer..." |
|
|
|
|
|
|
|
|
client = InferenceClient(model="Qwen/Qwen2.5-Math-7B-Instruct") |
|
|
|
|
|
|
|
|
messages = [{"role": "system", "content": system_message}] |
|
|
messages.extend(history) |
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
|
|
response = "" |
|
|
max_tokens = max(max_tokens, 1536) |
|
|
|
|
|
try: |
|
|
for message_chunk in client.chat_completion( |
|
|
messages, |
|
|
max_tokens=max_tokens, |
|
|
stream=True, |
|
|
temperature=temperature, |
|
|
top_p=top_p, |
|
|
): |
|
|
choices = message_chunk.choices |
|
|
if len(choices) and choices[0].delta.content: |
|
|
token = choices[0].delta.content |
|
|
response += token |
|
|
|
|
|
if "```" in response or len(response) > 500: |
|
|
formatted = render_latex(response) |
|
|
yield formatted |
|
|
else: |
|
|
yield response |
|
|
|
|
|
|
|
|
final_formatted = render_latex(response) |
|
|
yield final_formatted |
|
|
|
|
|
except Exception as e: |
|
|
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" |
|
|
yield error_msg |
|
|
|
|
|
def get_random_sample(): |
|
|
"""Get a random sample problem""" |
|
|
if math_samples: |
|
|
return random.choice(math_samples) |
|
|
return "Solve for x: 2x² + 5x - 3 = 0" |
|
|
|
|
|
def insert_sample_to_chat(difficulty): |
|
|
"""Insert random sample into chat input""" |
|
|
sample = get_random_sample() |
|
|
return "", [None, sample] |
|
|
|
|
|
def show_help(): |
|
|
return """**Math Help Tips:** |
|
|
|
|
|
1. **Be Specific**: "Find the derivative of..." instead of "Help with calculus" |
|
|
2. **Show Your Work**: "I got x=5, is this correct?" |
|
|
3. **Ask for Steps**: "Show me step-by-step how to solve..." |
|
|
4. **Request Verification**: "Check my solution to this problem" |
|
|
5. **Alternative Methods**: "What's another way to solve this?" |
|
|
""" |
|
|
|
|
|
|
|
|
chatbot = gr.ChatInterface( |
|
|
respond, |
|
|
type="messages", |
|
|
title="🧮 **Mathetics AI** - Advanced Mathematics Solver", |
|
|
description=""" |
|
|
**Powered by Qwen 2.5-Math** | **Specialized for Mathematical Problem Solving** |
|
|
|
|
|
✨ **Capabilities**: Algebra • Geometry • Calculus • Statistics • Competition Math |
|
|
📚 **Features**: Step-by-step solutions • Multiple approaches • Clear explanations |
|
|
""", |
|
|
additional_inputs=[ |
|
|
gr.Textbox( |
|
|
value=create_math_system_message(), |
|
|
label="🧠 System Message (Math Tutor Personality)", |
|
|
lines=3, |
|
|
max_lines=10 |
|
|
), |
|
|
gr.Slider(minimum=256, maximum=2048, value=768, step=64, label="📝 Max Tokens"), |
|
|
gr.Slider(minimum=0.1, maximum=1.0, value=0.3, step=0.1, label="🎯 Temperature"), |
|
|
gr.Slider(minimum=0.1, maximum=1.0, value=0.85, step=0.05, label="🔍 Top-p"), |
|
|
], |
|
|
examples=[ |
|
|
["What is the derivative of f(x) = 3x² + 2x - 1?"], |
|
|
["A triangle has sides of length 5, 12, and 13. What is its area?"], |
|
|
["Find the limit: lim(x→0) (sin(x)/x)"], |
|
|
["Solve the system: x + 2y = 7, 3x - y = 4"], |
|
|
["What is the integral of ∫(2x³ - 5x + 3)dx?"] |
|
|
], |
|
|
cache_examples=False, |
|
|
concurrency_limit=10, |
|
|
) |
|
|
|
|
|
|
|
|
with gr.Blocks( |
|
|
title="🧮 Mathetics AI", |
|
|
theme=gr.themes.Soft(), |
|
|
css=""" |
|
|
.math-highlight { background-color: #f0f8ff; padding: 10px; border-left: 4px solid #4CAF50; margin: 10px 0; border-radius: 5px; } |
|
|
.difficulty-selector { background-color: #fff3e0; padding: 15px; border-radius: 10px; margin: 10px 0; } |
|
|
.markdown math { font-size: 1.1em; } |
|
|
""" |
|
|
) as demo: |
|
|
|
|
|
gr.Markdown("# 🧮 **Mathematics AI** - Advanced Mathematics Solver\n**Your Personal AI Math Tutor**") |
|
|
|
|
|
with gr.Row(): |
|
|
with gr.Column(scale=4): |
|
|
chatbot.render() |
|
|
|
|
|
with gr.Column(scale=1): |
|
|
with gr.Accordion("🎲 **Quick Actions**", open=True): |
|
|
difficulty_preset = gr.Dropdown( |
|
|
choices=["Elementary", "High School", "College", "Competition"], |
|
|
value="High School", |
|
|
label="🎯 Problem Difficulty", |
|
|
elem_classes=["difficulty-selector"] |
|
|
) |
|
|
|
|
|
sample_btn = gr.Button("🎯 Get Sample Problem", variant="secondary") |
|
|
help_btn = gr.Button("❓ Math Help Tips", variant="secondary") |
|
|
|
|
|
gr.Markdown("### 🔧 **Quick Tools**") |
|
|
gr.Markdown("- **Algebra**: Equations, inequalities, factoring\n- **Geometry**: Area, volume, trigonometry\n- **Calculus**: Derivatives, integrals, limits\n- **Statistics**: Probability, distributions\n- **Number Theory**: Prime factorization, GCD/LCM") |
|
|
|
|
|
gr.Markdown(""" |
|
|
--- |
|
|
**🔧 Technical Details:** Qwen/Qwen2.5-Math-7B-Instruct | Real-time streaming responses |
|
|
|
|
|
**💡 Usage Tips:** Be specific • Request step-by-step • Ask for verification |
|
|
""") |
|
|
|
|
|
|
|
|
sample_btn.click( |
|
|
insert_sample_to_chat, |
|
|
inputs=[difficulty_preset], |
|
|
outputs=[chatbot] |
|
|
) |
|
|
|
|
|
help_btn.click( |
|
|
show_help, |
|
|
outputs=gr.Markdown() |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |