File size: 2,287 Bytes
4bf76eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732198e
4bf76eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import gradio as gr
import sympy as sp
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"  
SYSTEM_PROMPT = "You are a helpful tutor. Match the user's level."

tok = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype=torch.float32,  # CPU
    device_map=None
)
model.eval()

def verify_math(expr_str: str) -> str:
    try:
        expr = sp.sympify(expr_str)
        simplified = sp.simplify(expr)
        return f"Simplified: ${sp.latex(simplified)}$"
    except Exception as e:
        return f"Could not verify with SymPy: {e}"

def generate(question: str, level: str, step_by_step: bool) -> str:
    if not question.strip():
        return "Please enter a question."
    style = f"Level: {level}. {'Explain step-by-step.' if step_by_step else 'Be concise.'}"
    prompt = f"System: {SYSTEM_PROMPT}\n{style}\nUser: {question}\nAssistant:"
    inputs = tok(prompt, return_tensors="pt")
    with torch.no_grad():
        out = model.generate(
            **inputs,
            max_new_tokens=192,
            do_sample=True,
            temperature=0.7,
            top_p=0.95,
            pad_token_id=tok.eos_token_id
        )
    text = tok.decode(out[0], skip_special_tokens=True)
    if "Assistant:" in text:
        text = text.split("Assistant:", 1)[1].strip()
    is_math = any(ch in question for ch in "+-*/=^") or question.lower().startswith(("simplify","derive","integrate"))
    sympy_note = verify_math(question) if is_math else "No math verification needed."
    return f"{text}\n\n---\n**SymPy check:** {sympy_note}\n_Status: Transformers CPU_"

def build_app():
    with gr.Blocks(title="LearnLoop — CPU Space") as demo:
        gr.Markdown("# LearnLoop — CPU-only demo")
        q = gr.Textbox(label="Your question", placeholder="e.g., simplify (x^2 - 1)/(x - 1)")
        level = gr.Dropdown(choices=["Beginner","Intermediate","Advanced"], value="Beginner", label="Level")
        step = gr.Checkbox(value=True, label="Step-by-step")
        btn = gr.Button("Explain"); out = gr.Markdown()
        btn.click(generate, [q, level, step], out)
    return demo

if __name__ == "__main__":
    build_app().launch()