-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate_system.py
More file actions
339 lines (270 loc) · 11.1 KB
/
validate_system.py
File metadata and controls
339 lines (270 loc) · 11.1 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
#!/usr/bin/env python3
"""System validation for the CodeWeaver application.
Validates the current project structure, syntax, and runtime configuration that are
actually required for this repository.
"""
import os
import re
import ast
from pathlib import Path
def validate_python_syntax(file_path):
"""Validate Python syntax using AST parsing."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
ast.parse(content)
return True, "Syntax valid"
except SyntaxError as e:
return False, f"Syntax error: {e}"
except Exception as e:
return False, f"Error: {e}"
def validate_javascript_syntax(file_path):
"""Basic JavaScript syntax validation."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
open_braces = content.count('{')
close_braces = content.count('}')
open_parens = content.count('(')
close_parens = content.count(')')
open_brackets = content.count('[')
close_brackets = content.count(']')
if open_braces != close_braces:
return False, f"Mismatched braces: {open_braces} vs {close_braces}"
if open_parens != close_parens:
return False, f"Mismatched parentheses: {open_parens} vs {close_parens}"
if open_brackets != close_brackets:
return False, f"Mismatched brackets: {open_brackets} vs {close_brackets}"
return True, "Syntax appears valid"
except Exception as e:
return False, f"Error: {e}"
def validate_css_syntax(file_path):
"""Basic CSS syntax validation."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
open_braces = content.count('{')
close_braces = content.count('}')
if open_braces != close_braces:
return False, f"Mismatched braces: {open_braces} vs {close_braces}"
return True, "Syntax appears valid"
except Exception as e:
return False, f"Error: {e}"
def validate_file_structure():
"""Validate that required files exist and identify optional files."""
required_files = {
'app.py': ('Flask application entrypoint', True),
'dependency_analyzer.py': ('Dependency analysis module', True),
'compressor.py': ('Compression module', True),
'requirements.txt': ('Python dependencies', True),
'.env': ('Environment configuration', True),
'templates/index.html': ('Main HTML template', True),
'static/script.js': ('Frontend JavaScript', True),
'static/style.css': ('Frontend CSS styling', True),
}
optional_files = {
'model_configuration.py': ('Legacy model-configuration helper', False),
'README.md': ('Project documentation', False),
}
results = {}
for file_path, (description, required) in required_files.items():
exists = os.path.exists(file_path)
results[file_path] = {
'exists': exists,
'description': description,
'required': required,
'status': '✅ Found' if exists else '❌ Missing',
}
for file_path, (description, required) in optional_files.items():
exists = os.path.exists(file_path)
results[file_path] = {
'exists': exists,
'description': description,
'required': required,
'status': '✅ Found' if exists else '⚠️ Optional: Missing',
}
return results
def _read_env_value(env_content, key):
for raw_line in env_content.splitlines():
line = raw_line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
candidate_key, value = line.split('=', 1)
if candidate_key.strip() == key:
return value.strip()
return ''
def validate_frontend_enhancements():
"""Validate frontend enhancements that exist in this project."""
js_path = 'static/script.js'
css_path = 'static/style.css'
results = {}
if os.path.exists(js_path):
with open(js_path, 'r', encoding='utf-8') as f:
js_content = f.read()
js_features = [
'renderEnhancedMermaidDiagram',
'validateMermaidSyntax',
'addDiagramInteractivity',
'addMermaidControls',
'enhanced_mermaid_diagram',
]
missing_js = [feature for feature in js_features if feature not in js_content]
results['javascript'] = {
'valid': len(missing_js) == 0,
'missing': missing_js,
'status': '✅ Enhanced' if len(missing_js) == 0 else '⚠️ Partial'
}
else:
results['javascript'] = {'valid': False, 'missing': ['File not found'], 'status': '❌ Missing'}
if os.path.exists(css_path):
with open(css_path, 'r', encoding='utf-8') as f:
css_content = f.read()
css_features = [
'.mermaid-enhanced',
'.mermaid-controls',
'.mermaid-error-container',
'.mermaid-loading',
'.mermaid-svg-container',
]
missing_css = [feature for feature in css_features if feature not in css_content]
results['css'] = {
'valid': len(missing_css) == 0,
'missing': missing_css,
'status': '✅ Enhanced' if len(missing_css) == 0 else '⚠️ Partial'
}
else:
results['css'] = {'valid': False, 'missing': ['File not found'], 'status': '❌ Missing'}
return results
def validate_configuration():
"""Validate environment configuration."""
env_path = '.env'
if not os.path.exists(env_path):
return False, "Environment file not found", ['.env is required'], []
with open(env_path, 'r', encoding='utf-8') as f:
env_content = f.read()
openrouter_api_key = _read_env_value(env_content, 'OPENROUTER_API_KEY')
gemini_api_key = _read_env_value(env_content, 'GEMINI_API_KEY')
if not openrouter_api_key and not gemini_api_key:
return (
False,
"Missing provider keys: set OPENROUTER_API_KEY or GEMINI_API_KEY",
['No OPENROUTER_API_KEY'],
[],
)
if not openrouter_api_key:
warnings = ['OPENROUTER_API_KEY is not set; fallback legacy flow may fail']
else:
warnings = []
required_recommended = [
('OPENROUTER_MODEL', 'google/gemma-3-27b-it:free'),
('OPENROUTER_API_URL', 'https://openrouter.ai/api/v1/chat/completions'),
('OPENROUTER_REQUEST_TIMEOUT', '120'),
('OPENROUTER_TIMEOUT', '120 (legacy alias)'),
('OPENROUTER_MAX_RETRIES', '3'),
('OPENROUTER_INITIAL_RETRY_DELAY', '1.0'),
('OPENROUTER_MAX_RETRY_DELAY', '30.0'),
('OPENROUTER_RETRY_JITTER_SECONDS', '0.4'),
('OPENROUTER_TEMPERATURE', '0.7'),
('OPENROUTER_TOP_P', '0.95'),
('OPENROUTER_MAX_TOKENS', '8192'),
('AI_SELECT_MAX_FILES_FOR_PROMPT', '2000'),
]
recommendations = []
for key, fallback in required_recommended:
value = _read_env_value(env_content, key)
if not value:
recommendations.append(f"Missing recommended key '{key}' (default: {fallback})")
diagram_keys = ['DIAGRAM_MAX_NODES', 'DIAGRAM_MAX_EDGES', 'DIAGRAM_ENABLE_VALIDATION']
for key in diagram_keys:
if not _read_env_value(env_content, key):
recommendations.append(f"Missing recommended key '{key}'")
return True, 'Configuration valid for current runtime', recommendations if recommendations else [], warnings
def main():
"""Run comprehensive system validation."""
print("🔍 CodeWeaver System Validation")
print("=" * 60)
print("\n📁 File Structure Validation:")
file_structure = validate_file_structure()
all_files_exist = True
missing_optional = []
for file_path, info in file_structure.items():
status = info['status']
print(f" {status} {file_path} - {info['description']}")
if not info['exists']:
if info['required']:
all_files_exist = False
else:
missing_optional.append(file_path)
if missing_optional:
print(f" ℹ️ Optional files missing (non-blocking): {', '.join(missing_optional)}")
print("\n🐍 Python Syntax Validation:")
python_files = [
'app.py',
'dependency_analyzer.py',
'compressor.py',
'model_configuration.py',
]
python_syntax_valid = True
for file_path in python_files:
if os.path.exists(file_path):
valid, message = validate_python_syntax(file_path)
status = "✅" if valid else "❌"
print(f" {status} {file_path}: {message}")
if not valid:
python_syntax_valid = False
print("\n🌐 Frontend Syntax Validation:")
if os.path.exists('static/script.js'):
js_valid, js_message = validate_javascript_syntax('static/script.js')
print(f" {'✅' if js_valid else '❌'} script.js: {js_message}")
else:
js_valid = False
print(" ❌ script.js: File not found")
if os.path.exists('static/style.css'):
css_valid, css_message = validate_css_syntax('static/style.css')
print(f" {'✅' if css_valid else '❌'} style.css: {css_message}")
else:
css_valid = False
print(" ❌ style.css: File not found")
print("\n🎨 Frontend Feature Validation:")
frontend_results = validate_frontend_enhancements()
print(f" {frontend_results['javascript']['status']} JavaScript features")
if frontend_results['javascript']['missing']:
for missing in frontend_results['javascript']['missing']:
print(f" - Missing: {missing}")
print(f" {frontend_results['css']['status']} CSS features")
if frontend_results['css']['missing']:
for missing in frontend_results['css']['missing']:
print(f" - Missing: {missing}")
print("\n⚙️ Configuration Validation:")
config_valid, config_msg, config_recommendations, config_warnings = validate_configuration()
if config_warnings:
print(" ⚠️ Configuration warnings:")
for warning in config_warnings:
print(f" - {warning}")
if config_recommendations:
print(" ℹ️ Recommended settings:")
for recommendation in config_recommendations:
print(f" - {recommendation}")
status = "✅" if config_valid else "❌"
print(f" {status} Environment configuration: {config_msg}")
print("\n" + "=" * 60)
print("🎯 VALIDATION SUMMARY")
print("=" * 60)
overall_valid = (
all_files_exist and
python_syntax_valid and
js_valid and
css_valid and
config_valid
)
if overall_valid:
print("✅ SYSTEM VALIDATION PASSED")
print("\n🎉 CodeWeaver system is ready for deployment")
else:
print("❌ SYSTEM VALIDATION FAILED")
print("\n⚠️ Please address the issues above before deployment.")
return overall_valid
if __name__ == '__main__':
success = main()
exit(0 if success else 1)