CoolFace
Apppublic

PranavReddy18/STEM_Problem_Solver

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py124 linesDownload Raw Back to root
1import streamlit as st
2from dotenv import load_dotenv
3import os
4import tempfile
5import base64
6from gtts import gTTS  # ✅ Use gTTS instead of pyttsx3
7from langchain_groq import ChatGroq
8from langchain.chains import LLMChain
9from langchain.prompts import PromptTemplate
10
11# Load environment variables
12load_dotenv()
13GROQ_API_KEY = os.getenv("GROQ_API_KEY")
14
15# ✅ Exact optimized prompt as provided
16optimized_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
52llm = ChatGroq(api_key=GROQ_API_KEY, model_name="gemma2-9b-it")
53llm_chain = LLMChain(llm=llm, prompt=optimized_prompt)
54
55# Function to generate speech using gTTS and return Base64-encoded audio
56def 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
68st.set_page_config(page_title="STEM Solver 🤖", layout="centered", page_icon="🧠")
69
70st.markdown("<h1 style='text-align: center;'>📚 STEM Problem Solver 🤖</h1>", unsafe_allow_html=True)
71st.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
74problem = st.text_area("📝 Enter your problem:", placeholder="e.g., What is the integral of x?", height=100)
75
76# Solve (Text) Button
77if 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
91if 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
123st.markdown("<br><p style='text-align:center; font-size:14px;'>🚀 Created with ❤️ by an AI-powered tutor! 📖</p>", unsafe_allow_html=True)
124