| import gradio as gr |
| import os |
| from huggingface_hub import InferenceClient |
| from datasets import load_dataset |
| import random |
|
|
|
|
| |
| 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 respond( |
| message, |
| history: list[dict[str, str]], |
| system_message, |
| max_tokens, |
| temperature, |
| top_p, |
| |
| ): |
| |
| yield "🤔 Thinking for the suitable answer..." |
| |
| """ |
| Enhanced response function for mathematical problem solving |
| """ |
| |
| client = InferenceClient( |
| |
| model="Qwen/Qwen2.5-Math-72B" |
| ) |
|
|
| |
| messages = [{"role": "system", "content": system_message}] |
| messages.extend(history) |
| messages.append({"role": "user", "content": message}) |
|
|
| response = "" |
|
|
| 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 |
| token = "" |
| if len(choices) and choices[0].delta.content: |
| token = choices[0].delta.content |
|
|
| response += token |
| yield response |
| |
| 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 set_difficulty_preset(difficulty): |
| """Set temperature and other params based on difficulty""" |
| presets = { |
| "Elementary": (0.2, 0.8, 512), |
| "High School": (0.3, 0.85, 768), |
| "College": (0.4, 0.9, 1024), |
| "Competition": (0.3, 0.8, 1536) |
| } |
| return presets.get(difficulty, (0.3, 0.85, 768)) |
|
|
| |
| 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 (Solution Length)" |
| ), |
| gr.Slider( |
| minimum=0.1, |
| maximum=1.0, |
| value=0.3, |
| step=0.1, |
| label="🎯 Temperature (Creativity vs Precision)" |
| ), |
| gr.Slider( |
| minimum=0.1, |
| maximum=1.0, |
| value=0.85, |
| step=0.05, |
| label="🔍 Top-p (Response Diversity)", |
| ), |
| ], |
| 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?"], |
| ["If log₂(x) + log₂(x+6) = 4, find the value of x."], |
| ["A bag contains 5 red balls and 7 blue balls. What's the probability of drawing 2 red balls without replacement?"], |
| ["Find the limit: lim(x→0) (sin(x)/x)"], |
| ["Solve the system of equations: x + 2y = 7 and 3x - y = 4"], |
| ["What is the integral of ∫(2x³ - 5x + 3)dx?"], |
| ["In a right triangle, if one angle is 30° and the hypotenuse is 10, find the lengths of the other two sides."] |
| ], |
| 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; |
| } |
| """ |
| ) as demo: |
| |
| gr.Markdown(""" |
| # 🧮 **Mathetics AI** - Advanced Mathematics Solver |
| |
| **Your Personal AI Math Tutor** | Specialized in step-by-step problem solving across all mathematical domains |
| """) |
|
|
|
|
| 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", size="sm") |
| help_btn = gr.Button("❓ Math Help Tips", variant="secondary", size="sm") |
| |
| |
| gr.Markdown("### 🔧 **Quick Tools**") |
| gr.Markdown(""" |
| - **Algebra**: Equations, inequalities, factoring |
| - **Geometry**: Area, volume, trigonometry |
| - **Calculus**: Derivatives, integrals, limits |
| - **Statistics**: Probability, distributions |
| - **Number Theory**: Prime factorization, GCD/LCM |
| """) |
| |
| |
| gr.Markdown(""" |
| --- |
| **🔧 Technical Details:** |
| - **Model**: Qwen/Qwen2.5-Math-7B-Instruct (Specialized for Mathematics) |
| - **Authentication**: Automatic via Hugging Face OAuth |
| - **Features**: Real-time streaming responses, step-by-step solutions |
| |
| **💡 Usage Tips:** |
| - Be specific about what you want to find or solve |
| - Mention if you want step-by-step solutions |
| - Ask for alternative solution methods |
| - Request verification of your own solutions |
| """) |
| |
| |
| |
| def insert_sample(difficulty): |
| sample = get_random_sample() |
| return 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?" |
| """ |
| |
| |
| sample_btn.click( |
| lambda x: get_random_sample(), |
| inputs=[difficulty_preset], |
| outputs=[] |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch() |