shukdevdatta123 commited on
Commit
4dab2c1
Β·
verified Β·
1 Parent(s): be6c3d6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +422 -0
app.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import re
4
+ from openai import OpenAI
5
+ from typing import List, Dict, Tuple, Optional
6
+ import time
7
+ import random
8
+
9
+ class MemoryPalaceBuilder:
10
+ def __init__(self):
11
+ self.client = None
12
+ self.current_palace = None
13
+ self.learning_sessions = []
14
+
15
+ def set_api_key(self, api_key: str) -> str:
16
+ """Initialize OpenAI client with OpenRouter API key"""
17
+ try:
18
+ self.client = OpenAI(
19
+ base_url="https://openrouter.ai/api/v1",
20
+ api_key=api_key,
21
+ )
22
+ # Test the connection with a simple request
23
+ test_response = self.client.chat.completions.create(
24
+ model="deepseek/deepseek-r1-0528-qwen3-8b:free",
25
+ messages=[{"role": "user", "content": "Hello, respond with 'API connection successful'"}],
26
+ max_tokens=50
27
+ )
28
+ return "βœ… API Key validated successfully!"
29
+ except Exception as e:
30
+ return f"❌ API Key validation failed: {str(e)}"
31
+
32
+ def analyze_space(self, space_description: str, space_type: str) -> str:
33
+ """Analyze the user's space and create a spatial map"""
34
+ if not self.client:
35
+ return "Please set your OpenRouter API key first."
36
+
37
+ prompt = f"""
38
+ Analyze this {space_type} space and create a detailed spatial map for a memory palace:
39
+
40
+ Space Description: {space_description}
41
+
42
+ Please provide a structured analysis with:
43
+ 1. Key locations/rooms/areas identified
44
+ 2. Natural pathways and flow between areas
45
+ 3. Distinctive features that can serve as memory anchors
46
+ 4. Sensory elements (lighting, textures, sounds, smells)
47
+ 5. Emotional associations or significance of different areas
48
+
49
+ Format your response as a clear, organized spatial map that can be used for memory techniques.
50
+ """
51
+
52
+ try:
53
+ response = self.client.chat.completions.create(
54
+ model="deepseek/deepseek-r1-0528-qwen3-8b:free",
55
+ messages=[{"role": "user", "content": prompt}],
56
+ max_tokens=1000
57
+ )
58
+ return response.choices[0].message.content
59
+ except Exception as e:
60
+ return f"Error analyzing space: {str(e)}"
61
+
62
+ def create_memory_palace(self, space_analysis: str, learning_content: str, content_type: str, difficulty: str) -> str:
63
+ """Create a memory palace mapping content to space"""
64
+ if not self.client:
65
+ return "Please set your OpenRouter API key first."
66
+
67
+ prompt = f"""
68
+ Create an intelligent memory palace using advanced spatial reasoning:
69
+
70
+ SPACE ANALYSIS:
71
+ {space_analysis}
72
+
73
+ CONTENT TO MEMORIZE:
74
+ Type: {content_type}
75
+ Difficulty: {difficulty}
76
+ Content: {learning_content}
77
+
78
+ Use chain-of-thought reasoning to:
79
+ 1. Break down the content into logical chunks
80
+ 2. Map each chunk to specific locations in the space
81
+ 3. Create vivid, multi-sensory associations
82
+ 4. Design a logical pathway that connects all information
83
+ 5. Include memory triggers and retrieval cues
84
+ 6. Add narrative elements to make it memorable
85
+
86
+ Provide:
87
+ - Step-by-step journey through the memory palace
88
+ - Specific visualizations for each location
89
+ - Memory techniques and mnemonics
90
+ - Practice suggestions
91
+
92
+ Make it engaging, creative, and scientifically sound for memory retention.
93
+ """
94
+
95
+ try:
96
+ response = self.client.chat.completions.create(
97
+ model="deepseek/deepseek-r1-0528-qwen3-8b:free",
98
+ messages=[{"role": "user", "content": prompt}],
99
+ max_tokens=1500
100
+ )
101
+
102
+ palace_content = response.choices[0].message.content
103
+ self.current_palace = {
104
+ 'space_analysis': space_analysis,
105
+ 'content': learning_content,
106
+ 'content_type': content_type,
107
+ 'difficulty': difficulty,
108
+ 'palace_design': palace_content,
109
+ 'created_at': time.strftime("%Y-%m-%d %H:%M:%S")
110
+ }
111
+ return palace_content
112
+ except Exception as e:
113
+ return f"Error creating memory palace: {str(e)}"
114
+
115
+ def generate_quiz(self, quiz_type: str) -> Tuple[str, str]:
116
+ """Generate quiz questions based on the current memory palace"""
117
+ if not self.client or not self.current_palace:
118
+ return "Please create a memory palace first.", ""
119
+
120
+ prompt = f"""
121
+ Based on this memory palace, create a {quiz_type} quiz:
122
+
123
+ MEMORY PALACE:
124
+ {self.current_palace['palace_design']}
125
+
126
+ ORIGINAL CONTENT:
127
+ {self.current_palace['content']}
128
+
129
+ Create 5 questions that test:
130
+ - Recall of specific information
131
+ - Understanding of spatial relationships
132
+ - Application of learned concepts
133
+ - Memory pathway navigation
134
+
135
+ Format as clear questions with multiple choice or fill-in-the-blank.
136
+ Provide the answer key separately.
137
+ """
138
+
139
+ try:
140
+ response = self.client.chat.completions.create(
141
+ model="deepseek/deepseek-r1-0528-qwen3-8b:free",
142
+ messages=[{"role": "user", "content": prompt}],
143
+ max_tokens=800
144
+ )
145
+
146
+ quiz_content = response.choices[0].message.content
147
+
148
+ # Try to separate questions and answers
149
+ if "ANSWER KEY" in quiz_content or "ANSWERS" in quiz_content:
150
+ parts = re.split(r"ANSWER[S]?\s*KEY|ANSWERS", quiz_content, flags=re.IGNORECASE)
151
+ questions = parts[0].strip()
152
+ answers = parts[1].strip() if len(parts) > 1 else "Answers included in response above."
153
+ else:
154
+ questions = quiz_content
155
+ answers = "Answers are integrated with questions above."
156
+
157
+ return questions, answers
158
+ except Exception as e:
159
+ return f"Error generating quiz: {str(e)}", ""
160
+
161
+ def get_study_tips(self) -> str:
162
+ """Get personalized study tips and techniques"""
163
+ if not self.client or not self.current_palace:
164
+ return "Please create a memory palace first."
165
+
166
+ prompt = f"""
167
+ Provide advanced study tips and memory techniques for this memory palace:
168
+
169
+ PALACE INFO:
170
+ Content Type: {self.current_palace['content_type']}
171
+ Difficulty: {self.current_palace['difficulty']}
172
+
173
+ PALACE DESIGN:
174
+ {self.current_palace['palace_design'][:500]}...
175
+
176
+ Provide:
177
+ 1. Optimal review schedule using spaced repetition
178
+ 2. Advanced memory techniques to strengthen associations
179
+ 3. Ways to expand and connect this palace to other knowledge
180
+ 4. Troubleshooting common memory issues
181
+ 5. Progressive difficulty adjustments
182
+ 6. Multi-sensory enhancement techniques
183
+ """
184
+
185
+ try:
186
+ response = self.client.chat.completions.create(
187
+ model="deepseek/deepseek-r1-0528-qwen3-8b:free",
188
+ messages=[{"role": "user", "content": prompt}],
189
+ max_tokens=800
190
+ )
191
+ return response.choices[0].message.content
192
+ except Exception as e:
193
+ return f"Error getting study tips: {str(e)}"
194
+
195
+ def export_palace(self) -> str:
196
+ """Export current memory palace as JSON"""
197
+ if not self.current_palace:
198
+ return "No memory palace to export."
199
+
200
+ return json.dumps(self.current_palace, indent=2)
201
+
202
+ # Initialize the Memory Palace Builder
203
+ palace_builder = MemoryPalaceBuilder()
204
+
205
+ # Custom CSS for better styling
206
+ custom_css = """
207
+ .gradio-container {
208
+ max-width: 1200px !important;
209
+ }
210
+ .palace-header {
211
+ text-align: center;
212
+ color: #2c5aa0;
213
+ margin: 20px 0;
214
+ }
215
+ .section-header {
216
+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
217
+ color: white;
218
+ padding: 10px;
219
+ border-radius: 5px;
220
+ margin: 10px 0;
221
+ }
222
+ """
223
+
224
+ # Create the Gradio interface
225
+ with gr.Blocks(css=custom_css, title="Memory Palace Builder", theme=gr.themes.Soft()) as app:
226
+ gr.HTML("""
227
+ <div class="palace-header">
228
+ <h1>🏰 Memory Palace Builder</h1>
229
+ <p>Transform any space into a powerful learning tool using AI-powered spatial mnemonics</p>
230
+ </div>
231
+ """)
232
+
233
+ with gr.Tab("πŸ”‘ Setup"):
234
+ gr.HTML("<div class='section-header'><h3>API Configuration</h3></div>")
235
+
236
+ with gr.Row():
237
+ api_key_input = gr.Textbox(
238
+ label="OpenRouter API Key",
239
+ placeholder="Enter your OpenRouter API key here...",
240
+ type="password",
241
+ info="Get your free API key from https://openrouter.ai/"
242
+ )
243
+ api_status = gr.Textbox(
244
+ label="API Status",
245
+ value="Not connected",
246
+ interactive=False
247
+ )
248
+
249
+ validate_btn = gr.Button("πŸ”— Validate API Key", variant="primary")
250
+ validate_btn.click(
251
+ palace_builder.set_api_key,
252
+ inputs=[api_key_input],
253
+ outputs=[api_status]
254
+ )
255
+
256
+ with gr.Tab("πŸ—ΊοΈ Space Analysis"):
257
+ gr.HTML("<div class='section-header'><h3>Describe Your Space</h3></div>")
258
+
259
+ with gr.Row():
260
+ with gr.Column():
261
+ space_type = gr.Dropdown(
262
+ choices=["Home/Apartment", "Office/Workplace", "School/University", "Neighborhood Route", "Park/Outdoor Space", "Other"],
263
+ label="Space Type",
264
+ value="Home/Apartment"
265
+ )
266
+
267
+ space_description = gr.Textbox(
268
+ lines=8,
269
+ label="Space Description",
270
+ placeholder="""Describe your space in detail. For example:
271
+
272
+ 'My apartment has a front door that opens to a small hallway. To the left is the living room with a big window, couch, and TV. Straight ahead is the kitchen with white cabinets and a small dining table. The bedroom is to the right with a bed, dresser, and closet. The bathroom is next to the bedroom with a blue shower curtain.'
273
+
274
+ Include layouts, colors, furniture, lighting, and any distinctive features.""",
275
+ info="The more detail you provide, the better your memory palace will be!"
276
+ )
277
+
278
+ with gr.Column():
279
+ space_analysis_output = gr.Textbox(
280
+ lines=12,
281
+ label="Space Analysis",
282
+ placeholder="Your space analysis will appear here...",
283
+ interactive=False
284
+ )
285
+
286
+ analyze_btn = gr.Button("πŸ” Analyze Space", variant="primary", size="lg")
287
+ analyze_btn.click(
288
+ palace_builder.analyze_space,
289
+ inputs=[space_description, space_type],
290
+ outputs=[space_analysis_output]
291
+ )
292
+
293
+ with gr.Tab("🏰 Build Palace"):
294
+ gr.HTML("<div class='section-header'><h3>Create Your Memory Palace</h3></div>")
295
+
296
+ with gr.Row():
297
+ with gr.Column():
298
+ content_type = gr.Dropdown(
299
+ choices=["Language Vocabulary", "Historical Facts", "Scientific Concepts", "Programming Code", "Mathematical Formulas", "Medical Terms", "Literature/Poetry", "Business Concepts", "Other"],
300
+ label="Content Type",
301
+ value="Language Vocabulary"
302
+ )
303
+
304
+ difficulty = gr.Dropdown(
305
+ choices=["Beginner", "Intermediate", "Advanced", "Expert"],
306
+ label="Difficulty Level",
307
+ value="Intermediate"
308
+ )
309
+
310
+ learning_content = gr.Textbox(
311
+ lines=8,
312
+ label="Content to Memorize",
313
+ placeholder="""Enter the information you want to memorize. Examples:
314
+
315
+ For Language: 'French words: maison (house), chat (cat), livre (book), eau (water), rouge (red)'
316
+
317
+ For History: 'World War II timeline: 1939 - Germany invades Poland, 1941 - Pearl Harbor attack, 1944 - D-Day landings, 1945 - End of war'
318
+
319
+ For Programming: 'Python list methods: append(), remove(), pop(), insert(), index(), count()'""",
320
+ info="Be specific and organized - this will be mapped to your space!"
321
+ )
322
+
323
+ with gr.Column():
324
+ palace_output = gr.Textbox(
325
+ lines=15,
326
+ label="Your Memory Palace",
327
+ placeholder="Your custom memory palace will be generated here...",
328
+ interactive=False
329
+ )
330
+
331
+ create_btn = gr.Button("πŸ—οΈ Build Memory Palace", variant="primary", size="lg")
332
+ create_btn.click(
333
+ palace_builder.create_memory_palace,
334
+ inputs=[space_analysis_output, learning_content, content_type, difficulty],
335
+ outputs=[palace_output]
336
+ )
337
+
338
+ with gr.Tab("πŸ“ Practice & Quiz"):
339
+ gr.HTML("<div class='section-header'><h3>Test Your Memory Palace</h3></div>")
340
+
341
+ with gr.Row():
342
+ quiz_type = gr.Dropdown(
343
+ choices=["Quick Review", "Comprehensive Test", "Spatial Navigation", "Random Recall"],
344
+ label="Quiz Type",
345
+ value="Quick Review"
346
+ )
347
+ generate_quiz_btn = gr.Button("πŸ“‹ Generate Quiz", variant="secondary")
348
+
349
+ with gr.Row():
350
+ with gr.Column():
351
+ quiz_questions = gr.Textbox(
352
+ lines=10,
353
+ label="Quiz Questions",
354
+ placeholder="Quiz questions will appear here...",
355
+ interactive=False
356
+ )
357
+
358
+ with gr.Column():
359
+ quiz_answers = gr.Textbox(
360
+ lines=10,
361
+ label="Answer Key",
362
+ placeholder="Answer key will appear here...",
363
+ interactive=False
364
+ )
365
+
366
+ generate_quiz_btn.click(
367
+ palace_builder.generate_quiz,
368
+ inputs=[quiz_type],
369
+ outputs=[quiz_questions, quiz_answers]
370
+ )
371
+
372
+ with gr.Tab("πŸ’‘ Study Tips"):
373
+ gr.HTML("<div class='section-header'><h3>Personalized Learning Strategies</h3></div>")
374
+
375
+ get_tips_btn = gr.Button("🧠 Get Study Tips", variant="secondary", size="lg")
376
+
377
+ study_tips_output = gr.Textbox(
378
+ lines=15,
379
+ label="Personalized Study Tips",
380
+ placeholder="Personalized study strategies will appear here...",
381
+ interactive=False
382
+ )
383
+
384
+ get_tips_btn.click(
385
+ palace_builder.get_study_tips,
386
+ outputs=[study_tips_output]
387
+ )
388
+
389
+ with gr.Tab("πŸ’Ύ Export"):
390
+ gr.HTML("<div class='section-header'><h3>Save Your Memory Palace</h3></div>")
391
+
392
+ export_btn = gr.Button("πŸ“€ Export Palace as JSON", variant="secondary")
393
+
394
+ export_output = gr.Code(
395
+ label="Memory Palace Export",
396
+ language="json",
397
+ interactive=False
398
+ )
399
+
400
+ gr.HTML("""
401
+ <div style="margin-top: 20px; padding: 15px; background-color: #f0f0f0; border-radius: 5px;">
402
+ <h4>πŸ’‘ Tips for Using Your Memory Palace:</h4>
403
+ <ul>
404
+ <li><strong>Practice regularly:</strong> Walk through your palace daily for best retention</li>
405
+ <li><strong>Use multiple senses:</strong> Visualize, hear, and feel the associations</li>
406
+ <li><strong>Start simple:</strong> Master one palace before creating complex ones</li>
407
+ <li><strong>Be consistent:</strong> Always follow the same path through your space</li>
408
+ <li><strong>Make it personal:</strong> Use meaningful locations and vivid imagery</li>
409
+ </ul>
410
+ </div>
411
+ """)
412
+
413
+ export_btn.click(
414
+ palace_builder.export_palace,
415
+ outputs=[export_output]
416
+ )
417
+
418
+ # Launch the app
419
+ if __name__ == "__main__":
420
+ app.launch(
421
+ share=True
422
+ )