-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbjj_notebook.py
More file actions
executable file
Β·412 lines (341 loc) Β· 13.5 KB
/
bjj_notebook.py
File metadata and controls
executable file
Β·412 lines (341 loc) Β· 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python3
"""BJJ Notebook - Main CLI application."""
import sys
import os
from src.chat_handler import BJJChatHandler
from src.notes_manager import NotesManager
from src.bjj_reference import (
get_all_positions,
get_all_concepts,
search_techniques,
BJJ_TECHNIQUES
)
class BJJNotebook:
"""Main application class for BJJ Notebook."""
def __init__(self):
"""Initialize the application."""
self.chat_handler = None
self.notes_manager = NotesManager()
self.running = True
def initialize_chat(self):
"""Initialize OpenAI chat handler."""
if self.chat_handler is None:
try:
self.chat_handler = BJJChatHandler()
print("β OpenAI chat initialized successfully!\n")
return True
except Exception as e:
print(f"β Error initializing chat: {e}")
print("You can still use the reference and notes features.\n")
return False
return True
def display_menu(self):
"""Display the main menu."""
print("\n" + "="*60)
print("BJJ NOTEBOOK - Your Brazilian Jiu-Jitsu Assistant")
print("="*60)
print("\nπ Main Menu:")
print(" 1. Chat with BJJ Assistant (OpenAI)")
print(" 2. Browse BJJ Reference")
print(" 3. Manage Notes")
print(" 4. Search Techniques")
print(" 5. Exit")
print()
def chat_menu(self):
"""Handle chat interactions."""
if not self.initialize_chat():
return
print("\n㪠Chat with BJJ Assistant")
print("-" * 60)
print("Ask questions about BJJ techniques, positions, or concepts.")
print("Type 'back' to return to main menu")
print("Type 'save' to save conversation as a note")
print("Type 'clear' to start a new conversation")
print("-" * 60)
while True:
user_input = input("\nYou: ").strip()
if not user_input:
continue
if user_input.lower() == 'back':
break
if user_input.lower() == 'save':
conversation = self.chat_handler.export_conversation()
note_id = self.notes_manager.save_conversation(conversation)
print(f"β Conversation saved as note: {note_id}")
continue
if user_input.lower() == 'clear':
self.chat_handler.clear_history()
print("β Conversation cleared. Starting fresh!")
continue
# Get response from AI
print("\nBJJ Assistant: ", end="", flush=True)
response = self.chat_handler.chat(user_input)
print(response)
def reference_menu(self):
"""Browse BJJ reference information."""
while True:
print("\nπ BJJ Reference")
print("-" * 60)
print(" 1. View Positions")
print(" 2. View Key Concepts")
print(" 3. View Techniques by Category")
print(" 4. Back to Main Menu")
print()
choice = input("Select option: ").strip()
if choice == '1':
self.show_positions()
elif choice == '2':
self.show_concepts()
elif choice == '3':
self.show_techniques()
elif choice == '4':
break
def show_positions(self):
"""Display BJJ positions."""
positions = get_all_positions()
print("\nπ₯ BJJ Positions:")
print("-" * 60)
for key, pos in positions.items():
print(f"\n{pos['name']}:")
print(f" Description: {pos['description']}")
print(f" Types: {', '.join(pos['types'])}")
print(f" Key Concepts: {', '.join(pos['key_concepts'])}")
def show_concepts(self):
"""Display key BJJ concepts."""
concepts = get_all_concepts()
print("\nπ‘ Key BJJ Concepts:")
print("-" * 60)
for i, concept in enumerate(concepts, 1):
print(f" {i}. {concept}")
def show_techniques(self):
"""Display techniques by category."""
print("\nπ― Technique Categories:")
print("-" * 60)
print(" 1. Submissions")
print(" 2. Sweeps")
print(" 3. Passes")
print(" 4. Escapes")
print()
choice = input("Select category: ").strip()
if choice == '1':
self.show_submissions()
elif choice == '2':
self.show_category('sweeps')
elif choice == '3':
self.show_category('passes')
elif choice == '4':
self.show_category('escapes')
def show_submissions(self):
"""Display submissions."""
subs = BJJ_TECHNIQUES['submissions']
print("\nπ Submissions:")
print("-" * 60)
print("\nChokes:")
for tech in subs['chokes']:
print(f" β’ {tech['name']} (from {tech['position']})")
print("\nArmlocks:")
for tech in subs['armlocks']:
print(f" β’ {tech['name']} (from {tech['position']})")
print("\nLeglocks:")
for tech in subs['leglocks']:
print(f" β’ {tech['name']}")
def show_category(self, category):
"""Display techniques from a category."""
techniques = BJJ_TECHNIQUES.get(category, [])
print(f"\nπ― {category.title()}:")
print("-" * 60)
for tech in techniques:
if 'from_position' in tech:
print(f" β’ {tech['name']} (from {tech['from_position']})")
elif 'type' in tech:
print(f" β’ {tech['name']} ({tech['type']})")
else:
print(f" β’ {tech['name']}")
def notes_menu(self):
"""Manage notes."""
while True:
print("\nπ Notes Management")
print("-" * 60)
print(" 1. Create New Note")
print(" 2. List All Notes")
print(" 3. View Note")
print(" 4. Search Notes")
print(" 5. Delete Note")
print(" 6. Back to Main Menu")
print()
choice = input("Select option: ").strip()
if choice == '1':
self.create_note()
elif choice == '2':
self.list_notes()
elif choice == '3':
self.view_note()
elif choice == '4':
self.search_notes()
elif choice == '5':
self.delete_note()
elif choice == '6':
break
def create_note(self):
"""Create a new note."""
print("\nπ Create New Note")
print("-" * 60)
title = input("Note title: ").strip()
if not title:
print("β Title cannot be empty")
return
print("Enter note content (press Enter twice to finish):")
lines = []
empty_count = 0
while empty_count < 2:
line = input()
if line:
lines.append(line)
empty_count = 0
else:
empty_count += 1
content = "\n".join(lines).strip()
if not content:
print("β Content cannot be empty")
return
category_input = input("Category (general/technique/training/competition/concept): ").strip()
category = category_input if category_input else "general"
tags_input = input("Tags (comma-separated, optional): ").strip()
tags = [tag.strip() for tag in tags_input.split(',')] if tags_input else []
try:
note_id = self.notes_manager.save_note(title, content, tags, category)
print(f"β Note saved successfully! ID: {note_id}")
except Exception as e:
print(f"β Error saving note: {e}")
def list_notes(self):
"""List all notes."""
notes = self.notes_manager.list_notes()
if not notes:
print("\nπ No notes found.")
return
print(f"\nπ All Notes ({len(notes)}):")
print("-" * 60)
for note in notes:
category_str = f" π {note.get('category', 'general')}"
tags_str = f" [{', '.join(note['tags'])}]" if note['tags'] else ""
print(f" β’ {note['title']}{category_str}{tags_str}")
print(f" ID: {note['id']}")
print(f" Created: {note['created_at'][:10]}")
print()
def view_note(self):
"""View a specific note."""
note_id = input("\nEnter note ID: ").strip()
try:
note = self.notes_manager.get_note(note_id)
if not note:
print("β Note not found")
return
print(f"\nπ {note['title']}")
print("-" * 60)
print(f"Created: {note['created_at']}")
print(f"Updated: {note['updated_at']}")
print(f"Category: {note.get('category', 'general')}")
if note.get('tags'):
print(f"Tags: {', '.join(note['tags'])}")
print("\nContent:")
print(note['content'])
print("-" * 60)
# Show related notes
related_notes = self.notes_manager.get_related_notes(note_id)
if related_notes:
print("\nπ Related Notes:")
for related in related_notes[:5]: # Show up to 5 related notes
print(f" β’ {related['title']} (Category: {related['category']})")
if related.get('common_tags'):
print(f" Common tags: {', '.join(related['common_tags'])}")
print()
except Exception as e:
print(f"β Error viewing note: {e}")
def search_notes(self):
"""Search notes."""
query = input("\nSearch query: ").strip()
if not query:
print("β Search query cannot be empty")
return
results = self.notes_manager.search_notes(query)
if not results:
print(f"\nπ No notes found matching '{query}'")
return
print(f"\nπ Search Results ({len(results)}):")
print("-" * 60)
for note in results:
print(f" β’ {note['title']}")
print(f" ID: {note['id']}")
print()
def delete_note(self):
"""Delete a note."""
note_id = input("\nEnter note ID to delete: ").strip()
confirm = input(f"Are you sure you want to delete '{note_id}'? (yes/no): ").strip().lower()
if confirm != 'yes':
print("β Deletion cancelled")
return
try:
self.notes_manager.delete_note(note_id)
print("β Note deleted successfully")
except Exception as e:
print(f"β Error deleting note: {e}")
def search_techniques_menu(self):
"""Search for techniques."""
print("\nπ Search Techniques")
print("-" * 60)
query = input("Enter technique name to search: ").strip()
if not query:
print("β Search query cannot be empty")
return
results = search_techniques(query)
if not results:
print(f"\nβ No techniques found matching '{query}'")
return
print(f"\nπ― Search Results ({len(results)}):")
print("-" * 60)
for tech in results:
print(f"\n β’ {tech['name']}")
print(f" Category: {tech['category']}")
if 'sub_category' in tech:
print(f" Type: {tech['sub_category']}")
if 'position' in tech:
print(f" From: {tech['position']}")
if 'type' in tech and tech['category'] != 'submissions':
print(f" Type: {tech['type']}")
def run(self):
"""Run the main application loop."""
print("\nπ₯ Welcome to BJJ Notebook!")
# Check if .env file exists
if not os.path.exists('.env'):
print("\nβ οΈ Warning: No .env file found.")
print("To use the OpenAI chat feature, create a .env file with your API key.")
print("See .env.example for reference.\n")
while self.running:
self.display_menu()
choice = input("Select option: ").strip()
if choice == '1':
self.chat_menu()
elif choice == '2':
self.reference_menu()
elif choice == '3':
self.notes_menu()
elif choice == '4':
self.search_techniques_menu()
elif choice == '5':
print("\nπ Thank you for using BJJ Notebook! Train hard!")
self.running = False
else:
print("\nβ Invalid option. Please try again.")
def main():
"""Main entry point."""
try:
app = BJJNotebook()
app.run()
except KeyboardInterrupt:
print("\n\nπ Goodbye!")
sys.exit(0)
except Exception as e:
print(f"\nβ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()