newtechdevng commited on
Commit
dec1173
·
verified ·
1 Parent(s): f6aa143

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+
5
+ MODEL_ID = "newtechdevng/math-tutor-smollm2-360M"
6
+
7
+ print("Loading model...")
8
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ MODEL_ID,
11
+ torch_dtype=torch.float32,
12
+ device_map="cpu"
13
+ )
14
+ model.eval()
15
+ print("Ready!")
16
+
17
+ SYSTEM_PROMPT = (
18
+ "You are an expert math teacher for students from Class 6 to Class 10. "
19
+ "Solve problems step by step, show all working, and explain clearly."
20
+ )
21
+
22
+ def solve(question, class_level, history):
23
+ if not question.strip():
24
+ return history, ""
25
+ prompt = (
26
+ "<|im_start|>system\n"
27
+ + SYSTEM_PROMPT
28
+ + " You are helping a Class " + class_level + " student.<|im_end|>\n"
29
+ + "<|im_start|>user\n"
30
+ + question
31
+ + "<|im_end|>\n<|im_start|>assistant\n"
32
+ )
33
+ inputs = tokenizer(prompt, return_tensors="pt")
34
+ with torch.no_grad():
35
+ outputs = model.generate(
36
+ **inputs,
37
+ max_new_tokens=350,
38
+ temperature=0.1,
39
+ do_sample=True,
40
+ pad_token_id=tokenizer.eos_token_id,
41
+ )
42
+ reply = tokenizer.decode(outputs[0], skip_special_tokens=False)
43
+ answer = reply.split("<|im_start|>assistant\n")[-1]
44
+ answer = answer.replace("<|im_end|>", "").strip()
45
+ history.append((question, answer))
46
+ return history, ""
47
+
48
+ with gr.Blocks(title="Math Tutor Class 6-10", theme=gr.themes.Soft()) as app:
49
+ gr.Markdown("# 🎓 Math Tutor — Class 6 to 10")
50
+ gr.Markdown("Ask any math question and get step-by-step solutions!")
51
+ with gr.Row():
52
+ class_level = gr.Dropdown(
53
+ choices=["6", "7", "8", "9", "10"],
54
+ value="8", label="Select Class", scale=1
55
+ )
56
+ chatbot = gr.Chatbot(label="Math Solutions", height=450)
57
+ with gr.Row():
58
+ question = gr.Textbox(
59
+ label="Your Question",
60
+ placeholder="e.g. Solve 3x - 7 = 14. Show all steps.",
61
+ lines=2, scale=4
62
+ )
63
+ btn = gr.Button("Solve", variant="primary", scale=1)
64
+ gr.Examples(
65
+ examples=[
66
+ ["Find the LCM of 12, 18 and 24.", "6"],
67
+ ["Solve: 3x - 7 = 14", "8"],
68
+ ["Find roots of x2 - 5x + 6 = 0", "10"],
69
+ ["A train travels 360 km in 4 hours. What is its speed?", "7"],
70
+ ["Find the area of a triangle with base 10 cm and height 6 cm.", "9"],
71
+ ],
72
+ inputs=[question, class_level]
73
+ )
74
+ state = gr.State([])
75
+ btn.click(solve, [question, class_level, state], [chatbot, question])
76
+ question.submit(solve, [question, class_level, state], [chatbot, question])
77
+
78
+ app.launch()