-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvicky_server.py
More file actions
13483 lines (11240 loc) · 553 KB
/
vicky_server.py
File metadata and controls
13483 lines (11240 loc) · 553 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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import re
import sys
import pytz
import time
import importlib.util
import io
from datetime import datetime
from collections import defaultdict
import gzip
import re
import urllib.parse
import os
import requests
import shutil
import random
import gzip
import numpy as np
import base64
import tempfile
# Add this import at the top of vicky_server.py with other imports
from difflib import SequenceMatcher
import traceback
from contextlib import redirect_stdout
from typing import Dict, List, Optional, Any, Union, Tuple
# File paths
VICKYS_JSON = "E:/data science tool/main/grok/vickys.json"
BASE_PATH = "E:/data science tool"
# Load the questions database
with open(VICKYS_JSON, "r", encoding="utf-8") as f:
QUESTIONS_DATA = json.load(f)
def check_existing_tunnels():
"""Check if there are already running ngrok tunnels and return the existing URL if found"""
try:
response = requests.get("http://localhost:4040/api/tunnels")
if response.status_code == 200:
print("⚠️ Existing ngrok tunnel detected. Free tier only allows one tunnel.")
tunnels = response.json().get("tunnels", [])
if tunnels:
for tunnel in tunnels:
if tunnel["proto"] == "https":
public_url = tunnel["public_url"]
print(f"✅ Using existing tunnel: {public_url}")
return public_url
return None
except:
# No existing tunnels or API not accessible
return None
# Process questions to create a searchable structure
PROCESSED_QUESTIONS = []
def classify_domain(query_text):
"""Classify query into primary domain for better matching"""
query_lower = query_text.lower()
# Domain indicators with weighted terms (more specific terms get higher weights)
domain_indicators = {
"vscode": {"code -": 5, "visual studio code": 4, "vscode": 3, "-v": 2, "-h": 2, "--version": 3, "--help": 3},
"github": {"github pages": 5, "github action": 5, "github search": 5, "github": 3, "repository": 2},
"excel": {"excel data": 5, "clean excel": 5, "excel": 3, "sales data": 3, "margin": 2},
"vercel": {"vercel deploy": 5, "vercel api": 5, "vercel": 4},
"openai": {"openai api": 5, "embeddings": 4, "completion": 3, "openai": 3},
"llamafile": {"ngrok": 5, "tunnel": 4, "llamafile": 5, "llama-3.2": 5,
"free.app": 3, "ngrok-free.app": 5}
}
domain_scores = {}
# Calculate weighted score for each domain
for domain, indicators in domain_indicators.items():
score = 0
for term, weight in indicators.items():
if term in query_lower:
score += weight
if score > 0:
domain_scores[domain] = score
# Return the domain with the highest score, or None if no matches
if domain_scores:
return max(domain_scores.items(), key=lambda x: x[1])[0]
return None
def debug_matching(query):
"""Print debug information about why a query matched a specific question"""
print("\n=== DEBUG MATCH INFORMATION ===")
print(f"Query: {query[:50]}..." if len(query) > 50 else f"Query: {query}")
# Extract base features
query_lower = query.lower()
domain = classify_domain(query)
print(f"Classified domain: {domain}")
# Extract patterns from query
detected_patterns = []
for pattern_name, pattern_regex in [
("code_command", r'code\s+(-[a-z]+|--[a-z]+)'),
("github_pages", r'github\s+pages|showcase|email_off'),
("github_action", r'github\s+action|workflow|yml|steps:|run:'),
("github_search", r'github\s+search|location:|followers:|sort by'),
("vercel", r'vercel|deploy|api\?name='),
("excel", r'excel\s+data|clean.*excel|margin\s+for')
]:
if re.search(pattern_regex, query_lower):
detected_patterns.append(pattern_name)
print(f"Detected patterns: {detected_patterns}")
# Calculate match scores for top candidates
scores = []
for question in PROCESSED_QUESTIONS:
base_score = similarity_score(query, question["text"])
pattern_match = 0
for pattern in detected_patterns:
if question["patterns"].get(pattern, False):
pattern_match += 1
domain_match = 1 if question.get("domain") == domain else 0
# Calculate weighted score
final_score = (base_score * 0.5) + (pattern_match * 0.3 / max(1, len(detected_patterns))) + (domain_match * 0.2)
scores.append((question["file_path"], final_score, base_score, pattern_match, domain_match))
# Show top matches
scores.sort(key=lambda x: x[1], reverse=True)
print("\nTop 3 matches:")
for i, (file_path, score, base_score, pattern_match, domain_match) in enumerate(scores[:3]):
print(f"{i+1}. {file_path}")
print(f" - Total score: {score:.2f}")
print(f" - Text similarity: {base_score:.2f}")
print(f" - Pattern matches: {pattern_match}")
print(f" - Domain match: {'Yes' if domain_match else 'No'}")
print("===========================\n")
# Enhanced question processing with more attributes
for idx, question_data in enumerate(QUESTIONS_DATA):
if "question" in question_data:
question_text = question_data["question"]
file_path = question_data.get("file", "")
# Extract file category (GA1, GA2, etc.)
file_category = None
if file_path:
category_match = re.search(r'GA(\d+)', file_path)
if category_match:
file_category = f"GA{category_match.group(1)}"
# Extract sequence number from file path
sequence_number = None
if file_path:
sequence_match = re.search(r'([a-z]+)\.py$', file_path)
if sequence_match:
sequence_number = sequence_match.group(1)
# Get domain classification
domain = classify_domain(question_text)
# Extract key phrases and indicators from the question
keywords = set(re.findall(r'\b\w+\b', question_text.lower()))
# Add this right after your existing pattern definitions, near line 147
# Distinctive patterns dictionary for specific question files
DISTINCTIVE_PATTERNS = {
# VS Code related patterns
"GA1/first.py": ["code -", "code -s", "code --version", "visual studio code terminal", "command prompt"],
"GA1/second.py": ["httpie", "httpbin.org", "uv run", "https request", "url encoded parameter"],
# GitHub related patterns
"GA2/third.py": ["github pages", "showcase", "email_off", "cloudflare", "obfuscates"],
"GA2/seventh.py": ["github action", "workflow", "steps:", "run:", "trigger", "jobs:"],
"GA5/third.py": ["github search", "location:", "followers:", "sort by joined", "newest user"],
"GA1/thirteenth.py": ["github account", "repository", "commit", "json file", "raw github url"],
# Vercel related patterns
"GA2/sixth.py": ["vercel", "deploy", "api?name=", "marks", "json response"],
# File processing patterns
"GA1/eighth.py": ["extract-csv-zip", "extract.csv", "unzip", "answer column"],
"GA1/twelfth.py": ["unicode-data", "encodings", "cp-1252", "utf-8", "utf-16", "symbol matches"],
"GA5/tenth.py": ["jigsaw", "image pieces", "mapping file", "reconstruct", "original position"],
# Excel processing patterns
"GA5/first.py": ["clean excel", "sales data", "margin", "product filter", "zeta", "country filter"],
# Image processing patterns
"GA2/second.py": ["compress", "lossless", "image", "1,500 bytes", "vicky.png"],
"GA2/fifth.py": ["colab", "image", "brightness", "minimum lightness", "lenna.webp"],
# Ngrok and Llamafile patterns
"GA2/tenth.py": ["ngrok", "llamafile", "tunnel", "llama-3.2", "free.app",
"ngrok-free.app", "llama", "llamafile server", "Llama-3.2-1B-Instruct"]
}
# Special patterns to detect (expand this based on your questions)
patterns = {
"code_command": bool(re.search(r'code\s+(-[a-z]+|--[a-z]+)', question_text.lower())),
"email": bool(re.search(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', question_text)),
"date_range": bool(re.search(r'(\d{4}[-/]\d{1,2}[-/]\d{1,2})\s+to\s+(\d{4}[-/]\d{1,2}[-/]\d{1,2})', question_text)),
"pdf_extraction": bool(re.search(r'pdf|extract|table|marks|physics|maths', question_text.lower())),
"github_pages": bool(re.search(r'github\s+pages|showcase|email_off', question_text.lower())),
"github_action": bool(re.search(r'github\s+action|workflow|yml|steps:|run:', question_text.lower())),
"github_search": bool(re.search(r'github\s+search|location:|followers:|sort by', question_text.lower())),
"vercel": bool(re.search(r'vercel|deploy|api\?name=|students\.json', question_text.lower())),
"hidden_input": bool(re.search(r'hidden\s+input|secret\s+value', question_text.lower())),
"sql_query": bool(re.search(r'sql|query|select|from|where', question_text.lower())),
"weekdays": bool(re.search(r'monday|tuesday|wednesday|thursday|friday|saturday|sunday', question_text.lower())),
}
# Store processed question data
PROCESSED_QUESTIONS.append({
"id": idx,
"text": question_text,
"file_path": file_path,
"file_category": file_category,
"sequence_number": sequence_number,
"domain": domain,
"keywords": keywords,
"patterns": patterns,
"original": question_data
})
def classify_domain(query_text):
"""Classify query into primary domain for better matching"""
query_lower = query_text.lower()
# Domain indicators with weighted terms (more specific terms get higher weights)
domain_indicators = {
"vscode": {"code -": 5, "visual studio code": 4, "vscode": 3, "-v": 2, "-h": 2, "--version": 3, "--help": 3},
"github": {"github pages": 5, "github action": 5, "github search": 5, "github": 3, "repository": 2},
"excel": {"excel data": 5, "clean excel": 5, "excel": 3, "sales data": 3, "margin": 2},
"vercel": {"vercel deploy": 5, "vercel api": 5, "vercel": 4},
"openai": {"openai api": 5, "embeddings": 4, "completion": 3, "openai": 3}
}
domain_scores = {}
# Calculate weighted score for each domain
for domain, indicators in domain_indicators.items():
score = 0
for term, weight in indicators.items():
if term in query_lower:
score += weight
if score > 0:
domain_scores[domain] = score
# Return the domain with the highest score, or None if no matches
if domain_scores:
return max(domain_scores.items(), key=lambda x: x[1])[0]
return None
def debug_matching(query):
"""Print debug information about why a query matched a specific question"""
print("\n=== DEBUG MATCH INFORMATION ===")
print(f"Query: {query[:50]}..." if len(query) > 50 else f"Query: {query}")
# Extract base features
query_lower = query.lower()
domain = classify_domain(query)
print(f"Classified domain: {domain}")
# Extract patterns from query
detected_patterns = []
for pattern_name, pattern_regex in [
("code_command", r'code\s+(-[a-z]+|--[a-z]+)'),
("github_pages", r'github\s+pages|showcase|email_off'),
("github_action", r'github\s+action|workflow|yml|steps:|run:'),
("github_search", r'github\s+search|location:|followers:|sort by'),
("vercel", r'vercel|deploy|api\?name='),
("excel", r'excel\s+data|clean.*excel|margin\s+for')
]:
if re.search(pattern_regex, query_lower):
detected_patterns.append(pattern_name)
print(f"Detected patterns: {detected_patterns}")
# Calculate match scores for top candidates
scores = []
for question in PROCESSED_QUESTIONS:
base_score = similarity_score(query, question["text"])
pattern_match = 0
for pattern in detected_patterns:
if question["patterns"].get(pattern, False):
pattern_match += 1
domain_match = 1 if question.get("domain") == domain else 0
# Calculate weighted score
final_score = (base_score * 0.5) + (pattern_match * 0.3 / max(1, len(detected_patterns))) + (domain_match * 0.2)
scores.append((question["file_path"], final_score, base_score, pattern_match, domain_match))
# Show top matches
scores.sort(key=lambda x: x[1], reverse=True)
print("\nTop 3 matches:")
for i, (file_path, score, base_score, pattern_match, domain_match) in enumerate(scores[:3]):
print(f"{i+1}. {file_path}")
print(f" - Total score: {score:.2f}")
print(f" - Text similarity: {base_score:.2f}")
print(f" - Pattern matches: {pattern_match}")
print(f" - Domain match: {'Yes' if domain_match else 'No'}")
print("===========================\n")
def normalize_text(text):
"""Normalize text for consistent matching"""
if not text:
return ""
# Convert to lowercase, normalize spaces, remove punctuation for matching
return re.sub(r'[^\w\s]', ' ', re.sub(r'\s+', ' ', text.lower())).strip()
def similarity_score(text1, text2):
"""Calculate text similarity between two strings"""
return SequenceMatcher(None, normalize_text(text1), normalize_text(text2)).ratio()
def match_command_variant(query):
"""Detect which command variant is being asked about"""
query_lower = query.lower()
# Match command flags explicitly
if re.search(r'code\s+(-v|--version)', query_lower) or "version" in query_lower:
return "code -v"
elif re.search(r'code\s+(-s|--status)', query_lower) or "status" in query_lower:
return "code -s"
# Default to code -s if no specific variant detected
return "code -s"
def is_vscode_command_query(query):
"""Determine if the query is specifically asking about a VS Code command"""
# Look for explicit VS Code command patterns
if not query:
return False
query_lower = query.lower()
command_patterns = [
r'\bcode\b\s+(-[a-z]\b|--[a-z-]+\b)', # Must have space and dash after "code"
r'output of\s+\bcode\b\s+(-[a-z]|--[a-z-]+)\b',
r'running\s+\bcode\b\s+(-[a-z]|--[a-z-]+)\b',
r'command\s+\bcode\b\s+(-[a-z]|--[a-z-]+)\b',
r'vs code\s+(-[a-z]|--[a-z-]+)\b',
r'vscode\s+(-[a-z]|--[a-z-]+)\b',
r'visual studio code\s+(-[a-z]|--[a-z-]+)\b' # command code -s
]
for pattern in command_patterns:
if re.search(pattern, query.lower()):
return True
explicit_command_phrases = [
'code command line', 'code -s', 'code -v', 'code -h',
'code --version', 'code --help', 'code --status',
'vs code command', 'vscode terminal command',
'visual studio code command line'
]
for phrase in explicit_command_phrases:
if phrase in query_lower:
return True
# Check for specific mentions of VS Code and command arguments
vs_code_indicators = ["visual studio code", "vs code", "vscode"]
command_args = ["-s", "-v", "-h", "--version", "--help", "--status"]
has_vs_code = any(indicator in query.lower() for indicator in vs_code_indicators)
has_command = any(arg in query.lower() for arg in command_args)
# The combination of VS Code mention + specific argument is a strong indicator
if has_vs_code and has_command:
return True
return False
def find_best_question_match(query: str) -> Optional[Dict]:
"""Find the best matching question using semantic matching with a hierarchical approach"""
normalized_query = normalize_text(query)
query_lower = query.lower()
# =========== STAGE 1: DIRECT CATEGORY DETECTION ===========
# These are high-confidence pattern detections that should take precedence
# Direct ngrok pattern detection (highest priority)
if any(term in query_lower for term in ["ngrok", "llamafile", "llama-3.2", "tunnel", "ngrok-free.app"]):
print("Direct match: Ngrok/Llamafile query → GA2/tenth.py")
for question in QUESTIONS_DATA:
if 'file' in question and question['file'].endswith("GA2/tenth.py"):
return question
# VS Code commands detection
if is_vscode_command_query(query):
print("Direct match: VS Code command query → GA1/first.py")
for question in QUESTIONS_DATA:
if 'file' in question and question['file'].endswith("GA1/first.py"):
return question
# GitHub-related category detection
if 'github' in query_lower:
if ('location:' in query_lower or 'followers:' in query_lower or
'sort by joined' in query_lower or 'newest user' in query_lower):
print("Direct match: GitHub search query → GA5/third.py")
for question in QUESTIONS_DATA:
if 'file' in question and "GA5/third.py" in question['file']:
return question
elif 'github pages' in query_lower or 'showcase' in query_lower or 'email_off' in query_lower:
print("Direct match: GitHub Pages query → GA2/third.py")
for question in QUESTIONS_DATA:
if 'file' in question and "GA2/third.py" in question['file']:
return question
elif 'action' in query_lower and ('workflow' in query_lower or 'trigger' in query_lower):
print("Direct match: GitHub Action query → GA2/seventh.py")
for question in QUESTIONS_DATA:
if 'file' in question and "GA2/seventh.py" in question['file']:
return question
# Vercel deployment detection
if ('vercel' in query_lower and ('deploy' in query_lower or 'api?name=' in query_lower)) or 'marks of the names' in query_lower:
print("Direct match: Vercel deployment query → GA2/sixth.py")
for question in QUESTIONS_DATA:
if 'file' in question and "GA2/sixth.py" in question['file']:
return question
# Excel analysis detection
if 'clean' in query_lower and 'excel' in query_lower and ('margin' in query_lower or 'sales' in query_lower):
print("Direct match: Excel data cleaning query → GA5/first.py")
for question in QUESTIONS_DATA:
if 'file' in question and "GA5/first.py" in question['file']:
return question
# Special file pattern detection
file_patterns = {
"unicode-data.zip": "GA1/twelfth.py",
"mutli-cursor-json": "GA1/tenth.py",
"multi-cursor-json": "GA1/tenth.py",
"extract-csv-zip": "GA1/eighth.py",
"extract.csv": "GA1/eighth.py",
"compare-files": "GA1/seventeenth.py",
"replace-across-files": "GA1/fourteenth.py",
"jigsaw.webp": "GA5/tenth.py",
"tables-from-pdf": "GA4/ninth.py",
"pdf-to-markdown": "GA4/tenth.py"
}
for pattern, file_path in file_patterns.items():
if pattern in query_lower:
print(f"Direct file pattern match: {pattern} → {file_path}")
for question in QUESTIONS_DATA:
if 'file' in question and file_path in question['file']:
return question
# Check distinctive patterns for better matching
# query_lower = query.lower()
# best_match = None
# max_pattern_score = 0
# for file_path, distinctive_terms in DISTINCTIVE_PATTERNS.items():
# pattern_count = 0
# for term in distinctive_terms:
# if term.lower() in query_lower:
# pattern_count += 1
# if pattern_count > 0:
# Calculate a score based on percentage of matching patterns
# pattern_score = pattern_count / len(distinctive_terms)
# if pattern_score > max_pattern_score:
# max_pattern_score = pattern_score
# Find the matching question
# for question in QUESTIONS_DATA:
# if question.get('file', '').endswith(file_path):
# best_match = question
# break
# If we found a strong pattern match, return it
# if best_match and max_pattern_score > 0.4: # Threshold of 40% pattern match
# print(f"Strong distinctive pattern match found: {max_pattern_score:.2f}")
# return best_match
# =========== STAGE 2: DOMAIN CLASSIFICATION & WEIGHTED SCORING ===========
# Classify the query into domains, then apply domain-specific scoring
# Domain classification weights for better differentiation
domain_indicators = {
"vscode": ["code -", "visual studio code", "vscode", "--version", "--help", "-v", "-h"],
"github": ["github", "repository", "commit", "action", "pages"],
"excel": ["excel", "sales", "margin", "clean", "data"],
"colab": ["colab", "google", "notebook", "calculate", "pixels"],
"vercel": ["vercel", "deploy", "api", "marks", "students"],
"fastapi": ["fastapi", "api", "endpoint", "server"],
"file_processing": ["extract", "zip", "csv", "replace", "compare"],
"markdown": ["markdown", "heading", "bold", "italic", "hyperlink"],
"image": ["image", "compress", "lossless", "bytes", "pixel"],
"openai": ["openai", "api", "completion", "sentiment", "embedding"]
}
# Calculate domain scores
domain_scores = {}
for domain, indicators in domain_indicators.items():
score = sum(3 if indicator in query_lower else 0 for indicator in indicators)
if score > 0:
domain_scores[domain] = score
# Get primary domain (highest score)
primary_domain = max(domain_scores.items(), key=lambda x: x[1])[0] if domain_scores else None
print(f"Primary domain: {primary_domain}")
# Extract query patterns that may differentiate similar questions
query_patterns = {
"code_command": bool(re.search(r'code\s+(-[a-z]+|--[a-z]+)', query_lower) or "code -h" in query_lower),
"email": bool(re.search(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', query)),
"date_range": bool(re.search(r'(\d{4}[-/]\d{1,2}[-/]\d{1,2})\s+to\s+(\d{4}[-/]\d{1,2}[-/]\d{1,2})', query)),
"pdf_extraction": bool(re.search(r'pdf|extract|table|marks|physics|maths|students', query_lower)),
"github_pages": bool(re.search(r'github\s+pages|showcase|email_off', query_lower)),
"vercel": bool(re.search(r'vercel|deploy|api\?name=|students\.json', query_lower)),
"hidden_input": bool(re.search(r'hidden\s+input|secret\s+value', query_lower)),
"weekdays": bool(re.search(r'monday|tuesday|wednesday|thursday|friday|saturday|sunday', query_lower)),
"github_action": bool(re.search(r'github\s+action|workflow|yml|steps:|run:', query_lower)),
"github_search": bool(re.search(r'github\s+search|location:|followers:|sort by', query_lower)),
"image_compression": bool(re.search(r'compress\s+.*\s+image|lossless|bytes', query_lower)),
"pixel_counting": bool(re.search(r'pixel|lightness|brightness', query_lower)),
"file_extraction": bool(re.search(r'extract\s+.*\s+(zip|csv|file)|unzip', query_lower)),
"sql_query": bool(re.search(r'sql|query|select|from|where', query_lower))
}
# Get keywords from query
query_keywords = set(re.findall(r'\b\w+\b', query_lower))
best_score = 0
best_match = None
best_confidence = 0
for question in PROCESSED_QUESTIONS:
# Base similarity score (text comparison)
base_score = similarity_score(query, question["text"])
# Domain boost - strongly favor questions in the same domain
domain_boost = 0
file_path = question.get("file_path", "").lower()
# Add pattern matching score based on query indicators
pattern_score = 0
matching_patterns = 0
for pattern_name, has_pattern in query_patterns.items():
if has_pattern and question["patterns"].get(pattern_name, False):
pattern_score += 0.15
matching_patterns += 1
# Domain-based file path boost
if primary_domain == "vscode" and "GA1/first" in file_path:
domain_boost = 0.3
elif primary_domain == "github":
if "github_search" in query_patterns and query_patterns["github_search"] and "GA5/third" in file_path:
domain_boost = 0.4
elif "github_pages" in query_patterns and query_patterns["github_pages"] and "GA2/third" in file_path:
domain_boost = 0.4
elif "github_action" in query_patterns and query_patterns["github_action"] and "GA2/seventh" in file_path:
domain_boost = 0.4
elif "GA1/thirteenth" in file_path: # Simple GitHub repository
domain_boost = 0.2
elif primary_domain == "excel" and "GA5/first" in file_path:
domain_boost = 0.3
elif primary_domain == "vercel" and "GA2/sixth" in file_path:
domain_boost = 0.3
elif primary_domain == "fastapi" and ("GA2/ninth" in file_path or "GA3/seventh" in file_path):
domain_boost = 0.3
elif primary_domain == "file_processing" and any(x in file_path for x in ["eighth", "twelfth", "fourteenth", "seventeenth"]):
domain_boost = 0.3
elif primary_domain == "image" and ("GA2/second" in file_path or "GA2/fifth" in file_path):
domain_boost = 0.3
elif primary_domain == "openai" and "GA3" in file_path:
domain_boost = 0.25
# Keyword match score
keyword_overlap = len(query_keywords.intersection(question.get("keywords", set())))
keyword_score = min(0.1, keyword_overlap / 20) # Cap at 0.1
# Calculate final weighted score
final_score = (base_score * 0.4) + (pattern_score * 0.3) + (domain_boost * 0.2) + (keyword_score * 0.1)
# Calculate confidence level (for debugging)
confidence = min(100, int((final_score / 1.0) * 100))
if final_score > best_score:
best_score = final_score
best_match = question
best_confidence = confidence
if best_match and best_score > 0.35: # Minimum threshold
file_path = best_match.get("file_path", "unknown")
print(f"Best match: {file_path} (score: {best_score:.2f}, confidence: {best_confidence}%)")
return best_match["original"]
# Fallback for low-confidence matches - direct file path mapping
print("Low confidence match, trying explicit file path mapping...")
return None # No confident match found
# -------------------- SOLUTION FUNCTIONS --------------------
# Global file handling system for all solutions
class FileManager:
"""
Comprehensive file management system to handle files from all sources:
- Query references
- Uploaded files via TDS.py
- Different file types (images, PDFs, CSVs, etc.)
- Content-based identification for same-named files
"""
def __init__(self, base_directory="E:/data science tool"):
self.base_directory = base_directory
self.ga_folders = ["GA1", "GA2", "GA3", "GA4", "GA5"]
self.temp_dirs = [] # Track created temporary directories for cleanup
self.file_cache = {} # Cache for previously resolved files
self.supported_extensions = {
'image': ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp'],
'document': ['.pdf', '.docx', '.txt', '.md'],
'data': ['.csv', '.xlsx', '.json', '.xml'],
'archive': ['.zip', '.tar', '.gz', '.rar'],
'code': ['.py', '.js', '.html', '.css']
}
# File pattern by type for more accurate identification
self.file_patterns = {
'image': r'\.(png|jpg|jpeg|webp|gif|bmp)',
'document': r'\.(pdf|docx?|txt|md)',
'data': r'\.(csv|xlsx?|json|xml)',
'archive': r'\.(zip|tar|gz|rar)',
'code': r'\.(py|js|html|css|cpp|c|java)'
}
# Known files with their GA location and expected content signatures
self.known_files = {
# GA1 files
'q-extract-csv-zip.zip': {'folder': 'GA1', 'content_type': 'archive'},
'q-unicode-data.zip': {'folder': 'GA1', 'content_type': 'archive'},
'q-mutli-cursor-json.txt': {'folder': 'GA1', 'content_type': 'document'},
'q-compare-files.zip': {'folder': 'GA1', 'content_type': 'archive'},
'q-move-rename-files.zip': {'folder': 'GA1', 'content_type': 'archive'},
'q-list-files-attributes.zip': {'folder': 'GA1', 'content_type': 'archive'},
'q-replace-across-files.zip': {'folder': 'GA1', 'content_type': 'archive'},
# GA2 files
'lenna.png': {'folder': 'GA2', 'content_type': 'image'},
'lenna.webp': {'folder': 'GA2', 'content_type': 'image'},
'iit_madras.png': {'folder': 'GA2', 'content_type': 'image'},
'q-vercel-python.json': {'folder': 'GA2', 'content_type': 'data'},
'q-fastapi.csv': {'folder': 'GA2', 'content_type': 'data'},
# GA4 files
'q-extract-tables-from-pdf.pdf': {'folder': 'GA4', 'content_type': 'document'},
'q-pdf-to-markdown.pdf': {'folder': 'GA4', 'content_type': 'document'},
#GA5 Files
'jigsaw.webp': {'folder': 'GA5', 'content_type': 'image'},
'jigsaw.png': {'folder': 'GA5', 'content_type': 'image'},
'jigsaw.jpg': {'folder': 'GA5', 'content_type': 'image'},
'q-clean-up-excel-sales-data.xlsx':{'folder':'GA5','content_type':'data'},
'q-clean-up-sales-data.json':{'folder':'GA5','content_type':'data'},'q-clean-up-student-marks.txt':{'foler':'GA5','content_type':'docuemnt'},'q-extract-nested-json-keys.json':{'folder':'GA5','content_type':'data'},'q-parse-parital-json.jsonl':{'folder':'GA5','content_type':'data'},'s-anand_net-May-2024.gz':{'folder':'GA5','content_type':'archive'}
}
def __del__(self):
"""Clean up temporary directories when the manager is destroyed"""
self.cleanup()
import shutil
def cleanup(self):
"""Clean up any temporary directories created during processing"""
for temp_dir in self.temp_dirs:
try:
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=True)
except Exception as e:
print(f"Warning: Failed to clean up {temp_dir}: {str(e)}")
self.temp_dirs = []
def detect_file_from_query(self, query):
"""
Enhanced detection of file references from queries.
Supports multiple patterns, file types, and handles same-named files.
Args:
query (str): User query text that may contain file references
Returns:
dict: Comprehensive file information with content signature
"""
if not query:
return {"path": None, "exists": False, "type": None, "is_remote": False}
example_url_patterns = [
r'https?://\.your-app\.vercel\.app',
r'https?://\[USER\]\.github\.io',
r'https?://\.example\.com',
r'https?://.*\.vercel\.app/api\?name=X',
r'https?://.*\-anand\.net/',
r'https?://.*\.github.com/USER/REPO'
]
for pattern in example_url_patterns:
# Replace example URLs with placeholders to avoid false detection
query = re.sub(pattern, "EXAMPLE_URL_PLACEHOLDER", query) # Fixed missing parenthesis
# Flatten supported extensions for pattern matching
all_extensions = []
for ext_list in self.supported_extensions.values():
all_extensions.extend([ext[1:] for ext in ext_list]) # Remove leading dots
# Format for regex pattern
ext_pattern = '|'.join(all_extensions)
# PRIORITY 1: Check for uploaded files via TDS.py or file upload indicators
tds_upload_patterns = [
r'@file\s+([^\s]+\.(?:' + ext_pattern + r'))',
r'uploaded file at\s+([^\s]+\.(?:' + ext_pattern + r'))',
r'uploaded\s+to\s+([^\s]+\.(?:' + ext_pattern + r'))',
r'file uploaded to\s+([^\s]+\.(?:' + ext_pattern + r'))',
r'upload path[:\s]+([^\s]+\.(?:' + ext_pattern + r'))',
r'file (?:.*?) is located at ([^\s,\.]+)',
r'from file:? ([^\s,\.]+)',
r'file path:? ([^\s,\.]+)'
]
for pattern in tds_upload_patterns:
upload_match = re.search(pattern, query, re.IGNORECASE)
if upload_match:
path = upload_match.group(1).strip('"\'')
if os.path.exists(path):
ext = os.path.splitext(path)[1].lower()
file_type = self._get_file_type(ext)
content_sig = self._calculate_content_signature(path)
return {
"path": path,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": False,
"source": "upload",
"content_signature": content_sig
}
# NEW PRIORITY: Enhanced URL detection
url_info = self.enhance_url_detection(query)
if url_info:
return url_info
# PRIORITY 2: Check temporary directories for recent uploads
# This is critical for handling files uploaded through TDS.py that don't have explicit markers
temp_directories = [
tempfile.gettempdir(),
'/tmp',
os.path.join(tempfile.gettempdir(), 'uploads'),
os.path.join(os.getcwd(), 'uploads'),
os.path.join(os.getcwd(), 'temp'),
'E:/data science tool/temp'
]
# Extract target file type from query
target_type = None
target_extensions = None
for file_type, pattern in self.file_patterns.items():
if re.search(pattern, query, re.IGNORECASE):
target_type = file_type
target_extensions = self.supported_extensions.get(file_type)
break
# If we have identified a target file type, look for recent uploads of that type
if target_extensions:
latest_file = None
latest_time = 0
for temp_dir in temp_directories:
if os.path.exists(temp_dir):
try:
for file in os.listdir(temp_dir):
ext = os.path.splitext(file)[1].lower()
if ext in target_extensions:
path = os.path.join(temp_dir, file)
if os.path.isfile(path):
mtime = os.path.getmtime(path)
# Use recently modified files (within last hour)
if mtime > latest_time and time.time() - mtime < 3600:
latest_time = mtime
latest_file = path
except Exception as e:
print(f"Error accessing directory {temp_dir}: {str(e)}")
if latest_file:
ext = os.path.splitext(latest_file)[1].lower()
file_type = self._get_file_type(ext)
content_sig = self._calculate_content_signature(latest_file)
return {
"path": latest_file,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": False,
"source": "recent_upload",
"content_signature": content_sig
}
# PRIORITY 3: Look for file paths in query (Windows, Unix, quoted paths)
path_patterns = [
r'([a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]+\.(?:' + ext_pattern + r'))', # Windows
r'((?:/[^/]+)+\.(?:' + ext_pattern + r'))', # Unix
r'[\'\"]([^\'\"]+\.(?:' + ext_pattern + r'))[\'\"]', # Quoted path
r'file\s+[\'\"]?([^\'\"]+\.(?:' + ext_pattern + r'))[\'\"]?', # File keyword
]
for pattern in path_patterns:
path_match = re.search(pattern, query, re.IGNORECASE)
if path_match:
potential_path = path_match.group(1)
if os.path.exists(potential_path):
ext = os.path.splitext(potential_path)[1].lower()
file_type = self._get_file_type(ext)
content_sig = self._calculate_content_signature(potential_path)
return {
"path": potential_path,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": False,
"source": "query_path",
"content_signature": content_sig
}
# PRIORITY 4: Check for URLs pointing to files
url_pattern = r'(https?://[^\s"\'<>]+\.(?:' + ext_pattern + r'))'
url_match = re.search(url_pattern, query, re.IGNORECASE)
if url_match:
url = url_match.group(1)
ext = os.path.splitext(url)[1].lower()
file_type = self._get_file_type(ext)
return {
"path": url,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": True,
"source": "url"
}
# PRIORITY 5: Check for known file references
query_lower = query.lower()
for filename, info in self.known_files.items():
if filename.lower() in query_lower:
# Look for the file in the expected GA folder first
expected_path = os.path.join(self.base_directory, info['folder'], filename)
if os.path.exists(expected_path):
ext = os.path.splitext(expected_path)[1].lower()
file_type = self._get_file_type(ext)
content_sig = self._calculate_content_signature(expected_path)
return {
"path": expected_path,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": False,
"source": "known_file",
"content_signature": content_sig
}
# If not in the expected folder, search all GA folders
for folder in self.ga_folders:
alt_path = os.path.join(self.base_directory, folder, filename)
if os.path.exists(alt_path):
ext = os.path.splitext(alt_path)[1].lower()
file_type = self._get_file_type(ext)
content_sig = self._calculate_content_signature(alt_path)
return {
"path": alt_path,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": False,
"source": "known_file_alt_location",
"content_signature": content_sig
}
# PRIORITY 6: Looser filename pattern (just looking for something that might be a file)
filename_pattern = r'(?:file|document|data)[:\s]+["\']?([^"\'<>|*?\r\n]+\.(?:' + ext_pattern + r'))'
filename_match = re.search(filename_pattern, query, re.IGNORECASE)
if filename_match:
filename = filename_match.group(1).strip()
# Check current directory and all GA folders
search_paths = [
os.getcwd(),
os.path.join(os.getcwd(), "data"),
self.base_directory
]
# Add GA folders to search paths
for folder in self.ga_folders:
search_paths.append(os.path.join(self.base_directory, folder))
for base_path in search_paths:
full_path = os.path.join(base_path, filename)
if os.path.exists(full_path):
ext = os.path.splitext(full_path)[1].lower()
file_type = self._get_file_type(ext)
content_sig = self._calculate_content_signature(full_path)
return {
"path": full_path,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": False,
"source": "filename_search",
"content_signature": content_sig
}
# Not found
return {
"path": None,
"exists": False,
"type": None,
"is_remote": False,
"source": None
}
def enhance_url_detection(self, query):
"""
Enhanced URL detection that handles more formats and protocols
Args:
query (str): User query that might contain URLs
Returns:
dict: URL information if found, None otherwise
"""
if not query:
return None
# Expanded URL pattern to handle more formats
url_patterns = [
# Standard HTTP/HTTPS URLs ending with file extension
r'(https?://[^\s"\'<>]+\.(?:[a-zA-Z0-9]{2,6}))',
# URLs with query parameters or fragments
r'(https?://[^\s"\'<>]+\.(?:[a-zA-Z0-9]{2,6})(?:\?[^"\s<>]+)?)',
# Google Drive links
r'(https?://drive\.google\.com/[^\s"\'<>]+)',
# Dropbox links
r'(https?://(?:www\.)?dropbox\.com/[^\s"\'<>]+)',
# GitHub raw content links
r'(https?://raw\.githubusercontent\.com/[^\s"\'<>]+)',
# SharePoint/OneDrive links
r'(https?://[^\s"\'<>]+\.sharepoint\.com/[^\s"\'<>]+)',
# Amazon S3 links
r'(https?://[^\s"\'<>]+\.s3\.amazonaws\.com/[^\s"\'<>]+)'
]
for pattern in url_patterns:
url_match = re.search(pattern, query, re.IGNORECASE)
if url_match:
url = url_match.group(1)
# Try to determine file extension
if '?' in url:
base_url = url.split('?')[0]
ext = os.path.splitext(base_url)[1].lower()
else:
ext = os.path.splitext(url)[1].lower()
# If no extension but it's a special URL, try to determine type from context
if not ext:
if 'drive.google.com' in url:
if 'spreadsheet' in url.lower():
ext = '.xlsx'
elif 'document' in url.lower():
ext = '.docx'
elif 'presentation' in url.lower():
ext = '.pptx'
elif 'pdf' in url.lower():
ext = '.pdf'
else:
ext = '.tmp'
file_type = self._get_file_type(ext) if ext else "unknown"
return {
"path": url,
"exists": True,
"type": file_type,
"extension": ext,
"is_remote": True,
"source": "url",
"url_type": self._determine_url_type(url)
}
return None
def _determine_url_type(self, url):
"""Determine the type of URL for specialized handling"""
if 'drive.google.com' in url:
return "gdrive"
elif 'dropbox.com' in url:
return "dropbox"
elif 'githubusercontent.com' in url:
return "github"
elif 'sharepoint.com' in url or 'onedrive' in url:
return "microsoft"
elif 's3.amazonaws.com' in url:
return "s3"
else:
return "standard"
def download_url(self, url, desired_filename=None):
"""
Enhanced URL download with specialized handling for different services
Args:
url (str): URL to download
desired_filename (str, optional): Desired filename for the downloaded file
Returns: