PranavReddy18 commited on
Commit
c32ae9c
·
verified ·
1 Parent(s): 6c4b127

Upload 2 files

Browse files
Files changed (2) hide show
  1. app5.py +160 -0
  2. requirements.txt +13 -0
app5.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ import os
4
+ import pyttsx3
5
+ import threading
6
+
7
+ from langchain_groq import ChatGroq
8
+ from langchain.chains import LLMChain
9
+ from langchain.prompts import PromptTemplate
10
+
11
+ # Load environment variables
12
+ load_dotenv()
13
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
14
+
15
+ # Global variable for speech engine
16
+ speech_engine = None
17
+
18
+ # Function to initialize speech engine
19
+ def initialize_speech_engine():
20
+ global speech_engine
21
+ speech_engine = pyttsx3.init()
22
+
23
+ # Initialize engine at the start
24
+ initialize_speech_engine()
25
+
26
+ # Global variable to control speech stopping
27
+ stop_speech_flag = False
28
+
29
+ # Define the best-optimized prompt for structured problem-solving
30
+ optimized_prompt = PromptTemplate(
31
+ input_variables=["problem"],
32
+ template=(
33
+ "You are an advanced AI tutor specializing in solving **math and physics problems** step by step. "
34
+ "Your goal is to **guide students logically**, ensuring they **understand every step** and its relevance. "
35
+ "Think like a **patient teacher** who explains concepts with clarity.\n\n"
36
+
37
+ "📚 **Guidelines for solving problems:**\n"
38
+ "1️⃣ **Understanding the Problem:**\n"
39
+ " - Restate the problem in simple terms.\n"
40
+ " - Identify what is given and what needs to be found.\n\n"
41
+
42
+ "2️⃣ **Relevant Concepts & Formulas:**\n"
43
+ " - List the key principles, equations, or theorems needed to solve the problem.\n"
44
+ " - Explain why they are relevant.\n\n"
45
+
46
+ "3️⃣ **Step-by-Step Solution:**\n"
47
+ " - Break down the solution into small, logical steps.\n"
48
+ " - Show calculations with proper notation.\n"
49
+ " - Explain **each transformation, substitution, or simplification** clearly.\n\n"
50
+
51
+ "4️⃣ **Final Answer:**\n"
52
+ " - ✅ Box or highlight the final result.\n"
53
+ " - Include units where applicable.\n\n"
54
+
55
+ "5️⃣ **Verification & Insights:**\n"
56
+ " - 🔄 Verify the answer using an alternative method (if possible).\n"
57
+ " - 🏗️ Provide a real-world analogy or intuition behind the result.\n\n"
58
+
59
+ "💡 **Example Solutions:**\n"
60
+ "---\n"
61
+ "🔢 **Example 1:**\n"
62
+ "**Problem:** Find the integral of x.\n\n"
63
+ "**Solution:**\n"
64
+ "1️⃣ **Understanding the Problem:** Compute the indefinite integral of f(x) = x.\n"
65
+ "2️⃣ **Relevant Concepts:** Use the power rule: ∫x^n dx = (x^(n+1))/(n+1) + C.\n"
66
+ "3️⃣ **Step-by-Step Solution:**\n"
67
+ " - Recognize x as x^1.\n"
68
+ " - Apply the power rule: increase the exponent by 1, giving x², then divide by the new exponent.\n"
69
+ " - Add the constant of integration, C.\n"
70
+ "4️⃣ **Final Answer:** (x²)/2 + C.\n"
71
+ "5️⃣ **Verification & Insights:** Differentiating (x²)/2 gives x, confirming correctness.\n\n"
72
+ "---\n"
73
+ "🚗 **Example 2:**\n"
74
+ "**Problem:** A car accelerates from rest at 5 m/s². Find its velocity after 4 seconds.\n\n"
75
+ "**Solution:**\n"
76
+ "1️⃣ **Understanding the Problem:** The car starts from rest and accelerates uniformly.\n"
77
+ "2️⃣ **Relevant Concepts:** Use kinematic equation: v = u + at.\n"
78
+ "3️⃣ **Step-by-Step Solution:**\n"
79
+ " - Given: u = 0 m/s, a = 5 m/s², t = 4 s.\n"
80
+ " - Apply formula: v = 0 + (5 × 4) = 20 m/s.\n"
81
+ "4️⃣ **Final Answer:** v = 20 m/s.\n"
82
+ "5️⃣ **Verification & Insights:** The result aligns with expected acceleration; using v² = u² + 2as also gives v = 20 m/s.\n\n"
83
+ "---\n\n"
84
+
85
+ "🎯 **Now, solve the following problem using this structured approach:**\n"
86
+ "**Problem:** {problem}\n\n"
87
+ "**Solution:**"
88
+ )
89
+ )
90
+
91
+ # Initialize Groq API model
92
+ llm = ChatGroq(api_key=GROQ_API_KEY, model_name="gemma2-9b-it")
93
+ llm_chain = LLMChain(llm=llm, prompt=optimized_prompt)
94
+
95
+ # Function to handle text-to-speech in a separate thread
96
+ def text_to_speech(text):
97
+ global stop_speech_flag, speech_engine
98
+ stop_speech_flag = False # Reset stop flag before speaking
99
+
100
+ def speak():
101
+ global stop_speech_flag, speech_engine
102
+ if speech_engine is None:
103
+ initialize_speech_engine() # Reinitialize if stopped
104
+ speech_engine.say(text)
105
+ speech_engine.runAndWait()
106
+
107
+ speech_thread = threading.Thread(target=speak)
108
+ speech_thread.start()
109
+
110
+ # Function to stop speech and reinitialize engine
111
+ def stop_speech():
112
+ global stop_speech_flag, speech_engine
113
+ stop_speech_flag = True
114
+ if speech_engine:
115
+ speech_engine.stop()
116
+ initialize_speech_engine() # Reinitialize for next use
117
+
118
+ # Streamlit UI Design
119
+ st.set_page_config(page_title="STEM Solver 🤖", layout="centered", page_icon="🧠")
120
+
121
+ st.markdown("<h1 style='text-align: center;'>📚 STEM Problem Solver 🤖</h1>", unsafe_allow_html=True)
122
+ st.markdown("<p style='text-align: center; font-size:18px;'>Enter a math or physics problem, and I'll solve it step by step! 🚀</p>", unsafe_allow_html=True)
123
+
124
+ # User Input
125
+ problem = st.text_area("📝 Enter your problem:", placeholder="e.g., What is the integral of x?", height=100)
126
+
127
+ # Solve (Text) Button
128
+ if st.button("🔍 Solve (Text)"):
129
+ if problem.strip():
130
+ with st.spinner("Thinking... 🤔"):
131
+ response = llm_chain.invoke({"problem": problem})
132
+ solution_text = response['text']
133
+ st.success("✅ Solution Found!")
134
+
135
+ st.markdown("### ✨ Solve (Text):")
136
+ st.markdown(f"<div style='background-color:#222831; padding:15px; border-radius:10px; color:white;'>"
137
+ f"<p style='font-size:16px;'>{solution_text}</p></div>", unsafe_allow_html=True)
138
+ else:
139
+ st.warning("⚠️ Please enter a valid problem.")
140
+
141
+ # Solve (Speech) Button
142
+ if st.button("🔊 Solve (Speech)"):
143
+ if problem.strip():
144
+ with st.spinner("Speaking... 🎤"):
145
+ response = llm_chain.invoke({"problem": problem})
146
+ solution_text = response['text']
147
+
148
+ st.success("✅ Solve (Speech) Started!")
149
+ text_to_speech(solution_text)
150
+ else:
151
+ st.warning("⚠️ Please enter a valid problem.")
152
+
153
+ # Stop Speech Button
154
+ if st.button("🛑 Stop Speech"):
155
+ stop_speech()
156
+ st.warning("🔇 Speech Stopped!")
157
+
158
+ # Footer
159
+ st.markdown("<br><p style='text-align:center; font-size:14px;'>🚀 Created with ❤️ by an AI-powered tutor! 📖</p>", unsafe_allow_html=True)
160
+
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ langchain-community
3
+ langchain-groq
4
+ python-dotenv
5
+ fastapi
6
+ streamlit
7
+ langsmith
8
+ langserve
9
+ uvicorn
10
+ python-dotenv
11
+ requests
12
+ pyttsx3
13
+ gtts