Spaces:
Runtime error
Runtime error
Upload 3 files
Browse filesFiles changed (3)
- README.md+44-12
- app.py+64-310
- requirements.txtAdded+3
123456789101112---title: Mathemoji: 🌍colorFrom: indigocolorTo: greensdk: gradiosdk_version: 5.29.0app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526272829303132333435363738394041424344---title: Mathematics Question Generatoremoji: 🧮colorFrom: bluecolorTo: greensdk: gradiosdk_version: 4.16.0app_file: app.pypinned: false---# Mathematics Question GeneratorThis application generates customized mathematics questions on any topic you specify. Simply enter a mathematics chapter or concept you want to practice, and the AI will create questions with step-by-step solutions.## Features- Generate mathematics questions on any topic- Choose the number of questions (1-10)- Select difficulty level (elementary to advanced)- View detailed step-by-step solutions## How to Use1. Enter a mathematics topic (e.g., "Linear Algebra: Eigenvalues", "Calculus: Integration")2. Adjust the number of questions and difficulty level as needed3. Click "Generate Questions"4. Study the generated questions and their solutions## Setup RequirementsThis application requires a Hugging Face API token with access to the DeepSeek models. To set up your token:1. Generate a Hugging Face API token with read access from [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)2. Add this token to your Space as a secret with the key `HUGGINGFACE_TOKEN`- Go to your Space settings- Click on "Secrets"- Add a new secret with name `HUGGINGFACE_TOKEN` and your token as the value## AboutThis application uses DeepSeek's mathematics-focused language model to generate high-quality mathematics questions tailored to your learning needs.Created by Kamagelo Mosia
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345import gradio as grimport osfrom huggingface_hub import InferenceClient# Define calculus topics and subtopicsCALCULUS_TOPICS = {"Limits": ["Finding limits algebraically","One-sided limits","Limits at infinity","Limits that don't exist","Epsilon-delta proofs"],"Derivatives": ["Basic differentiation rules","Power rule","Product rule","Quotient rule","Chain rule","Implicit differentiation","Logarithmic differentiation","Higher-order derivatives"],"Applications of Derivatives": ["Related rates","Mean value theorem","Critical points","Curve sketching","Optimization problems","Linear approximation","Newton's method"],"Integrals": ["Indefinite integrals","Basic integration rules","Substitution method","Integration by parts","Partial fractions","Trigonometric integrals","Improper integrals"],"Applications of Integrals": ["Area between curves","Volume of solids of revolution","Arc length","Surface area","Work and energy problems","Center of mass"],"Sequences and Series": ["Convergence tests","Power series","Taylor and Maclaurin series","Radius of convergence"],"Multivariable Calculus": ["Partial derivatives","Directional derivatives","Gradient","Multiple integrals","Line integrals","Surface integrals"],"Differential Equations": ["First-order differential equations","Separable equations","Second-order differential equations","Systems of differential equations"]}# Initialize DeepSeek clientdef get_deepseek_client():# You'll need to set up your HuggingFace token as an environment variableclient = InferenceClient(model="deepseek-ai/deepseek-math-7b-instruct",token=os.getenv("HUGGINGFACE_TOKEN"))return clientdef generate_math_problems(topic, subtopic, difficulty, num_problems=3):"""Generate math problems with step-by-step solutions and explanations"""client = get_deepseek_client()# Create a specific prompt with the selected topic, subtopic and difficultyprompt = f"""Create {num_problems} {difficulty} difficulty calculus problems about '{subtopic}' (under the general topic of '{topic}').For each problem:1. Provide a clear and concise question.2. Provide a detailed step-by-step solution that a student can follow.3. Include explanations for each step.4. Mark the final answer clearly.Format:## Problem N:[Problem description]### Solution:[Step-by-step solution]### Explanation:[Explanation for the solution steps]### Answer:[Final answer]"""try:response = client.text_generation(prompt=prompt,max_new_tokens=2048,temperature=0.7,repetition_penalty=1.2,do_sample=True)return responseexcept Exception as e:return f"Error generating problems: {str(e)}"# Function to update subtopics based on main topic selectiondef update_subtopics(topic):return gr.Dropdown(choices=CALCULUS_TOPICS.get(topic, []), value=CALCULUS_TOPICS.get(topic, [""])[0])# Function to handle Gradio input and outputdef create_problems(topic, subtopic, difficulty, num_problems):if not topic or not subtopic:return "Please select both a topic and subtopic to generate problems."try:num_problems = int(num_problems)except ValueError:num_problems = 3 # Default to 3 problems if input is invalidreturn generate_math_problems(topic, subtopic, difficulty, num_problems)# Custom CSS with Google Fonts integrationcustom_css = """@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&family=JetBrains+Mono&display=swap');:root {--border-color: #e0e0e0;--bg-color: #ffffff;--text-color: #333333;--hover-color: #f0f0f0;}body, .gradio-container {font-family: 'Inter', sans-serif;color: var(--text-color);}.header {text-align: center;padding: 1.5rem 0;margin-bottom: 1rem;border-bottom: 1px solid var(--border-color);}.header h1 {font-weight: 500;margin-bottom: 0.5rem;}.header p {font-weight: 300;opacity: 0.8;}.card {border: 1px solid var(--border-color);border-radius: 4px;padding: 1.25rem;margin-bottom: 1rem;background-color: var(--bg-color);}.card h3 {font-weight: 500;margin-bottom: 1rem;font-size: 1.1rem;}button.generate-btn {width: 100%;background-color: var(--bg-color);border: 1px solid var(--border-color);border-radius: 4px;padding: 0.5rem;cursor: pointer;transition: background-color 0.2s ease;font-family: 'Inter', sans-serif;font-weight: 500;}button.generate-btn:hover {background-color: var(--hover-color);}.output-box {font-family: 'JetBrains Mono', monospace;border: 1px solid var(--border-color);border-radius: 4px;padding: 1rem;white-space: pre-wrap;line-height: 1.5;}.output-box h2 {font-weight: 500;margin-top: 1.5rem;padding-top: 1rem;border-top: 1px solid var(--border-color);}.output-box h2:first-child {margin-top: 0;padding-top: 0;border-top: none;}.output-box h3 {font-weight: 500;margin-top: 1rem;}/* Customizing Gradio elements */.gr-form, .gr-panel {border: none !important;box-shadow: none !important;}.gr-input, .gr-dropdown, .gr-radio {border: 1px solid var(--border-color) !important;border-radius: 4px !important;}.gr-input:focus, .gr-dropdown:focus {border-color: #999 !important;box-shadow: none !important;}.gr-slider-thumb {background-color: #999 !important;}.footer {text-align: center;font-size: 0.8rem;padding: 1rem 0;border-top: 1px solid var(--border-color);margin-top: 2rem;opacity: 0.7;}"""# Define the Gradio interface with custom stylingwith gr.Blocks(css=custom_css) as demo:# Headergr.HTML("""<div class="header"><h1>Calculus Problem Generator</h1><p>Generate problems with step-by-step solutions</p></div>""")# Main content areawith gr.Row():# Left panel - Problem configurationwith gr.Column(scale=1):with gr.Box(elem_classes="card"):gr.Markdown("### Configure Problems")# Topic selectiontopic_dropdown = gr.Dropdown(choices=list(CALCULUS_TOPICS.keys()),label="Topic",value=list(CALCULUS_TOPICS.keys())[0])# Subtopic selection (dynamically updated)subtopic_dropdown = gr.Dropdown(choices=CALCULUS_TOPICS[list(CALCULUS_TOPICS.keys())[0]],label="Subtopic",value=CALCULUS_TOPICS[list(CALCULUS_TOPICS.keys())[0]][0])# Update subtopics when topic changestopic_dropdown.change(fn=update_subtopics,inputs=topic_dropdown,outputs=subtopic_dropdown)# Difficulty selectiondifficulty_radio = gr.Radio(choices=["Basic", "Intermediate", "Advanced"],label="Difficulty",value="Intermediate")# Number of problemsnum_problems_slider = gr.Slider(minimum=1,maximum=5,value=3,step=1,label="Number of Problems")# Generate buttongenerate_button = gr.Button("Generate Problems", elem_classes="generate-btn")# Right panel - Output displaywith gr.Column(scale=2):with gr.Box(elem_classes="card"):gr.Markdown("### Problems & Solutions")# Output displayoutput_md = gr.Markdown(elem_classes="output-box",value="Select options and click 'Generate Problems' to start.")# Footergr.HTML("""<div class="footer"><p>Calculus Problem Generator | Educational Tool</p></div>""")# Connect the generate button to the functiongenerate_button.click(fn=create_problems,inputs=[topic_dropdown, subtopic_dropdown, difficulty_radio, num_problems_slider],outputs=output_md)# Launch the appif __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import gradio as grimport osimport requestsfrom huggingface_hub import InferenceClient# Initialize the Hugging Face Inference client for DeepSeekdef get_inference_client():api_token = os.environ.get("HUGGINGFACE_TOKEN")if not api_token:return Noneclient = InferenceClient(token=api_token)return clientdef generate_math_questions(chapter, num_questions=5, difficulty="medium"):"""Generate mathematics questions based on the provided chapter/topic"""client = get_inference_client()if not client:return "Error: Hugging Face token not configured. Please set the HUGGINGFACE_TOKEN in your space settings."prompt = f"""Generate {num_questions} {difficulty}-level mathematics questions about {chapter}.For each question:1. Write a clear, well-defined question2. Provide a step-by-step solution3. Include the final answerFormat your response as:## Question 1[Question text]### Solution[Step-by-step solution]### Answer[Final answer]## Question 2...and so on"""try:response = client.text_generation(prompt=prompt,model="deepseek-ai/deepseek-math-7b-instruct",max_new_tokens=2048,temperature=0.7,top_p=0.95,)return responseexcept Exception as e:return f"Error generating questions: {str(e)}\n\nPlease ensure your Hugging Face token has the necessary permissions."# Create the Gradio interfacewith gr.Blocks(title="Mathematics Question Generator") as demo:gr.Markdown("# 🧮 Mathematics Question Generator")gr.Markdown("Enter a mathematics chapter or topic to generate practice questions with solutions.")with gr.Row():with gr.Column(scale=3):chapter_input = gr.Textbox(label="Mathematics Topic/Chapter",placeholder="e.g., Calculus: Integration by Parts",info="Be specific for better results")with gr.Row():num_questions = gr.Slider(minimum=1,maximum=10,value=5,step=1,label="Number of Questions")difficulty = gr.Dropdown(choices=["elementary", "easy", "medium", "hard", "advanced"],value="medium",label="Difficulty Level")generate_button = gr.Button("Generate Questions", variant="primary")with gr.Row():output = gr.Markdown(label="Generated Questions")generate_button.click(fn=generate_math_questions,inputs=[chapter_input, num_questions, difficulty],outputs=output)gr.Markdown("---")gr.Markdown("Created by Kamagelo Mosia | Powered by DeepSeek and Hugging Face")# Launch the appdemo.launch()
123gradio>=4.0.0huggingface_hub>=0.19.0requests>=2.31.0README.md+44-12
app.py+64-310
requirements.txtAdded+3