UmaGeeth commited on
Commit
dae0bc1
Β·
verified Β·
1 Parent(s): 910a335

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -0
app.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from deep_translator import GoogleTranslator
5
+ from gtts import gTTS
6
+ import base64
7
+ import tempfile
8
+ import google.generativeai as genai
9
+ import uuid
10
+ import speech_recognition as sr
11
+
12
+ # Load environment variables
13
+ load_dotenv()
14
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
15
+ model = genai.GenerativeModel("gemini-1.5-flash")
16
+
17
+ st.set_page_config(page_title="LearnMate - AI Buddy", page_icon="πŸ“š")
18
+ st.title("πŸŽ“ LearnMate - AI Learning Companion")
19
+
20
+ # Sidebar: Enhanced Sidebar with Goals and Tasks
21
+ st.sidebar.title("πŸ“Œ LearnMate Dashboard")
22
+
23
+ # Learning Goals Section
24
+ st.sidebar.subheader("🎯 Your Learning Goals")
25
+ learning_goal = st.sidebar.text_input("Add a Goal")
26
+ if st.sidebar.button("βž• Add Goal") and learning_goal:
27
+ if "goals" not in st.session_state:
28
+ st.session_state.goals = []
29
+ st.session_state.goals.append(learning_goal)
30
+
31
+ if "goals" in st.session_state:
32
+ for goal in st.session_state.goals:
33
+ st.sidebar.markdown(f"βœ… {goal}")
34
+
35
+ # Project Tracker
36
+ st.sidebar.subheader("πŸ“‹πŸ˜ŽTask Tracker")
37
+ if "todo" not in st.session_state:
38
+ st.session_state.todo = []
39
+ if "done" not in st.session_state:
40
+ st.session_state.done = []
41
+
42
+ new_task = st.sidebar.text_input("πŸ†•πŸ‘‰ New Task")
43
+ if st.sidebar.button("πŸ“ŒπŸŽ― Add Task") and new_task:
44
+ st.session_state.todo.append(new_task)
45
+
46
+ for i, task in enumerate(st.session_state.todo):
47
+ if st.sidebar.checkbox(f"⬜ {task}", key=f"todo_{i}_{task}"):
48
+ st.session_state.todo.remove(task)
49
+ st.session_state.done.append(task)
50
+
51
+ st.sidebar.subheader("βœ…πŸ™ŒTask Completed")
52
+ for i, task in enumerate(st.session_state.done):
53
+ st.sidebar.checkbox(f"βœ” {task}", value=True, disabled=True, key=f"done_{i}_{task}")
54
+
55
+ # Translation helper
56
+
57
+ def safe_translate(text, lang):
58
+ max_len = 500
59
+ chunks = [text[i:i+max_len] for i in range(0, len(text), max_len)]
60
+ return " ".join([GoogleTranslator(source='auto', target=lang).translate(chunk) for chunk in chunks])
61
+
62
+ # Tabs
63
+
64
+ TABS = st.tabs(["πŸ“˜ Learning Path", "πŸ’¬ Study Twin", "πŸ§ͺ Quiz Generator", "🎧 Audio Summary", "🌐 Regional Buddy"])
65
+
66
+ # ------------------------ πŸ“˜ Learning Path ------------------------#
67
+ with TABS[0]:
68
+ st.header("πŸ“˜ Build Your Learning Roadmap")
69
+
70
+ lang = st.selectbox("🌐 Language", ["english", "hindi", "tamil", "telugu"])
71
+ knowledge = st.text_area("🧠 Your Current Knowledge")
72
+ goal = st.text_area("🎯 Learning Goal")
73
+ style = st.selectbox("🧩 Learning Style", ["Visual", "Reading", "Hands-on", "Mixed"])
74
+
75
+ if st.button("πŸš€ Generate Plan"):
76
+ with st.spinner("🧠 Crafting your custom roadmap..."):
77
+ prompt = f"""
78
+ You are LearnMate, an expert AI tutor.
79
+ The user has the following:
80
+ - Current knowledge: {knowledge}
81
+ - Goal: {goal}
82
+ - Preferred learning style: {style}
83
+ Please generate a full markdown learning roadmap that includes:
84
+ 1. πŸ“˜ Stage-by-stage steps with estimated timelines.
85
+ 2. 🎨 Visual-style flow or layout described in text if user chose 'Visual'.
86
+ 3. πŸ“Ί Three *specific YouTube videos* including titles and real video *hyperlinks*.
87
+ 4. πŸ“š Recommended resources, tools or tutorials related to the goal.
88
+ 5. 🧠 Personalized study tips matching the selected learning style.
89
+ Format all sections clearly with markdown headers (##) and bullet points.
90
+ Example for video: [How Neural Networks Learn](https://www.youtube.com/watch?v=aircAruvnKk)
91
+ Do NOT return video titles without links.
92
+ """
93
+
94
+ response = model.generate_content(prompt)
95
+ plan = response.text
96
+
97
+ # Translate if needed
98
+ if lang != "english":
99
+ plan = safe_translate(plan, lang)
100
+
101
+ st.markdown("### πŸ“œ Your Learning Plan")
102
+ st.markdown(plan)
103
+
104
+ # Enable download
105
+ st.download_button(
106
+ label="⬇ Download Plan as .txt",
107
+ data=plan,
108
+ file_name="learning_plan.txt",
109
+ mime="text/plain"
110
+ )
111
+
112
+ st.markdown("---")
113
+ st.success("βœ… Video links are now clickable. Save this roadmap and start learning!")
114
+ # ------------------------ πŸ’¬ Study Twin ------------------------
115
+ # ------------------------ πŸ’¬ Study Twin ------------------------
116
+ with TABS[1]:
117
+ st.header("πŸ’¬ AI Study TwinπŸ‘―")
118
+ if "study_step" not in st.session_state:
119
+ st.session_state.study_step = 1
120
+ if "chat_history" not in st.session_state:
121
+ st.session_state.chat_history = []
122
+
123
+ if st.session_state.study_step == 1:
124
+ st.write("Let's get started ✨")
125
+ st.session_state.study_topic = st.text_input("πŸ“˜ What topic are you studying?")
126
+ st.session_state.confidence_level = st.slider("Confidence (0-10)", 0, 10)
127
+ if st.button("➑ Continue"):
128
+ st.session_state.study_step = 2
129
+
130
+ elif st.session_state.study_step == 2:
131
+ topic = st.session_state.study_topic
132
+ score = st.session_state.confidence_level
133
+ prompt = f"User is studying: {topic}, confidence: {score}/10. Suggest action plan, style-based activities & encouragement."
134
+ reply = model.generate_content(prompt).text
135
+ st.markdown("### 🎯 Suggestion")
136
+ st.markdown(reply)
137
+ if st.button("πŸ’¬ Ask a Question🌟"):
138
+ st.session_state.study_step = 3
139
+
140
+ elif st.session_state.study_step == 3:
141
+ st.subheader("πŸ€– Chat with Your Twin")
142
+ user_msg = st.text_input("You:", key="twin_input")
143
+ if st.button("πŸ“¨ Send"):
144
+ chat = model.start_chat(history=st.session_state.chat_history)
145
+ reply = chat.send_message(user_msg)
146
+ st.session_state.chat_history.append({"role": "user", "parts": [user_msg]})
147
+ st.session_state.chat_history.append({"role": "model", "parts": [reply.text]})
148
+
149
+ for msg in st.session_state.chat_history:
150
+ role = "πŸ§‘ You" if msg["role"] == "user" else "πŸ€– Twin"
151
+ st.markdown(f"{role}:** {msg['parts'][0]}")
152
+ # ------------------------ πŸ§ͺ Quiz Generator ------------------------
153
+ with TABS[2]:
154
+ st.header("πŸ§ͺ Test Yourself!")
155
+
156
+ topic = st.text_input("πŸ“˜ Enter a topic to quiz yourself:")
157
+ if st.button("🎯 Generate Quiz"):
158
+ prompt = f"""
159
+ You are a quiz master.
160
+ Generate 5 multiple choice questions (MCQs) for the topic: {topic}.
161
+ Each question must include:
162
+ - Question
163
+ - Four options (a, b, c, d)
164
+ - Correct answer line: Answer: x)
165
+ Format:
166
+ Q: [question]
167
+ a) ...
168
+ b) ...
169
+ c) ...
170
+ d) ...
171
+ Answer: x)
172
+ """
173
+ quiz_text = model.generate_content(prompt).text
174
+ st.session_state.quiz_data = quiz_text.strip().split("\n\n")
175
+ st.session_state.full_quiz_text = quiz_text
176
+
177
+ if "quiz_data" in st.session_state:
178
+ st.markdown("### πŸ“ Your Quiz")
179
+ for i, q_block in enumerate(st.session_state.quiz_data):
180
+ lines = q_block.strip().split("\n")
181
+ q_line = next((l for l in lines if l.strip().lower().startswith("q:")), None)
182
+ opts = [line for line in lines if line.strip()[:2] in ["a)", "b)", "c)", "d)"]]
183
+ ans_line = next((l for l in lines if "Answer:" in l), None)
184
+
185
+ if not (q_line and opts and ans_line):
186
+ st.warning(f"❌ Skipping malformed Q{i+1}")
187
+ continue
188
+
189
+ correct = ans_line.split(":")[-1].strip().lower()
190
+ selected = st.radio(f"Q{i+1}: {q_line[2:].strip()}", opts, key=f"quiz_{i}")
191
+
192
+ if st.button(f"βœ” Check Q{i+1}", key=f"btn_{i}"):
193
+ if selected.lower().startswith(correct):
194
+ st.success("βœ… Correct!")
195
+ else:
196
+ st.error(f"❌ Wrong. Correct answer is: {correct}")
197
+
198
+ # Download full quiz
199
+ st.markdown("---")
200
+ st.download_button("⬇ Download Full Quiz (.txt)", st.session_state.full_quiz_text, file_name="quiz.txt")
201
+ # ------------------------ 🎧 Audio Summary ------------------------
202
+ with TABS[3]:
203
+ st.header("🎧 Audio Summary")
204
+ text = st.text_area("Enter content:")
205
+ if st.button("πŸ”Š Generate Audio"):
206
+ tts = gTTS(text)
207
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
208
+ tts.save(fp.name)
209
+ with open(fp.name, "rb") as f:
210
+ audio_data = f.read()
211
+ b64 = base64.b64encode(audio_data).decode()
212
+ st.audio(f"data:audio/mp3;base64,{b64}", format='audio/mp3')
213
+ st.download_button("⬇ Download Audio", audio_data, file_name="audio_summary.mp3")
214
+
215
+ # ------------------------ 🌐 Regional Buddy ------------------------
216
+ with TABS[4]:
217
+ st.header("🌐 Speak in Your Language")
218
+ lang = st.selectbox("Choose Language", ["hindi", "tamil", "telugu"])
219
+ msg = st.text_area("Type your message:")
220
+ if st.button("πŸ” Translate"):
221
+ try:
222
+ translated = GoogleTranslator(source="en", target=lang).translate(msg)
223
+ st.success(f"Translated ({lang.upper()}): {translated}")
224
+ except Exception as e:
225
+ st.error(f"Error: {e}")