Pbhat commited on
Commit
fef407d
Β·
verified Β·
1 Parent(s): 4b85d6c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -88
app.py CHANGED
@@ -1,88 +1,97 @@
1
- # streamlit_app.py
2
- import streamlit as st
3
- import re
4
- from sympy import symbols, integrate, exp, pi
5
- from transformers import AutoTokenizer, AutoModelForCausalLM
6
- import torch
7
-
8
- st.set_page_config(page_title="AI Physics Solver", page_icon="🧠")
9
-
10
- x, t = symbols("x t")
11
-
12
- def extract_integral(problem_text):
13
- match = re.search(r'(\d+)\*?[tx]\^(\d+)', problem_text)
14
- limits = re.findall(r'[tx]\s*=\s*([\d\.\w]+)', problem_text)
15
- exp_match = re.search(r'(\d+)e\^([\-+]?[\d\.]*)[tx]', problem_text)
16
-
17
- if 'radioactive' in problem_text or 'half-life' in problem_text:
18
- decay_match = re.search(r'(\d+)\s*e\^\s*-\s*(\d+\.?\d*)[tx]', problem_text)
19
- if decay_match and len(limits) == 2:
20
- N0 = int(decay_match.group(1))
21
- lam = float(decay_match.group(2))
22
- lower, upper = map(lambda v: eval(v, {"pi": pi}), limits)
23
- expr = lam * N0 * exp(-lam * t)
24
- return f"Total decayed = {integrate(expr, (t, lower, upper)).evalf()} units."
25
-
26
- if match and len(limits) == 2:
27
- coefficient = int(match.group(1))
28
- exponent = int(match.group(2))
29
- lower_limit = eval(limits[0], {"pi": pi})
30
- upper_limit = eval(limits[1], {"pi": pi})
31
- expr = coefficient * x**exponent
32
- return f"Accumulated Quantity = {integrate(expr, (x, lower_limit, upper_limit))}"
33
-
34
- return "Could not parse the integral format."
35
-
36
- @st.cache_resource
37
- def load_deepseek():
38
- model_name = "deepseek-ai/deepseek-math-7b-base"
39
- tokenizer = AutoTokenizer.from_pretrained(model_name)
40
- model = AutoModelForCausalLM.from_pretrained(
41
- model_name,
42
- torch_dtype=torch.float16,
43
- device_map="auto"
44
- )
45
- return tokenizer, model
46
-
47
- def run_deepseek(user_question):
48
- tokenizer, model = load_deepseek()
49
-
50
- solution_steps = """### Solution Format:
51
- 1. **Identify Given Data**
52
- 2. **Determine the Required Variable**
53
- 3. **Apply Relevant Equations**
54
- 4. **Substitute Values & Solve Step-by-Step**
55
- 5. **Verify & Conclude**
56
-
57
- ### Final Answer Format:
58
- Final Answer: [VARIABLE] = [ANSWER] [UNIT]
59
- """
60
- prompt = f"Q: Solve the following physics problem using rigorous mathematical reasoning. Do not skip any steps.\n\nProblem: {user_question}\n\n{solution_steps}\nA:"
61
- inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
62
-
63
- with torch.no_grad():
64
- outputs = model.generate(
65
- **inputs,
66
- max_new_tokens=500,
67
- temperature=0.1,
68
- repetition_penalty=1.0,
69
- eos_token_id=tokenizer.eos_token_id,
70
- pad_token_id=tokenizer.eos_token_id
71
- )
72
- return tokenizer.decode(outputs[0], skip_special_tokens=True).split("A:")[-1].strip()
73
-
74
- # ---------------- UI Layout ----------------
75
- st.title("🧠 AI Science Solver")
76
-
77
- task_type = st.selectbox("Choose Task Type", ["LLM Reasoning (DeepSeek)", "Symbolic Integration"])
78
- user_question = st.text_area("Enter your physics or math question below:")
79
-
80
- if st.button("Solve"):
81
- with st.spinner("Solving..."):
82
- if task_type == "LLM Reasoning (DeepSeek)":
83
- result = run_deepseek(user_question)
84
- else:
85
- result = extract_integral(user_question)
86
-
87
- st.subheader("πŸ“˜ Answer")
88
- st.write(result)
 
 
 
 
 
 
 
 
 
 
1
+ # streamlit_app.py
2
+ # app.py
3
+ import streamlit as st
4
+ import re
5
+ from sympy import symbols, integrate, exp, pi
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM
7
+ import torch
8
+
9
+ st.set_page_config(page_title="AI Physics Solver", page_icon="🧠")
10
+
11
+ x, t = symbols("x t")
12
+
13
+ def extract_integral(problem_text):
14
+ match = re.search(r'(\d+)\*?[tx]\^(\d+)', problem_text)
15
+ limits = re.findall(r'[tx]\s*=\s*([\d\.\\\w]+)', problem_text)
16
+ exp_match = re.search(r'(\d+)e\^([\-\+]?\d+\.?\d*)[tx]', problem_text)
17
+
18
+ if 'radioactive' in problem_text or 'half-life' in problem_text:
19
+ decay_match = re.search(r'(\d+)\s*e\^\s*-\s*(\d+\.?\d*)[tx]', problem_text)
20
+ if decay_match and len(limits) == 2:
21
+ N0 = int(decay_match.group(1))
22
+ lam = float(decay_match.group(2))
23
+ lower, upper = map(lambda v: eval(v, {"pi": pi}), limits)
24
+ expr = lam * N0 * exp(-lam * t)
25
+ return f"Total decayed = {integrate(expr, (t, lower, upper)).evalf()} units."
26
+
27
+ if match and len(limits) == 2:
28
+ coefficient = int(match.group(1))
29
+ exponent = int(match.group(2))
30
+ lower_limit = eval(limits[0], {"pi": pi})
31
+ upper_limit = eval(limits[1], {"pi": pi})
32
+ expr = coefficient * x**exponent
33
+ return f"Accumulated Quantity = {integrate(expr, (x, lower_limit, upper_limit))}"
34
+
35
+ return "Could not parse the integral format."
36
+
37
+ @st.cache_resource
38
+ def load_deepseek():
39
+ model_name = "deepseek-ai/deepseek-math-7b-base"
40
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
41
+
42
+ if torch.cuda.is_available():
43
+ model = AutoModelForCausalLM.from_pretrained(
44
+ model_name,
45
+ torch_dtype=torch.float16,
46
+ device_map="auto"
47
+ )
48
+ else:
49
+ model = AutoModelForCausalLM.from_pretrained(model_name)
50
+
51
+ return tokenizer, model
52
+
53
+ def run_deepseek(user_question):
54
+ tokenizer, model = load_deepseek()
55
+ solution_steps = """
56
+ ### Solution:
57
+ 1. Understand the problem and extract known quantities.
58
+ 2. Apply relevant physical laws or mathematical formulas.
59
+ 3. Solve algebraically or numerically as required.
60
+ 4. Clearly present the final answer.
61
+
62
+ ### Final Answer Format:
63
+ Final Answer: [VARIABLE] = [ANSWER] [UNIT]
64
+ """
65
+ prompt = f"Q: Solve the following physics problem using rigorous mathematical reasoning. Do not skip any steps.\n\nProblem: {user_question}\n\n{solution_steps}\nA:"
66
+ inputs = tokenizer(prompt, return_tensors="pt")
67
+
68
+ # Move inputs to GPU if available
69
+ if torch.cuda.is_available():
70
+ inputs = inputs.to("cuda")
71
+
72
+ with torch.no_grad():
73
+ outputs = model.generate(
74
+ **inputs,
75
+ max_new_tokens=500,
76
+ temperature=0.1,
77
+ repetition_penalty=1.0,
78
+ eos_token_id=tokenizer.eos_token_id,
79
+ pad_token_id=tokenizer.eos_token_id
80
+ )
81
+ return tokenizer.decode(outputs[0], skip_special_tokens=True).split("A:")[-1].strip()
82
+
83
+ # ---------------- UI Layout ----------------
84
+ st.title("🧠 AI Science Solver")
85
+
86
+ task_type = st.selectbox("Choose Task Type", ["LLM Reasoning (DeepSeek)", "Symbolic Integration"])
87
+ user_question = st.text_area("Enter your physics or math question below:")
88
+
89
+ if st.button("Solve"):
90
+ with st.spinner("Solving..."):
91
+ if task_type == "LLM Reasoning (DeepSeek)":
92
+ result = run_deepseek(user_question)
93
+ else:
94
+ result = extract_integral(user_question)
95
+
96
+ st.subheader("πŸ“˜ Answer")
97
+ st.write(result)