-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1878 lines (1534 loc) · 65.5 KB
/
app.py
File metadata and controls
1878 lines (1534 loc) · 65.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
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
#!/usr/bin/env python3
import os
import json
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass, field, asdict
from collections import defaultdict
import chardet
from flask import Flask, render_template, request, jsonify, send_file, session
from flask_cors import CORS
import secrets
import tempfile
import random
import logging
from functools import lru_cache
import threading
import time
import urllib.request
import urllib.error
from dotenv import load_dotenv
load_dotenv()
log = logging.getLogger(__name__)
def _load_positive_int_env(name: str, default: int) -> int:
raw = os.environ.get(name)
if raw is None:
return default
try:
value = int(raw.strip())
if value <= 0:
log.warning("Invalid %s value %r (must be > 0), using default %s", name, raw, default)
return default
return value
except ValueError:
log.warning("Invalid %s value %r, using default %s", name, raw, default)
return default
def _load_positive_float_env(name: str, default: float) -> float:
raw = os.environ.get(name)
if raw is None:
return default
try:
value = float(raw.strip())
if value <= 0:
log.warning("Invalid %s value %r (must be > 0), using default %s", name, raw, default)
return default
return value
except ValueError:
log.warning("Invalid %s value %r, using default %s", name, raw, default)
return default
from compressor import SemanticCompressor, LosslessCompressor, HybridCompressor
from dependency_analyzer import DependencyAnalyzer
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)
CORS(app, resources={r"/api/*": {"origins": "*"}})
OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY')
OPENROUTER_MODEL = os.environ.get('OPENROUTER_MODEL', 'google/gemma-3-27b-it:free')
OPENROUTER_MAX_RETRIES = _load_positive_int_env('OPENROUTER_MAX_RETRIES', 3)
OPENROUTER_API_URL = os.environ.get(
'OPENROUTER_API_URL',
'https://openrouter.ai/api/v1/chat/completions'
)
OPENROUTER_REQUEST_TIMEOUT = _load_positive_float_env(
'OPENROUTER_REQUEST_TIMEOUT',
_load_positive_float_env('OPENROUTER_TIMEOUT', 120.0),
)
AI_SELECT_MAX_FILES_FOR_PROMPT = _load_positive_int_env('AI_SELECT_MAX_FILES_FOR_PROMPT', 2000)
OPENROUTER_INITIAL_RETRY_DELAY = _load_positive_float_env('OPENROUTER_INITIAL_RETRY_DELAY', 1.0)
OPENROUTER_MAX_RETRY_DELAY = _load_positive_float_env('OPENROUTER_MAX_RETRY_DELAY', 30.0)
OPENROUTER_RETRY_JITTER_SECONDS = _load_positive_float_env('OPENROUTER_RETRY_JITTER_SECONDS', 0.4)
OPENROUTER_GENERATION_CONFIG: Dict[str, Any] = {
'temperature': _load_positive_float_env('OPENROUTER_TEMPERATURE', 0.7),
'top_p': _load_positive_float_env('OPENROUTER_TOP_P', 0.95),
'max_tokens': _load_positive_int_env('OPENROUTER_MAX_TOKENS', 8192),
}
def sanitize_output_filename(requested_filename: Any, compression_type: str) -> str:
extension = 'md' if compression_type == 'none' else 'json'
if isinstance(requested_filename, str):
requested_filename = requested_filename.strip()
else:
requested_filename = ''
if not requested_filename:
return ''
filename = Path(requested_filename).name
filename = re.sub(r'[\\/:*?"<>|]', '_', filename).strip(' .')
if not filename:
return ''
stem = Path(filename).stem.strip(' .')
if not stem:
return ''
return f'{stem}.{extension}'
_FILENAME_QUERY_STOPWORDS = {
'and',
'or',
'then',
'및',
'또는',
'및은',
'and/or',
'or/and'
}
def _normalize_filename_token(token: str) -> str:
return token.strip().strip('`"\'()[]{}<>;,::')
def _is_version_like_token(token: str) -> bool:
token_lower = token.lower()
return bool(re.fullmatch(r"\d+(?:\.\d+)+", token_lower))
def _is_likely_filename_token(
token: str,
*,
known_filenames: Set[str],
known_extensions: Set[str]
) -> bool:
if not token:
return False
lowered = token.lower()
if lowered in known_filenames:
return True
has_path_sep = '/' in token or '\\' in token
has_dot = '.' in token
if not has_path_sep and not has_dot:
return False
if has_path_sep:
return len(token.strip('/\\')) > 0
if _is_version_like_token(lowered):
return False
suffix = Path(token).suffix.lower()
if suffix and suffix in known_extensions:
return True
return suffix in known_filenames
def _extract_filename_only_candidates(
query: str,
*,
known_filenames: Optional[Set[str]] = None,
known_extensions: Optional[Set[str]] = None
) -> List[str]:
if not isinstance(query, str):
return []
query = query.strip()
if not query:
return []
tokens = re.findall(r"[^\s,]+", query)
if not tokens:
return []
known_filenames = known_filenames or set()
known_extensions = known_extensions or set()
candidates: List[str] = []
seen = set()
for token in tokens:
normalized = _normalize_filename_token(token)
if not normalized:
continue
if not _is_likely_filename_token(
normalized,
known_filenames=known_filenames,
known_extensions=known_extensions
):
continue
lowered = normalized.lower()
if lowered in seen:
continue
seen.add(lowered)
candidates.append(normalized)
return candidates
def _build_ai_file_manifest(
all_files: Dict[str, Any],
query: str,
*,
max_files: int
) -> List[Dict[str, str]]:
if max_files <= 0:
return []
manifest: List[Dict[str, str]] = []
for file_id, file_info in all_files.items():
if not isinstance(file_id, str) or not isinstance(file_info, dict):
continue
relative_path = file_info.get('relative_path')
if not isinstance(relative_path, str) or not relative_path:
continue
compact_entry: Dict[str, str] = {
'id': file_id,
'relative_path': relative_path,
}
extension = Path(relative_path).suffix.lower()
if extension:
compact_entry['extension'] = extension
manifest.append(compact_entry)
if not manifest:
return []
manifest.sort(key=lambda file_entry: file_entry['relative_path'].lower())
if len(manifest) <= max_files:
return manifest
query_terms = [
_normalize_filename_token(token).lower()
for token in re.findall(r"[^\s,]+", query or '')
if _normalize_filename_token(token)
]
query_terms = [
term for term in query_terms
if term and term not in _FILENAME_QUERY_STOPWORDS
]
if not query_terms:
return manifest[:max_files]
scored_files: List[Tuple[float, str, Dict[str, str]]] = []
for file_entry in manifest:
lower_path = file_entry['relative_path'].lower()
lower_name = Path(lower_path).name
score = 0.0
for term in query_terms:
if term in lower_path:
score += 1.0
if term == lower_name:
score += 2.0
if score > 0:
scored_files.append((score, lower_path, file_entry))
if not scored_files:
return manifest[:max_files]
scored_files.sort(key=lambda item: (item[0], item[1]), reverse=True)
return [entry for _, _, entry in scored_files[:max_files]]
def _is_pure_filename_query(query: str, candidates: List[str]) -> bool:
if not candidates:
return False
normalized_candidates = {candidate.lower() for candidate in candidates}
has_any_candidate = False
for raw_token in re.findall(r"[^\s,]+", query):
token = _normalize_filename_token(raw_token).lower()
if not token:
continue
if token in _FILENAME_QUERY_STOPWORDS:
continue
if token in normalized_candidates:
has_any_candidate = True
continue
return False
return has_any_candidate
if not OPENROUTER_API_KEY:
raise ValueError("OPENROUTER_API_KEY environment variable is not set")
TEMP_DIR = Path(tempfile.gettempdir()) / "source_aggregator"
TEMP_DIR.mkdir(exist_ok=True)
ORIGINALS_DIR = TEMP_DIR / "originals"
ORIGINALS_DIR.mkdir(exist_ok=True)
SESSION_TIMEOUT = timedelta(hours=2)
# Initialize with enhanced model configuration
@dataclass
class FileInfo:
path: str
size: int
extension: str
relative_path: str
selected: bool = False
id: str = ""
last_modified: float = 0
def __post_init__(self):
if not self.id:
self.id = self.relative_path.replace('/', '_').replace('.', '_').replace('-', '_')
@dataclass
class DirectoryInfo:
path: str
name: str
relative_path: str
file_count: int = 0
total_size: int = 0
children: List[Dict] = field(default_factory=list)
files: List[Dict] = field(default_factory=list)
selected: bool = False
expanded: bool = False
id: str = ""
def __post_init__(self):
if not self.id:
self.id = self.relative_path.replace('/', '_').replace('.', '_').replace('-', '_')
class WebSourceAggregator:
DEFAULT_EXTENSIONS = {
'.py', '.js', '.jsx', '.ts', '.tsx', '.java', '.c', '.cpp', '.h', '.hpp',
'.cs', '.php', '.rb', '.go', '.rs', '.swift', '.kt', '.scala', '.r',
'.html', '.css', '.scss', '.sass', '.less',
'.json', '.xml', '.yaml', '.yml', '.toml', '.ini', '.conf', '.config',
'.sql', '.sh', '.bash', '.zsh', '.fish', '.ps1', '.bat', '.cmd',
'.dockerfile', '.dockerignore', '.gitignore', '.env', '.env.example',
'.md', '.txt', '.rst', '.tex',
'.vue', '.svelte', '.astro',
'.prisma', '.graphql', '.proto'
}
DEFAULT_EXCLUDE_DIRS = {
'.git', '.svn', '.hg', '.bzr',
'node_modules', '__pycache__', '.pytest_cache', '.mypy_cache',
'venv', 'env', '.venv', '.env', 'virtualenv',
'dist', 'build', 'out', 'target', 'bin', 'obj',
'.idea', '.vscode', '.vs', '.sublime',
'coverage', '.coverage', 'htmlcov',
'.next', '.nuxt', '.cache', '.parcel-cache',
'vendor', 'packages', 'bower_components'
}
# Method to check if a directory should be excluded
def _should_exclude_dir(self, dir_name: str) -> bool:
# Exclude directories starting with .
if dir_name.startswith('.'):
return True
# Exclude directories in DEFAULT_EXCLUDE_DIRS
if dir_name in self.DEFAULT_EXCLUDE_DIRS:
return True
return False
def __init__(self, root_dir: str, max_file_size_mb: float = 10):
self.root_dir = Path(root_dir).resolve()
self._validate_root_dir()
self.max_file_size = max_file_size_mb * 1024 * 1024
self.all_files = {}
self.all_directories = {}
self.file_extensions = defaultdict(list)
self.errors = []
self.search_index = {}
def _validate_root_dir(self):
if not self.root_dir.exists():
raise ValueError(f"Directory does not exist: {self.root_dir}")
if not self.root_dir.is_dir():
raise ValueError(f"Path is not a directory: {self.root_dir}")
try:
os.listdir(self.root_dir)
except PermissionError:
raise ValueError(f"Permission denied: {self.root_dir}")
def analyze_directory_structure(self) -> Dict:
def analyze_dir(dir_path: Path, parent_path: Optional[Path] = None) -> Dict:
relative_path = str(dir_path.relative_to(self.root_dir)) if dir_path != self.root_dir else "."
dir_info = DirectoryInfo(
path=str(dir_path),
name=dir_path.name if dir_path != self.root_dir else self.root_dir.name,
relative_path=relative_path
)
try:
items = sorted(dir_path.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))
for item in items:
if item.is_dir() and not self._should_exclude_dir(item.name):
try:
child_data = analyze_dir(item, dir_path)
dir_info.children.append(child_data)
dir_info.file_count += child_data['file_count']
dir_info.total_size += child_data['total_size']
except PermissionError:
continue
for item in items:
if item.is_file():
try:
# Get relative path to check for hidden directories in the path
relative_path = str(item.relative_to(self.root_dir))
path_parts = relative_path.split('/')
# Check if file is hidden or in a hidden directory
is_hidden = item.name.startswith('.')
is_in_hidden_dir = any(part.startswith('.') for part in path_parts[:-1])
is_lock_file = 'lock' in item.name.lower() and item.name.endswith(('.yaml', '.yml', '.json'))
# Skip hidden files, files in hidden directories, and lock files
if is_hidden or is_in_hidden_dir or is_lock_file:
continue
file_stat = item.stat()
if file_stat.st_size <= self.max_file_size:
file_info = FileInfo(
path=str(item),
size=file_stat.st_size,
extension=item.suffix.lower(),
relative_path=relative_path,
last_modified=file_stat.st_mtime
)
file_dict = asdict(file_info)
dir_info.files.append(file_dict)
dir_info.file_count += 1
dir_info.total_size += file_stat.st_size
self.all_files[file_info.id] = file_dict
self.file_extensions[file_info.extension].append(file_dict)
self._index_file_for_search(file_info)
except Exception as e:
self.errors.append({'path': str(item), 'error': str(e)})
except PermissionError as e:
self.errors.append({'path': str(dir_path), 'error': f"Permission denied: {e}"})
dir_dict = asdict(dir_info)
self.all_directories[dir_info.id] = dir_dict
return dir_dict
root_structure = analyze_dir(self.root_dir)
extension_stats = {}
for ext, files in self.file_extensions.items():
if ext:
total_size = sum(f['size'] for f in files)
extension_stats[ext] = {
'count': len(files),
'size': total_size,
'extension': ext
}
return {
'tree': root_structure,
'stats': {
'total_files': len(self.all_files),
'total_dirs': len(self.all_directories),
'extensions': sorted(extension_stats.values(), key=lambda x: x['count'], reverse=True),
'errors': len(self.errors)
}
}
def _index_file_for_search(self, file_info: FileInfo):
filename = Path(file_info.relative_path).name.lower()
relative_path_lower = file_info.relative_path.lower()
words = re.findall(r'\w+', filename)
for word in words:
if word not in self.search_index:
self.search_index[word] = []
self.search_index[word].append(file_info.id)
if relative_path_lower not in self.search_index:
self.search_index[relative_path_lower] = []
self.search_index[relative_path_lower].append(file_info.id)
def search_files(self, query: str) -> List[Dict]:
if not query:
return []
query_lower = query.lower()
matched_file_ids = set()
for word in re.findall(r'\w+', query_lower):
for index_key, file_ids in self.search_index.items():
if word in index_key:
matched_file_ids.update(file_ids)
for path_key, file_ids in self.search_index.items():
if query_lower in path_key:
matched_file_ids.update(file_ids)
results = []
for file_id in matched_file_ids:
if file_id in self.all_files:
file_info = self.all_files[file_id].copy()
file_info['match_score'] = self._calculate_match_score(
file_info['relative_path'], query_lower
)
results.append(file_info)
return sorted(results, key=lambda x: x['match_score'], reverse=True)
def _calculate_match_score(self, path: str, query: str) -> float:
path_lower = path.lower()
filename = Path(path).name.lower()
score = 0.0
if query == filename:
score += 100.0
elif query in filename:
score += 50.0
elif query in path_lower:
score += 25.0
query_words = set(re.findall(r'\w+', query))
path_words = set(re.findall(r'\w+', path_lower))
if query_words:
word_match_ratio = len(query_words & path_words) / len(query_words)
score += word_match_ratio * 20.0
if path_lower.startswith(query):
score += 10.0
return score
def select_files_by_names(self, filenames: List[str]) -> Dict[str, List[str]]:
selected = []
not_found = []
for filename in filenames:
filename_lower = filename.lower()
found = False
for file_id, file_info in self.all_files.items():
file_path = file_info['relative_path']
if filename_lower in file_path.lower():
selected.append(file_id)
found = True
if not found:
not_found.append(filename)
return {
'selected': selected,
'not_found': not_found
}
def generate_markdown(self, selected_files: List[str], compression_type: str = 'none') -> Tuple[str, Optional[Dict]]:
lines = []
lines.append("# Aggregated Source Code")
lines.append(f"\n**Generated at:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append(f"**Root Directory:** `{self.root_dir}`")
lines.append(f"**Total Files:** {len(selected_files)}")
lines.append(f"**Compression Type:** {compression_type}")
lines.append("\n## Table of Contents\n")
for i, file_id in enumerate(selected_files, 1):
if file_id in self.all_files:
file_info = self.all_files[file_id]
lines.append(f"{i}. [{file_info['relative_path']}](#{file_id})")
lines.append("\n---\n")
for file_id in selected_files:
if file_id in self.all_files:
file_info = self.all_files[file_id]
file_path = Path(file_info['path'])
lines.append(f"\n## {file_info['relative_path']}\n")
lines.append(f"**File Size:** {self._format_size(file_info['size'])} ")
lines.append(f"**Last Modified:** {datetime.fromtimestamp(file_info['last_modified']).strftime('%Y-%m-%d %H:%M:%S')} ")
lines.append("")
try:
content, language = self._read_file_content(file_path)
lines.append(f"```{language}")
lines.append(content)
lines.append("```")
except Exception as e:
lines.append(f"**Error reading file:** {e}")
lines.append("\n---")
markdown_content = '\n'.join(lines)
# Use unified compression factory
from compressor import compress_markdown_unified
return compress_markdown_unified(markdown_content, compression_type)
def _format_size(self, size_bytes: int) -> str:
size_value = float(size_bytes)
for unit in ['B', 'KB', 'MB', 'GB']:
if size_value < 1024.0:
return f"{size_value:.2f} {unit}"
size_value /= 1024.0
return f"{size_value:.2f} TB"
@lru_cache(maxsize=128)
def _detect_encoding(self, file_path: str) -> str:
try:
with open(file_path, 'rb') as f:
raw_data = f.read(10000)
result = chardet.detect(raw_data)
encoding = result.get('encoding', 'utf-8')
if not encoding or result.get('confidence', 0) < 0.7:
encoding = 'utf-8'
return encoding
except Exception:
return 'utf-8'
def _read_file_content(self, file_path: Path) -> tuple:
language_map = {
'.py': 'python', '.js': 'javascript', '.jsx': 'jsx',
'.ts': 'typescript', '.tsx': 'tsx', '.java': 'java',
'.c': 'c', '.cpp': 'cpp', '.h': 'c', '.hpp': 'cpp',
'.cs': 'csharp', '.php': 'php', '.rb': 'ruby',
'.go': 'go', '.rs': 'rust', '.swift': 'swift',
'.kt': 'kotlin', '.scala': 'scala', '.r': 'r',
'.html': 'html', '.css': 'css', '.scss': 'scss',
'.json': 'json', '.xml': 'xml', '.yaml': 'yaml',
'.yml': 'yaml', '.sql': 'sql', '.sh': 'bash',
'.md': 'markdown', '.txt': 'text'
}
suffix = file_path.suffix.lower()
language = language_map.get(suffix, 'text')
if file_path.name == 'Dockerfile':
language = 'dockerfile'
elif file_path.name in ['Makefile', 'makefile']:
language = 'makefile'
encoding = self._detect_encoding(str(file_path))
with open(file_path, 'r', encoding=encoding, errors='replace') as f:
content = f.read()
return content, language
class OpenRouterAPIError(RuntimeError):
def __init__(
self,
status_code: int,
message: str,
*,
provider: Optional[str] = None,
error_code: Optional[Any] = None,
retry_after: Optional[float] = None,
raw_payload: Optional[Dict[str, Any]] = None,
raw_body: str = ''
) -> None:
super().__init__(message)
self.status_code = status_code
self.error = message
self.provider = provider
self.error_code = error_code
self.retry_after = retry_after
self.raw_payload = raw_payload
self.raw_body = raw_body
def is_quota_error(self) -> bool:
message = (self.error or '').lower()
return self.status_code == 429 and (
'quota' in message
or 'exceed' in message
or 'rate' in message
)
class OpenRouterFileAnalyzer:
def __init__(self, model_name: Optional[str] = None):
self.model_name = model_name or OPENROUTER_MODEL
def _post_openrouter_request(self, prompt: str) -> str:
payload: Dict[str, Any] = {
'model': self.model_name,
'messages': [
{
'role': 'system',
'content': (
'You are a strict JSON-only code analysis assistant. '
'Return valid JSON only.'
)
},
{
'role': 'user',
'content': prompt
}
]
}
payload.update(OPENROUTER_GENERATION_CONFIG)
data = json.dumps(payload).encode('utf-8')
request = urllib.request.Request(
OPENROUTER_API_URL,
data=data,
headers={
'Authorization': f'Bearer {OPENROUTER_API_KEY}',
'Content-Type': 'application/json',
'HTTP-Referer': 'http://localhost',
'X-Title': 'CodeWeaver AI File Selector'
},
method='POST'
)
try:
with urllib.request.urlopen(request, timeout=OPENROUTER_REQUEST_TIMEOUT) as response:
response_text = response.read().decode('utf-8')
except urllib.error.HTTPError as e:
error_body = ''
try:
error_body = e.read().decode('utf-8', errors='replace')
except Exception:
error_body = e.reason if isinstance(e.reason, str) else ''
parsed_error = self._parse_openrouter_error_payload(error_body)
provider_name, provider_message, error_code = self._extract_provider_error_info(parsed_error)
retry_after = self._extract_retry_after(parsed_error, e.headers, error_body)
if (e.code == 429 and retry_after is None and provider_message):
retry_after = self._extract_retry_after_from_message(provider_message)
error_message = provider_message if provider_message else f'OpenRouter API request failed ({e.code}): {error_body or e.reason}'
app.logger.error(f'OpenRouter API request failed ({e.code}): {error_message}')
raise OpenRouterAPIError(
status_code=e.code or 0,
message=error_message,
provider=provider_name,
error_code=error_code,
retry_after=retry_after,
raw_payload=parsed_error,
raw_body=error_body
)
except urllib.error.URLError as e:
app.logger.error(f'OpenRouter API request failed: {e.reason}')
raise OpenRouterAPIError(
status_code=503,
message=f'OpenRouter API request failed: {e.reason}',
error_code='network_error'
)
response_payload = json.loads(response_text)
choices = response_payload.get('choices', [])
if not choices:
raise ValueError('No choices returned by OpenRouter API')
message = choices[0].get('message', {})
content = message.get('content', '')
if not content:
raise ValueError('Empty content returned by OpenRouter API')
return str(content)
def analyze_files_for_query(
self,
query: str,
file_structure: Dict[str, Any]
) -> Dict[str, Any]:
prompt = self._build_analysis_prompt(query, file_structure)
try:
attempts = 0
last_error = None
response_text = ''
retryable_status = {429, 500, 502, 503, 504}
while attempts < OPENROUTER_MAX_RETRIES:
try:
response_text = self._post_openrouter_request(prompt)
last_error = None
break
except (OpenRouterAPIError, urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError) as e:
attempts += 1
last_error = e
status_code = None
if attempts >= OPENROUTER_MAX_RETRIES:
break
if isinstance(e, OpenRouterAPIError):
status_code = e.status_code
if status_code and status_code not in retryable_status:
break
if e.retry_after is not None and e.retry_after > 0:
delay = float(e.retry_after)
else:
delay = min(
OPENROUTER_MAX_RETRY_DELAY,
OPENROUTER_INITIAL_RETRY_DELAY * (2 ** (attempts - 1))
)
else:
delay = min(
OPENROUTER_MAX_RETRY_DELAY,
OPENROUTER_INITIAL_RETRY_DELAY * (2 ** (attempts - 1))
)
if OPENROUTER_RETRY_JITTER_SECONDS:
jitter = random.uniform(0.0, OPENROUTER_RETRY_JITTER_SECONDS)
delay += jitter
if delay > 0:
time.sleep(delay)
if status_code == 429:
app.logger.warning(
'OpenRouter rate-limited on attempt %s/%s; retrying in %.2fs',
attempts,
OPENROUTER_MAX_RETRIES,
delay,
)
if last_error is not None and not response_text:
raise last_error
result = self._parse_openrouter_response(response_text)
raw_selected_files = result.get('files', result.get('selected_files', []))
normalized_files = self._normalize_selected_files(raw_selected_files)
return {
'success': True,
'selected_files': normalized_files,
'reasoning': result.get('reasoning', ''),
'confidence': self._to_float(result.get('confidence'), 0.0)
}
except Exception as e:
app.logger.error(f"OpenRouter API error: {str(e)}")
if isinstance(e, OpenRouterAPIError):
return {
'success': False,
'error': e.error,
'error_category': 'provider_error',
'status_code': e.status_code,
'error_code': e.error_code,
'provider': e.provider,
'retry_after': e.retry_after,
'reasoning': '',
'confidence': 0.0
}
if isinstance(e, urllib.error.HTTPError):
return {
'success': False,
'error': str(e),
'error_category': 'http_error',
'status_code': e.code,
'reasoning': '',
'confidence': 0.0
}
if isinstance(e, (urllib.error.URLError, json.JSONDecodeError, ValueError)):
return {
'success': False,
'error': str(e),
'error_category': 'provider_error',
'status_code': 503,
'reasoning': '',
'confidence': 0.0
}
return {
'success': False,
'error': str(e),
'error_category': 'framework_error',
'status_code': 502
}
def _build_analysis_prompt(
self,
query: str,
file_structure: Dict[str, Any]
) -> str:
files_info = self._extract_file_info(file_structure)
prompt = f"""You are an expert code analyzer. Analyze the following project structure and identify files related to the user's query.
**User Query (in Korean):** {query}
**Project Structure:**
{json.dumps(files_info, indent=2, ensure_ascii=False)}
**Task:**
1. Understand the user's intent from the Korean query
2. Analyze each file's path, name, and extension
3. Identify files that are likely related to the query
4. Provide reasoning for each selection
**Output Format (JSON):**
{{
"files": [
{{
"file_id": "unique_file_identifier",
"relative_path": "path/to/file.ext",
"reason": "Why this file is relevant",
"confidence": 0.95
}}
],
"reasoning": "Overall analysis explanation in Korean",
"confidence": 0.85
}}
**Selection Criteria:**
- File names and paths that suggest relevant functionality
- Common patterns (e.g., "upload", "download", "transfer" for file transfer)
- File types that typically contain such logic (e.g., .py, .js for backend/frontend)
- Configuration files that might define related settings
Respond ONLY with valid JSON, no additional text."""
return prompt
def _extract_file_info(self, node: Dict, files_list: Optional[List[Dict[str, Any]]] = None) -> List[Dict]:
if files_list is None:
files_list = []
if node.get('files'):
for file in node['files']:
files_list.append({
'id': file.get('id'),
'relative_path': file.get('relative_path'),
'extension': file.get('extension'),
'size': file.get('size')
})
if node.get('children'):
for child in node['children']:
self._extract_file_info(child, files_list)
return files_list
@staticmethod
def _safe_json_loads(payload: str) -> Optional[Dict[str, Any]]:
try:
loaded = json.loads(payload)
if isinstance(loaded, dict):
return loaded
return None
except Exception:
return None
@staticmethod
def _extract_retry_after_from_message(message: str) -> Optional[float]:
if not message:
return None
message_lower = message.lower()
if 'retry' not in message_lower:
return None
patterns = [
r'please\s+retry\s+in\s*([0-9]+(?:\.[0-9]+)?)\s*s',
r'retry\s+in\s*([0-9]+(?:\.[0-9]+)?)\s*seconds?',
r'retry\s+in\s*([0-9]+(?:\.[0-9]+)?)\s*sec'
]
for pattern in patterns:
match = re.search(pattern, message_lower)
if match is None:
continue