-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
516 lines (418 loc) · 18 KB
/
Copy pathutils.py
File metadata and controls
516 lines (418 loc) · 18 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
"""Shared utility functions for Pytalon."""
import io
import sys
import difflib
from config import FILLER_WORDS, NEGATION_WORDS, COMMON_SHORT_WORDS, COMMAND_PREFIXES
# ========== NEGATION HANDLING ==========
_SINGLE_NEGATIONS = {w for w in NEGATION_WORDS if " " not in w}
_MULTI_NEGATIONS = {p for p in NEGATION_WORDS if " " in p}
# ------- Helper function to detect negation cues in text -------
def _text_has_negation(text):
"""True if text contains an explicit negation cue."""
lowered = text.lower()
words = set(lowered.split())
if words & _SINGLE_NEGATIONS:
return True
return any(phrase in lowered for phrase in _MULTI_NEGATIONS)
# ------- Helper function to adjust similarity score based on negation cues -------
def _apply_negation_cap(score, user_text, reference_text):
"""Lower score when the reference is negative but the user did not negate."""
if _text_has_negation(reference_text) and not _text_has_negation(user_text):
return min(score, 0.5)
return score
# ========== UTILITY FUNCTIONS ==========
# These functions provide common utilities used across the Pytalon
# Global Separator Function
def print_global_separator():
"""Prints a visual separator line for better readability"""
global_separator = "\n" + "="*50
print(global_separator, flush=True)
# CODE PRACTICE SYSTEM Helper Functions
# ===== Step 1: Get multiline code input from the user =====
def get_multiline_code_input():
"""
Gets multiple lines of Python code from the user.
User types code line by line, then types 'DONE' to finish.
- String containing all the code lines joined together
- Validates stdin is available before attempting input
"""
# ----check if stdin is available or not ----
if sys.stdin.closed:
print("⚠️ Input stream is closed. Restarting practice session...", flush=True)
return ""
print("\n📝 ENTER YOUR PYTHON CODE (type 'DONE' on a new line when finished):", flush=True)
print_global_separator()
code_lines = []
try:
while True:
line = input()
# Check if user wants to stop entering code
if line.strip().upper() == 'DONE':
break
code_lines.append(line)
except EOFError:
print("\n⚠️ It's not your fault input ended unexpectedly, using entered code...", flush=True)
# Return whatever was entered so far
# Join all lines with newline characters
return "\n".join(code_lines)
# ===== Step 2: Execute code and check for expected/forbidden keywords =====
def execute_and_check_code(code, expected_keywords=None, forbidden_keywords=None):
"""
Safely executes the user's Python code and checks for required elements.
Parameters:
code: The Python code string to execute
expected_keywords: List of keywords that MUST be in the code
forbidden_keywords: List of keywords that must NOT be in the code
Returns:
(success, output, error_message)
- success: True if code ran correctly and passed all checks
- output: What the code printed (if anything)
- error_message: Description of any problems found
"""
success = True
error_message = ""
output = ""
# ---- BLOCK INFINITE LOOPS (before stdout redirect) ----
# Check for common infinite loop patterns (best-effort detection)
# Note: Variable-based loops may still bypass this check
infinite_loop_patterns = [
'while True',
'while 1',
'while(True)',
'while(1)',
'while (True)',
'while (1)',
'while 1==1',
'while 1 == 1',
]
code_lower = code.lower()
detected_pattern = None
for pattern in infinite_loop_patterns:
if pattern.lower() in code_lower:
detected_pattern = pattern
break
if detected_pattern:
success = False
error_message = f"⚠️ Infinite loops are not allowed in practice mode (detected: {detected_pattern})"
return success, output, error_message
# ---- SETUP: Capture printed output ----
old_stdout = sys.stdout
sys.stdout = captured_output = io.StringIO()
try:
# ---- Namespace with exit/quit blocked ----
# This prevents users from calling exit() or quit() in their code
def _blocked_exit(*args, **kwargs):
raise Exception("exit() is not allowed in practice exercises")
def _blocked_quit(*args, **kwargs):
raise Exception("quit() is not allowed in practice exercises")
namespace = {
'exit': _blocked_exit,
'quit': _blocked_quit,
}
# ---- EXECUTE: Run the code in isolated namespace ----
exec(code, namespace)
output = captured_output.getvalue()
# ---- CHECK: Verify expected keywords are present ----
if expected_keywords:
# Find which expected keywords are missing
missing_keywords = [
kw for kw in expected_keywords
if kw.lower() not in code.lower()
]
if missing_keywords:
success = False
error_message = f"Missing required elements: {', '.join(missing_keywords)}"
# ---- CHECK: Verify forbidden keywords are absent ----
if forbidden_keywords:
# Find which forbidden keywords were used
found_forbidden = [
kw for kw in forbidden_keywords
if kw.lower() in code.lower()
]
if found_forbidden:
success = False
error_message = f"Please don't use: {', '.join(found_forbidden)}"
except SyntaxError as e:
success = False
error_message = f"Syntax Error: {str(e)}"
except SystemExit:
success = False
error_message = "⚠️ Code attempted to exit. Please don't use exit() in practice."
except Exception as e:
success = False
error_message = f"Error: {str(e)}"
finally:
# ---- CLEANUP: Restore normal output and close StringIO ----
sys.stdout = old_stdout
# ---- Explicitly close the StringIO to prevent I/O state corruption ----
captured_output.close()
return success, output, error_message
# ===== Step 3: Main practice session flow =====
def run_practice_session(topic_name, instructions, expected_keywords, example_code, custom_check_function=None):
"""
Runs a complete interactive practice session for a specific topic.
Flow:
1. Shows instructions and example
2. Gets user's code
3. Executes and validates the code
4. If correct: shows success message
5. If wrong: shows error, lets user try again
Parameters:
topic_name: Display name of the topic (e.g., "Variables")
instructions: What the user needs to do
expected_keywords: Keywords that must appear in the code
example_code: A working example to show the user
custom_check_function: Optional extra validation function
"""
# ---- SUB STEP 1: Show practice header and instructions ----
print_global_separator()
print(f"🧪 INTERACTIVE PRACTICE: {topic_name}", flush=True)
print_global_separator()
print(f"\n📋 TASK:", flush=True)
print(instructions, flush=True)
print(f"\n💡 EXAMPLE SOLUTION:", flush=True)
print(f"{example_code}", flush=True)
print(f"\n🔑 Required elements: {', '.join(expected_keywords)}", flush=True)
# ---- SUB STEP 2: Main practice loop with attempt limit ----
attempts = 0
MAX_ATTEMPTS = 3
while True:
# Get user's code attempt
user_code = get_multiline_code_input()
# Check for empty submission
if not user_code.strip():
print("⚠️ Please enter some Python code!", flush=True)
continue
# Execute the code and check for basic requirements
success, output, error_message = execute_and_check_code(
user_code,
expected_keywords=expected_keywords
)
# Run custom validation if provided (for topic-specific checks)
if success and custom_check_function:
success, error_message = custom_check_function(user_code, output)
# ---- SUB STEP 3: Show results ----
if success:
print_global_separator()
print("✅ PERFECT! Your code is correct!", flush=True)
if output:
print(f"\n📤 YOUR OUTPUT:", flush=True)
print(output, flush=True)
print(f"\n💡 Code structure and elements are correct!", flush=True)
print("✅ Practice complete! You can continue to the next topic.", flush=True)
print_global_separator()
break
else:
attempts += 1
print_global_separator()
print(f"❌ Not quite right! {error_message}", flush=True)
if attempts >= MAX_ATTEMPTS:
from validators import get_global_valid_input
retry = get_global_valid_input("\n🔹 You've tried several times. Try again? (yes/no): ")
if retry == 'yes':
attempts = 0
continue
elif retry == 'exit':
print("👋 Exiting practice session. See you next time!", flush=True)
break
else: # retry == 'no'
print("✅ Skipping practice. You can always come back later!", flush=True)
break
else:
print(f"\n🔄 Attempt {attempts}/{MAX_ATTEMPTS}. Please try again!", flush=True)
print_global_separator()
# ========= MENU DISPLAY FUNCTION ==========
def show_topic_menu(topics, prompt="Which topic would you like to start with?"):
"""
Displays the full topic list and returns the chosen number (string) or 'exit'.
"""
from validators import get_global_menu_choice # Imported here to avoid circular dependency
print_global_separator()
print("I can teach you Python basics! Here are the topics:", flush=True)
print_global_separator()
for num, topic in topics.items():
print(f" {num}. {topic}", flush=True)
choice = get_global_menu_choice(
f"\n🔹 {prompt} (1-13/exit): ",
1,
len(topics)
)
return choice
# ========= Helper: Smart Detection Function ==========
# Smart Detection Function for detecting the users intent during the conservation.
def smart_detection(s1, s2):
"""
Compares two strings and returns a similarity score between 0 and 1.
Checks for:
- Sub‑string containment
- Full‑string similarity
- Each word of s1 against s2 and vice‑versa
- Word‑order reversal
- All words of one string present in the other (subset match)
"""
if not s1 or not s2:
return 0.0
s1 = s1.lower().strip()
s2 = s2.lower().strip()
# Direct containment
if s1 in s2 or s2 in s1:
return 1.0
# --- New check: all words of s2 appear in s1 (or vice‑versa) ---
words1 = set(s1.split())
words2 = set(s2.split())
if words2 and words2.issubset(words1):
# All keywords are present in the user's topic phrase → strong match
return 1.0
if words1 and words1.issubset(words2):
return 1.0
# ----------------------------------------------------------------
# Full‑string comparison
best = difflib.SequenceMatcher(None, s1, s2).ratio()
# Word‑by‑word comparisons
for word in s1.split():
score = difflib.SequenceMatcher(None, word, s2).ratio()
if score > best:
best = score
for word in s2.split():
score = difflib.SequenceMatcher(None, word, s1).ratio()
if score > best:
best = score
# Handle swapped word order
if " " in s2:
reversed_s2 = " ".join(reversed(s2.split()))
score = difflib.SequenceMatcher(None, s1, reversed_s2).ratio()
if score > best:
best = score
return best
# Smart Validations for the Validators to detect the users intent during the conservation.
def smart_validators(s1, s2, w1, w2):
"""
Validates the user's input based on smart detection logic.
Parameters:
- s1: User's input string
- s2: Reference string to compare against
- w1: Extracted keywords from user's input
- w2: Extracted keywords from reference string
Returns:
- A similarity score between 0 and 1, with adjustments for negation cues.
The function performs multiple checks:
1. Direct containment of one string in the other.
2. Subset match where all keywords of one string are present in the other.
3. Full-string similarity using difflib.
4. Word-by-word comparisons for both the main strings and the keywords.
5. Handling of swapped word order.
6. Adjusting the final score if negation cues are detected in the reference string but not in the user's input,
to prevent false positives in cases of negation.
"""
s1 = s1.lower().strip()
s2 = s2.lower().strip()
w1 = w1.lower().strip()
w2 = w2.lower().strip()
# Extract keywords and filter out common short words to prevent false positives
s1_clean = {w for w in _extract_keywords(s1).split() if w not in COMMON_SHORT_WORDS}
s2_clean = {w for w in _extract_keywords(s2).split() if w not in COMMON_SHORT_WORDS}
w1_words = {w for w in w1.split() if w not in COMMON_SHORT_WORDS}
w2_words = {w for w in w2.split() if w not in COMMON_SHORT_WORDS}
min_overlap = 2
overlap1 = len(s1_clean & s2_clean)
overlap2 = len(w1_words & w2_words)
overlap3 = len(s1_clean & w2_words)
overlap4 = len(w1_words & s2_clean)
# Strong match requires min_overlap=2 in both main strings AND keyword sets
if (overlap1 >= min_overlap or overlap2 >= min_overlap) and (overlap3 >= min_overlap or overlap4 >= min_overlap):
return _apply_negation_cap(1.0, s1, s2)
# Weaker match with at least 1 overlap in each (but not common short words)
if (overlap1 >= 1 or overlap2 >= 1) and (overlap3 >= 1 or overlap4 >= 1):
return _apply_negation_cap(0.5, s1, s2)
# ----------------------------------------------------------------
# Full‑string comparison
best = difflib.SequenceMatcher(None, s1, s2).ratio()
# Word‑by‑word comparisons
for word in s1.split():
score = difflib.SequenceMatcher(None, word, s2).ratio()
if score > best:
best = score
for word in s2.split():
score = difflib.SequenceMatcher(None, word, s1).ratio()
if score > best:
best = score
# String-by-string comparisons for keywords
for word_w1 in w1.split():
score = difflib.SequenceMatcher(None, word_w1, w2).ratio()
if score > best:
best = score
for word_w2 in w2.split():
score = difflib.SequenceMatcher(None, word_w2, w1).ratio()
if score > best:
best = score
# Handle swapped word order for both the main strings and the keywords
if " " in s2:
reversed_s2 = " ".join(reversed(s2.split()))
score = difflib.SequenceMatcher(None, s1, reversed_s2).ratio()
if score > best:
best = score
if " " in w2:
reversed_w2 = " ".join(reversed(w2.split()))
score = difflib.SequenceMatcher(None, s1, reversed_w2).ratio()
if score > best:
best = score
return _apply_negation_cap(best, s1, s2)
# ========== HELPER: Extract intent keywords from a string ==========
def _extract_keywords(text):
"""
Extracts the most intent-carrying words from a string.
Strips common filler words and punctuation so smart_validators
gets meaningful w1/w2.
Returns a string of the remaining words joined by spaces.
"""
# Convert to lowercase and strip whitespace
text = text.lower().strip()
# Remove common punctuation by keeping only alphanumeric, spaces, and apostrophes
# This handles contractions like "don't", "I'm", etc.
cleaned_chars = []
for char in text:
if char.isalnum() or char.isspace() or char == "'":
cleaned_chars.append(char)
else:
# Replace punctuation with space to separate words
cleaned_chars.append(' ')
cleaned = ''.join(cleaned_chars)
# Split into words and filter out filler words
words = cleaned.split()
keywords = [w for w in words if w not in FILLER_WORDS]
return ' '.join(keywords) if keywords else cleaned
# ========== HELPER: Remove command-style prefixes from user input ==========
def remove_command_prefix(text):
"""
Remove command-style prefixes from user input.
Handles cases like: /lists, !functions, #variables, \\loops, etc.
This function checks if the first character is a command prefix
and removes it along with any following whitespace.
Uses COMMAND_PREFIXES from config.py for maintainability.
Custom implementation without using lstrip() or strip().
Args:
text: The input text to clean
Returns:
Text with leading command prefix removed if present
"""
# Handle empty or single-character input
if not text or len(text) <= 1:
return text
# Check if first character is a command prefix
first_char = text[0]
is_command_prefix = False
for prefix in COMMAND_PREFIXES:
if first_char == prefix:
is_command_prefix = True
break
# If not a command prefix, return original text
if not is_command_prefix:
return text
# Remove the prefix character
cleaned = text[1:]
# Remove leading whitespace manually (custom implementation)
start_index = 0
while start_index < len(cleaned) and cleaned[start_index] == ' ':
start_index += 1
# Return the text with prefix and leading spaces removed
return cleaned[start_index:] if start_index < len(cleaned) else cleaned