Spaces:
Runtime error
Runtime error
import gradio as gr | |
from huggingface_hub import InferenceClient | |
import os | |
from sympy import symbols, Eq, solve, latex | |
# Initialize the Hugging Face Inference Client | |
client = InferenceClient() | |
def preprocess_latex(content): | |
""" | |
Preprocess the AI response using sympy to properly format mathematical expressions. | |
""" | |
lines = content.split("\n") # Split response into lines | |
processed_lines = [] | |
for line in lines: | |
if "[" in line and "]" in line: # Detect mathematical expressions in brackets | |
while "[" in line and "]" in line: | |
start = line.index("[") | |
end = line.index("]") + 1 | |
math_expr = line[start + 1 : end - 1].strip() | |
try: | |
# Parse the math expression and convert to LaTeX | |
sympy_expr = sympify(math_expr) | |
latex_expr = latex(sympy_expr) | |
line = line[:start] + f"$$ {latex_expr} $$" + line[end:] | |
except Exception: | |
# Fallback to raw math if parsing fails | |
line = line[:start] + f"$$ {math_expr} $$" + line[end:] | |
processed_lines.append(line) | |
return "\n".join(processed_lines) | |
# Function to generate and format AI response | |
def generate_response(prompt_template, **kwargs): | |
# Simulate processing/loading | |
prompt = os.getenv(prompt_template).format(**kwargs) | |
response = client.chat.completions.create( | |
model="Qwen/Qwen2.5-Math-1.5B-Instruct", | |
messages=[{"role": "user", "content": prompt}], | |
temperature=0.7, | |
max_tokens=1024, | |
top_p=0.8 | |
) | |
response_content = response.choices[0].message["content"] | |
print(response_content) | |
formatted_response = preprocess_latex(response_content) | |
return gr.update(value=f"{formatted_response}") | |
# Gradio app interface | |
with gr.Blocks() as app: | |
gr.Markdown("## Mathematical Insight Tutor") | |
gr.Markdown("An advanced AI-powered tutor to help you master math concepts with step-by-step explanations.") | |
def create_tab(tab_name, prompt_template, inputs): | |
with gr.Tab(tab_name): | |
input_fields = [] | |
for inp in inputs: | |
if inp["type"] == "textbox": | |
input_fields.append( | |
gr.Textbox(lines=inp.get("lines", 1), label=inp["label"], placeholder=inp["placeholder"]) | |
) | |
elif inp["type"] == "dropdown": | |
input_fields.append( | |
gr.Dropdown(choices=inp["choices"], label=inp["label"]) | |
) | |
elif inp["type"] == "value": | |
input_fields.append( | |
gr.Textbox(label=inp["label"], placeholder=inp["placeholder"]) | |
) | |
# Button and output | |
button = gr.Button(f"{tab_name} Execute") | |
output = gr.Markdown(label="Output", elem_id="latex-output") | |
# Link button to the response wrapper | |
button.click( | |
fn=lambda *args: generate_response(prompt_template, **dict(zip([inp["key"] for inp in inputs], args))), | |
inputs=input_fields, | |
outputs=output, | |
api_name=f"/{tab_name.lower().replace(' ', '_')}_execute" | |
) | |
# Tabs for functionalities | |
create_tab( | |
"Solve a Problem", | |
"PROMPT_SOLVE", | |
[ | |
{"key": "problem", "type": "textbox", "label": "Enter Math Problem", "placeholder": "e.g., Solve for x: 2x + 5 = 15"}, | |
{"key": "difficulty", "type": "dropdown", "label": "Difficulty Level", "choices": ["Beginner", "Intermediate", "Advanced"]} | |
] | |
) | |
create_tab( | |
"Generate a Hint", | |
"PROMPT_HINT", | |
[ | |
{"key": "problem", "type": "textbox", "label": "Enter Math Problem for Hint", "placeholder": "e.g., Solve for x: 2x + 5 = 15"}, | |
{"key": "difficulty", "type": "dropdown", "label": "Difficulty Level", "choices": ["Beginner", "Intermediate", "Advanced"]} | |
] | |
) | |
create_tab( | |
"Verify Solution", | |
"PROMPT_VERIFY", | |
[ | |
{"key": "problem", "type": "textbox", "label": "Enter Math Problem", "placeholder": "e.g., Solve for x: 2x + 5 = 15"}, | |
{"key": "solution", "type": "value", "label": "Enter Your Solution", "placeholder": "e.g., x = 5"} | |
] | |
) | |
create_tab( | |
"Generate Practice Question", | |
"PROMPT_GENERATE", | |
[ | |
{"key": "topic", "type": "textbox", "label": "Enter Math Topic", "placeholder": "e.g., Algebra, Calculus"}, | |
{"key": "difficulty", "type": "dropdown", "label": "Difficulty Level", "choices": ["Beginner", "Intermediate", "Advanced"]} | |
] | |
) | |
create_tab( | |
"Explain Concept", | |
"PROMPT_EXPLAIN", | |
[ | |
{"key": "problem", "type": "textbox", "label": "Enter Math Problem", "placeholder": "e.g., Solve for x: 2x + 5 = 15"}, | |
{"key": "difficulty", "type": "dropdown", "label": "Difficulty Level", "choices": ["Beginner", "Intermediate", "Advanced"]} | |
] | |
) | |
# Add custom CSS for LaTeX rendering | |
app.css = """ | |
#latex-output { | |
font-family: "Computer Modern", serif; | |
font-size: 16px; | |
line-height: 1.5; | |
} | |
""" | |
# Launch the app | |
app.launch(debug=True) |