PranavReddy18 commited on
Commit
2fd293d
Β·
verified Β·
1 Parent(s): 0fc9bed

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from dotenv import load_dotenv
3
+ import os
4
+ import tempfile
5
+ import base64
6
+ from gtts import gTTS # βœ… Use gTTS instead of pyttsx3
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
+ # βœ… Exact optimized prompt as provided
16
+ optimized_prompt = PromptTemplate(
17
+ input_variables=["problem"],
18
+ template=(
19
+ "You are an advanced AI tutor specializing in solving **math and physics problems** step by step. "
20
+ "Your goal is to **guide students logically**, ensuring they **understand every step** and its relevance. "
21
+ "Think like a **patient teacher** who explains concepts with clarity.\n\n"
22
+
23
+ "πŸ“š **Guidelines for solving problems:**\n"
24
+ "1️⃣ **Understanding the Problem:**\n"
25
+ " - Restate the problem in simple terms.\n"
26
+ " - Identify what is given and what needs to be found.\n\n"
27
+
28
+ "2️⃣ **Relevant Concepts & Formulas:**\n"
29
+ " - List the key principles, equations, or theorems needed to solve the problem.\n"
30
+ " - Explain why they are relevant.\n\n"
31
+
32
+ "3️⃣ **Step-by-Step Solution:**\n"
33
+ " - Break down the solution into small, logical steps.\n"
34
+ " - Show calculations with proper notation.\n"
35
+ " - Explain **each transformation, substitution, or simplification** clearly.\n\n"
36
+
37
+ "4️⃣ **Final Answer:**\n"
38
+ " - βœ… Box or highlight the final result.\n"
39
+ " - Include units where applicable.\n\n"
40
+
41
+ "5️⃣ **Verification & Insights:**\n"
42
+ " - πŸ”„ Verify the answer using an alternative method (if possible).\n"
43
+ " - πŸ—οΈ Provide a real-world analogy or intuition behind the result.\n\n"
44
+
45
+ "🎯 **Now, solve the following problem using this structured approach:**\n"
46
+ "**Problem:** {problem}\n\n"
47
+ "**Solution:**"
48
+ )
49
+ )
50
+
51
+ # Initialize Groq API model
52
+ llm = ChatGroq(api_key=GROQ_API_KEY, model_name="gemma2-9b-it")
53
+ llm_chain = LLMChain(llm=llm, prompt=optimized_prompt)
54
+
55
+ # Function to generate speech using gTTS and return Base64-encoded audio
56
+ def text_to_speech(text):
57
+ """Generate gTTS audio and return Base64 encoded string."""
58
+ tts = gTTS(text, lang="en")
59
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_audio:
60
+ tts.save(temp_audio.name)
61
+ with open(temp_audio.name, "rb") as audio_file:
62
+ audio_bytes = audio_file.read()
63
+ encoded_audio = base64.b64encode(audio_bytes).decode()
64
+ os.remove(temp_audio.name)
65
+ return encoded_audio
66
+
67
+ # Streamlit UI Design
68
+ st.set_page_config(page_title="STEM Solver πŸ€–", layout="centered", page_icon="🧠")
69
+
70
+ st.markdown("<h1 style='text-align: center;'>πŸ“š STEM Problem Solver πŸ€–</h1>", unsafe_allow_html=True)
71
+ 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)
72
+
73
+ # User Input
74
+ problem = st.text_area("πŸ“ Enter your problem:", placeholder="e.g., What is the integral of x?", height=100)
75
+
76
+ # Solve (Text) Button
77
+ if st.button("πŸ” Solve (Text)"):
78
+ if problem.strip():
79
+ with st.spinner("Thinking... πŸ€”"):
80
+ response = llm_chain.invoke({"problem": problem})
81
+ solution_text = response['text']
82
+ st.success("βœ… Solution Found!")
83
+
84
+ st.markdown("### ✨ Solution:")
85
+ st.markdown(f"<div style='background-color:#222831; padding:15px; border-radius:10px; color:white;'>"
86
+ f"<p style='font-size:16px;'>{solution_text}</p></div>", unsafe_allow_html=True)
87
+ else:
88
+ st.warning("⚠️ Please enter a valid problem.")
89
+
90
+ # Solve (Speech) Button
91
+ if st.button("πŸ”Š Solve (Speech)"):
92
+ if problem.strip():
93
+ with st.spinner("Speaking... 🎀"):
94
+ response = llm_chain.invoke({"problem": problem})
95
+ solution_text = response['text']
96
+
97
+ audio_base64 = text_to_speech(solution_text) # Get Base64 audio
98
+ audio_html = f"""
99
+ <audio controls>
100
+ <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
101
+ Your browser does not support the audio element.
102
+ </audio>
103
+ """
104
+ st.success("βœ… Solve (Speech) Started!")
105
+ st.markdown(audio_html, unsafe_allow_html=True)
106
+
107
+ # πŸ“₯ Add a download button for mobile users
108
+ audio_file_name = "solution.mp3"
109
+ with open(audio_file_name, "wb") as file:
110
+ file.write(base64.b64decode(audio_base64))
111
+
112
+ with open(audio_file_name, "rb") as file:
113
+ st.download_button(
114
+ label="πŸ“₯ Download Audio",
115
+ data=file,
116
+ file_name="solution.mp3",
117
+ mime="audio/mp3"
118
+ )
119
+ else:
120
+ st.warning("⚠️ Please enter a valid problem.")
121
+
122
+ # Footer
123
+ st.markdown("<br><p style='text-align:center; font-size:14px;'>πŸš€ Created with ❀️ by an AI-powered tutor! πŸ“–</p>", unsafe_allow_html=True)