maya-cli 0.1.2__py3-none-any.whl → 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maya_cli/cli.py CHANGED
@@ -48,21 +48,27 @@ def create(project_name):
48
48
  logging.error(f"Error while creating project: {str(e)}")
49
49
  click.echo(f"❌ An error occurred: {str(e)}")
50
50
 
51
-
52
51
  @click.command()
53
- @click.argument("folder", required=False, default="api")
54
- @click.argument("filename", required=False)
55
- def check_best_practices(folder, filename):
56
- """CLI Command: maya check best-practices [folder] [filename]"""
52
+ @click.argument("path", nargs=-1, required=True)
53
+ def check_best_practices(path):
54
+ """CLI Command: maya check-best-practices [folder] [sub-folder] ... [filename]"""
57
55
  click.echo("🚀 Running Best Practices Check...")
56
+
58
57
  base_path = os.getcwd()
59
- target_directory = os.path.join(base_path, folder)
58
+ target_path = os.path.join(base_path, *path)
60
59
 
61
- if not os.path.exists(target_directory):
62
- click.echo(f"❌ Folder '{folder}' does not exist.")
60
+ if not os.path.exists(target_path):
61
+ click.echo(f"❌ Path '{target_path}' does not exist.")
62
+ return
63
+
64
+ if os.path.isdir(target_path):
65
+ process_directory(target_path)
66
+ elif os.path.isfile(target_path):
67
+ process_directory(os.path.dirname(target_path), os.path.basename(target_path))
68
+ else:
69
+ click.echo("❌ Invalid path provided.")
63
70
  return
64
71
 
65
- process_directory(target_directory, filename)
66
72
  click.echo("✅ Best practices check completed!")
67
73
 
68
74
 
@@ -87,112 +93,105 @@ def set_env(key, value):
87
93
  logging.error(f"Error setting environment variable {key}: {str(e)}")
88
94
  click.echo(f"❌ Error setting environment variable: {str(e)}")
89
95
 
90
-
91
96
  @click.command()
92
- @click.argument("target", required=False, default=None)
93
- def optimize(target):
94
- """Optimize AI scripts with caching & async processing"""
95
- fine_tune = click.confirm("Do you want to enable fine-tuning?", default=False)
96
-
97
- if target:
98
- if os.path.isdir(target):
99
- optimize_folder(target, fine_tune)
100
- elif os.path.isfile(target):
101
- optimize_file(target, fine_tune)
102
- else:
103
- click.echo(f"❌ Error: '{target}' is not a valid file or folder.")
104
- return
105
- else:
106
- click.echo("Optimizing the entire project...")
107
- optimize_project(fine_tune)
108
-
97
+ @click.argument("parent_folder", required=True)
98
+ @click.argument("sub_folder", required=True)
99
+ @click.argument("filename", required=True)
100
+ def optimize(parent_folder, sub_folder, filename):
101
+ """Optimize a file by importing optimize.py from maya_cli.scripts."""
102
+
103
+ # Construct the full file path
104
+ target_path = os.path.abspath(os.path.join(parent_folder, sub_folder, filename))
109
105
 
110
- def optimize_file(filepath, fine_tune_enabled):
111
- """Dynamically import optimize.py into the specified file."""
112
- try:
113
- module_name = "scripts.optimize"
114
- spec = importlib.util.spec_from_file_location(module_name, "scripts/optimize.py")
115
- optimize_module = importlib.util.module_from_spec(spec)
116
- spec.loader.exec_module(optimize_module)
106
+ if not os.path.isfile(target_path):
107
+ click.echo(f" Error: '{target_path}' is not a valid file.")
108
+ logging.error(f"Invalid file provided: {target_path}")
109
+ return
117
110
 
118
- click.echo(f"✅ Optimization applied to {filepath}")
119
- logging.info(f"Optimization applied to {filepath}")
111
+ # Inject the import statement into the file
112
+ inject_import(target_path)
120
113
 
121
- if fine_tune_enabled and hasattr(optimize_module, "fine_tune_model"):
122
- optimize_module.fine_tune_model()
123
- click.echo("🚀 Fine-tuning enabled!")
114
+ def inject_import(filepath):
115
+ """Inject import statement for optimize.py into the target file."""
116
+ try:
117
+ import_statement = "from maya_cli.scripts import optimize\n"
118
+
119
+ with open(filepath, "r+", encoding="utf-8") as f:
120
+ content = f.readlines()
121
+
122
+ # Check if the import already exists
123
+ if any(line.strip() == import_statement.strip() for line in content):
124
+ click.echo(f"✅ {filepath} already imports optimize.py.")
125
+ return
126
+
127
+ # Insert import at the top
128
+ content.insert(0, import_statement)
129
+ f.seek(0)
130
+ f.writelines(content)
131
+
132
+ click.echo(f"✅ Imported optimize.py into {filepath}")
133
+ logging.info(f"Imported optimize.py into {filepath}")
124
134
 
125
135
  except Exception as e:
126
- logging.error(f"Error optimizing file '{filepath}': {str(e)}")
127
- click.echo(f"❌ Error optimizing file '{filepath}': {str(e)}")
128
-
129
-
130
- def optimize_folder(folderpath, fine_tune_enabled):
131
- """Import optimize.py into all Python files in a folder."""
132
- for root, _, files in os.walk(folderpath):
133
- for file in files:
134
- if file.endswith(".py"):
135
- optimize_file(os.path.join(root, file), fine_tune_enabled)
136
-
136
+ logging.error(f"Error injecting import into '{filepath}': {str(e)}")
137
+ click.echo(f"❌ Error injecting import into '{filepath}': {str(e)}")
137
138
 
138
- def optimize_project(fine_tune_enabled):
139
- """Optimize the entire project by importing optimize.py globally."""
140
- try:
141
- import scripts.optimize
139
+ import os
140
+ import json
141
+ import click
142
+ import logging
143
+ import openai
142
144
 
143
- click.echo("✅ Project-wide optimization applied!")
144
- logging.info("Project-wide optimization applied.")
145
+ @click.command()
146
+ @click.argument("parent_folder", required=True)
147
+ @click.argument("sub_folder", required=True)
148
+ @click.argument("filename", required=True)
149
+ def is_secured(parent_folder, sub_folder, filename):
150
+ """Check and enforce API security measures: Authentication, Encryption, and Rate Limiting."""
151
+ click.echo("🔍 Running API Security Check...")
145
152
 
146
- if fine_tune_enabled and hasattr(scripts.optimize, "fine_tune_model"):
147
- scripts.optimize.fine_tune_model()
148
- click.echo("🚀 Fine-tuning enabled!")
153
+ # Construct the full file path
154
+ target_path = os.path.abspath(os.path.join(parent_folder, sub_folder, filename))
149
155
 
150
- except Exception as e:
151
- logging.error(f"Error applying project-wide optimization: {str(e)}")
152
- click.echo(f" Error applying project-wide optimization: {str(e)}")
156
+ if not os.path.isfile(target_path):
157
+ click.echo(f"Error: '{target_path}' is not a valid file.")
158
+ logging.error(f"Invalid file provided: {target_path}")
159
+ return
153
160
 
154
- @click.command()
155
- @click.argument("target")
156
- @click.argument("filename", required=False)
157
- def isSecured(target, filename=None):
158
- """Check and enforce API security measures: Authentication, Encryption, and Rate Limiting."""
159
- click.echo("\U0001F50D Running API Security Check...")
160
- security_issues = []
161
-
162
- # Determine path to check
163
- if filename:
164
- files_to_check = [os.path.join(target, filename)]
165
- else:
166
- files_to_check = [os.path.join(target, f) for f in os.listdir(target) if f.endswith(".py")]
167
-
168
- for file in files_to_check:
169
- with open(file, "r") as f:
161
+ try:
162
+ with open(target_path, "r", encoding="utf-8") as f:
170
163
  code_content = f.read()
171
-
172
- # Validate security using OpenAI
164
+
165
+ # Validate security using AI
173
166
  validation_feedback = validate_security_with_ai(code_content)
174
-
167
+ security_issues = []
168
+
175
169
  if not validation_feedback.get("authentication", False):
176
- security_issues.append(f"{file}: Missing API Authentication. Applying OAuth/API Key authentication.")
177
- apply_api_authentication(file)
178
-
170
+ security_issues.append(f" Missing API Authentication. Applying OAuth/API Key authentication.")
171
+ apply_api_authentication(target_path)
172
+
179
173
  if not validation_feedback.get("encryption", False):
180
- security_issues.append(f"{file}: Missing Data Encryption. Implementing encryption protocols.")
181
- apply_data_encryption(file)
182
-
174
+ security_issues.append(f" Missing Data Encryption. Implementing encryption protocols.")
175
+ apply_data_encryption(target_path)
176
+
183
177
  if not validation_feedback.get("rate_limiting", False):
184
- security_issues.append(f"{file}: No Rate Limiting detected. Implementing rate limiting & quotas.")
185
- apply_rate_limiting(file)
186
-
187
- if security_issues:
188
- for issue in security_issues:
189
- click.echo(f"⚠️ {issue}")
190
- click.echo("✅ Security measures have been enforced!")
191
- else:
192
- click.echo("✅ API Usage is secure. No changes needed.")
193
-
178
+ security_issues.append(f" No Rate Limiting detected. Implementing rate limiting & quotas.")
179
+ apply_rate_limiting(target_path)
180
+
181
+ if security_issues:
182
+ for issue in security_issues:
183
+ click.echo(f"⚠️ {issue}")
184
+ click.echo("✅ Security measures have been enforced!")
185
+ else:
186
+ click.echo("✅ API usage is secure. No changes needed.")
187
+
188
+ except Exception as e:
189
+ logging.error(f"❌ Error processing {target_path}: {str(e)}")
190
+ click.echo(f"❌ Error processing {target_path}: {str(e)}")
191
+
194
192
  logging.info("API Security Check Completed.")
195
193
 
194
+
196
195
  def validate_security_with_ai(code):
197
196
  """Use OpenAI to validate security measures in the given code."""
198
197
  prompt = f"""
@@ -201,162 +200,360 @@ def validate_security_with_ai(code):
201
200
  1. Secure API Authentication (OAuth or API Keys)
202
201
  2. Proper Data Encryption Protocols for sensitive data
203
202
  3. Rate Limiting and Quotas to prevent API abuse
204
-
203
+
205
204
  Return a JSON response with keys: authentication, encryption, rate_limiting, each set to True or False.
206
-
205
+
207
206
  Code:
208
207
  ```
209
208
  {code}
210
209
  ```
211
210
  """
212
-
213
- response = openai.ChatCompletion.create(
214
- model="gpt-4",
215
- messages=[{"role": "system", "content": prompt}]
216
- )
217
-
218
- result = response["choices"][0]["message"]["content"]
219
-
211
+
220
212
  try:
213
+ response = openai.ChatCompletion.create(
214
+ model="gpt-4",
215
+ messages=[{"role": "system", "content": prompt}],
216
+ )
217
+
218
+ result = response["choices"][0]["message"]["content"]
221
219
  return json.loads(result)
222
- except json.JSONDecodeError:
220
+
221
+ except Exception as e:
222
+ logging.error(f"Error in AI validation: {str(e)}")
223
223
  return {"authentication": False, "encryption": False, "rate_limiting": False}
224
224
 
225
+
225
226
  def apply_api_authentication(filepath):
226
227
  """Apply OAuth or API Key authentication to the specified file."""
227
228
  logging.info(f"Applying OAuth/API Key Authentication to {filepath}.")
228
- with open(filepath, "a") as f:
229
- f.write("\n# Added OAuth/API Key Authentication\n")
229
+ with open(filepath, "a", encoding="utf-8") as f:
230
+ f.write("\n# TODO: Implement OAuth/API Key Authentication\n")
231
+
230
232
 
231
233
  def apply_data_encryption(filepath):
232
234
  """Implement data encryption protocols in the specified file."""
233
235
  logging.info(f"Applying Data Encryption Protocols to {filepath}.")
234
- with open(filepath, "a") as f:
235
- f.write("\n# Implemented Data Encryption\n")
236
+ with open(filepath, "a", encoding="utf-8") as f:
237
+ f.write("\n# TODO: Implement Data Encryption\n")
238
+
236
239
 
237
240
  def apply_rate_limiting(filepath):
238
241
  """Implement API rate limiting and quotas in the specified file."""
239
242
  logging.info(f"Applying Rate Limiting & Quotas to {filepath}.")
240
- with open(filepath, "a") as f:
241
- f.write("\n# Enforced API Rate Limiting & Quotas\n")
243
+ with open(filepath, "a", encoding="utf-8") as f:
244
+ f.write("\n# TODO: Enforce API Rate Limiting & Quotas\n")
242
245
 
243
246
  @click.command()
244
- @click.argument("target")
247
+ @click.argument("parent_folder", required=True)
248
+ @click.argument("sub_folder", required=True)
245
249
  @click.argument("filename", required=False)
246
- def check_ethics(target, filename=None):
250
+ def check_ethics(parent_folder, sub_folder, filename=None):
247
251
  """Check code for efficiency, accuracy, and best practices."""
248
- click.echo("🔍 Running Code Ethics Check...")
249
- # Implement AI-based ethics validation here
250
- click.echo("✅ Ethics Check Completed!")
252
+ click.echo("\U0001F50D Running Code Ethics Check...")
253
+ ethics_issues = []
254
+
255
+ # Construct the full path
256
+ target_path = os.path.abspath(os.path.join(parent_folder, sub_folder))
257
+
258
+ if not os.path.isdir(target_path):
259
+ click.echo(f"❌ Error: '{target_path}' is not a valid directory.")
260
+ logging.error(f"Invalid directory provided: {target_path}")
261
+ return
262
+
263
+ # Determine files to check
264
+ if filename:
265
+ files_to_check = [os.path.join(target_path, filename)]
266
+ if not os.path.isfile(files_to_check[0]):
267
+ click.echo(f"❌ Error: '{files_to_check[0]}' is not a valid file.")
268
+ logging.error(f"Invalid file provided: {files_to_check[0]}")
269
+ return
270
+ else:
271
+ files_to_check = [
272
+ os.path.join(target_path, f) for f in os.listdir(target_path) if f.endswith(".py")
273
+ ]
274
+
275
+ for file in files_to_check:
276
+ try:
277
+ with open(file, "r", encoding="utf-8") as f:
278
+ code_content = f.read()
279
+
280
+ # Validate ethics using AI
281
+ validation_feedback = validate_ethics_with_ai(code_content)
282
+
283
+ if not validation_feedback.get("efficiency", False):
284
+ ethics_issues.append(f"{file}: Code may have performance inefficiencies.")
285
+
286
+ if not validation_feedback.get("accuracy", False):
287
+ ethics_issues.append(f"{file}: Code accuracy needs review for correctness.")
288
+
289
+ if not validation_feedback.get("best_practices", False):
290
+ ethics_issues.append(f"{file}: Code may not follow industry best practices.")
291
+
292
+ except Exception as e:
293
+ logging.error(f"❌ Error processing {file}: {str(e)}")
294
+ click.echo(f"❌ Error processing {file}: {str(e)}")
295
+
296
+ if ethics_issues:
297
+ for issue in ethics_issues:
298
+ click.echo(f"⚠️ {issue}")
299
+ click.echo("✅ Ethics Review Completed with Recommendations!")
300
+ else:
301
+ click.echo("✅ Code meets ethical standards. No issues detected.")
302
+
303
+ logging.info("Code Ethics Check Completed.")
304
+
305
+
306
+ def validate_ethics_with_ai(code):
307
+ """Use OpenAI to validate code ethics, efficiency, and best practices."""
308
+ prompt = f"""
309
+ Analyze the following Python code for ethical concerns in:
310
+ 1. Efficiency (performance optimization, unnecessary loops, redundant code)
311
+ 2. Accuracy (logical correctness, potential calculation errors)
312
+ 3. Best Practices (PEP8 compliance, maintainability, documentation)
313
+
314
+ Return a JSON response with keys: efficiency, accuracy, best_practices, each set to True or False.
315
+
316
+ Code:
317
+ ```
318
+ {code}
319
+ ```
320
+ """
321
+
322
+ try:
323
+ response = openai.ChatCompletion.create(
324
+ model="gpt-4",
325
+ messages=[{"role": "system", "content": prompt}],
326
+ )
327
+
328
+ result = response["choices"][0]["message"]["content"]
329
+ return json.loads(result)
330
+
331
+ except Exception as e:
332
+ logging.error(f"Error in AI validation: {str(e)}")
333
+ return {"efficiency": False, "accuracy": False, "best_practices": False}
251
334
 
252
335
  @click.command()
253
- @click.argument("target")
336
+ @click.argument("parent_folder")
337
+ @click.argument("sub_folder")
254
338
  @click.argument("filename")
255
- def doc(target, filename):
339
+ def doc(parent_folder, sub_folder, filename):
256
340
  """Generate README.md documentation for the given file."""
257
341
  click.echo("📄 Generating Documentation...")
258
- # Implement AI-based documentation generation here
259
- click.echo("✅ Documentation Created!")
342
+
343
+ # Construct the full file path
344
+ target_path = os.path.join(parent_folder, sub_folder)
345
+ file_path = os.path.join(target_path, filename)
346
+
347
+ # Validate directory existence
348
+ if not os.path.isdir(target_path):
349
+ click.echo(f"❌ Error: The directory '{target_path}' does not exist.")
350
+ return
351
+
352
+ # Validate file existence
353
+ if not os.path.isfile(file_path):
354
+ click.echo(f"❌ Error: The file '{file_path}' does not exist in the specified directory.")
355
+ return
356
+
357
+ readme_path = os.path.join(target_path, "README.md")
358
+
359
+ try:
360
+ with open(file_path, "r", encoding="utf-8") as source_file:
361
+ code_content = source_file.read()
362
+
363
+ # Generate documentation (Placeholder function, replace with AI-based generation)
364
+ documentation = generate_documentation(code_content)
365
+
366
+ # Write to README.md
367
+ with open(readme_path, "w", encoding="utf-8") as readme_file:
368
+ readme_file.write(documentation)
369
+
370
+ click.echo(f"✅ Documentation created for {file_path} -> {readme_path}")
371
+
372
+ except Exception as e:
373
+ logging.error(f"❌ Error processing {file_path}: {str(e)}")
374
+ click.echo(f"❌ Error processing {file_path}: {str(e)}")
375
+
376
+ def generate_documentation(code):
377
+ """Generate structured documentation based on the given Python code."""
378
+ return f"# Auto-Generated Documentation\n\n```python\n{code}\n```"
260
379
 
261
380
  @click.command()
262
- @click.argument("target")
263
- @click.argument("filename")
264
- def codex(target, filename):
265
- """Provide in-depth analysis and recommendations for the given file."""
381
+ @click.argument("parent_folder")
382
+ @click.argument("sub_folder")
383
+ @click.argument("filename", required=False)
384
+ def codex(parent_folder, sub_folder, filename=None):
385
+ """Provide in-depth analysis and recommendations for a file or all Python files in a directory."""
266
386
  click.echo("📚 Creating Code Codex Report...")
267
- # Implement AI-based code explanation and recommendations here
268
- click.echo("✅ Codex Report Generated!")
387
+
388
+ # Construct the full target path
389
+ target_path = os.path.join(parent_folder, sub_folder)
390
+
391
+ # Validate directory existence
392
+ if not os.path.isdir(target_path):
393
+ click.echo(f"❌ Error: The directory '{target_path}' does not exist.")
394
+ return
395
+
396
+ # Determine files to analyze
397
+ if filename:
398
+ file_path = os.path.join(target_path, filename)
399
+ if not os.path.isfile(file_path):
400
+ click.echo(f"❌ Error: The file '{file_path}' does not exist in the specified directory.")
401
+ return
402
+ files_to_analyze = [file_path]
403
+ else:
404
+ files_to_analyze = [os.path.join(target_path, f) for f in os.listdir(target_path) if f.endswith(".py")]
405
+
406
+ if not files_to_analyze:
407
+ click.echo("⚠️ No Python files found in the specified directory.")
408
+ return
409
+
410
+ for file in files_to_analyze:
411
+ codex_report_path = os.path.join(".\\docs/", "CODEX_REPORT.md")
412
+
413
+ try:
414
+ with open(file, "r", encoding="utf-8") as source_file:
415
+ code_content = source_file.read()
416
+
417
+ # Generate codex report (Placeholder function, replace with AI-based analysis)
418
+ report = generate_codex_report(code_content)
419
+
420
+ # Write report to CODEX_REPORT.md
421
+ with open(codex_report_path, "w", encoding="utf-8") as report_file:
422
+ report_file.write(report)
423
+
424
+ click.echo(f"✅ Codex Report generated for {file} -> {codex_report_path}")
425
+
426
+ except Exception as e:
427
+ logging.error(f"❌ Error processing {file}: {str(e)}")
428
+ click.echo(f"❌ Error processing {file}: {str(e)}")
429
+
430
+ def generate_codex_report(code):
431
+ """Generate an in-depth analysis and recommendations based on the given Python code."""
432
+ return f"# Code Analysis & Recommendations\n\n```python\n{code}\n```\n\n## Recommendations:\n- Improve efficiency\n- Enhance readability\n- Optimize performance\n"
269
433
 
270
434
  @click.command()
271
- @click.argument("target")
435
+ @click.argument("parent_folder")
436
+ @click.argument("sub_folder")
272
437
  @click.argument("filename", required=False)
273
- def regulate(target, filename=None):
438
+ def regulate(parent_folder, sub_folder, filename=None):
274
439
  """Ensure code compliance with GDPR, CCPA, AI Act, and ISO 42001 AI governance standards."""
275
440
  click.echo("🔍 Running Compliance & Regulation Check...")
441
+
276
442
  compliance_issues = []
277
-
278
- # Determine path to check
443
+
444
+ # Construct the full target path
445
+ target_path = os.path.join(parent_folder, sub_folder)
446
+
447
+ # Validate directory existence
448
+ if not os.path.isdir(target_path):
449
+ click.echo(f"❌ Error: The directory '{target_path}' does not exist.")
450
+ return
451
+
452
+ # Determine files to check
279
453
  if filename:
280
- files_to_check = [os.path.join(target, filename)]
454
+ file_path = os.path.join(target_path, filename)
455
+ if not os.path.isfile(file_path):
456
+ click.echo(f"❌ Error: The file '{file_path}' does not exist in the specified directory.")
457
+ return
458
+ files_to_check = [file_path]
281
459
  else:
282
- files_to_check = [os.path.join(target, f) for f in os.listdir(target) if f.endswith(".py")]
283
-
460
+ files_to_check = [os.path.join(target_path, f) for f in os.listdir(target_path) if f.endswith(".py")]
461
+
462
+ if not files_to_check:
463
+ click.echo("⚠️ No Python files found in the specified directory.")
464
+ return
465
+
284
466
  for file in files_to_check:
285
- with open(file, "r") as f:
286
- code_content = f.read()
287
-
288
- # Validate compliance using OpenAI
289
- compliance_feedback = validate_compliance_with_ai(code_content)
290
-
291
- if not compliance_feedback.get("gdpr", False):
292
- compliance_issues.append(f"{file}: GDPR compliance issues detected. Adjusting for data privacy.")
293
- apply_gdpr_compliance(file)
294
-
295
- if not compliance_feedback.get("ccpa", False):
296
- compliance_issues.append(f"{file}: CCPA compliance issues detected. Ensuring consumer rights protection.")
297
- apply_ccpa_compliance(file)
298
-
299
- if not compliance_feedback.get("ai_act", False):
300
- compliance_issues.append(f"{file}: AI Act risk classification missing. Implementing compliance measures.")
301
- apply_ai_act_compliance(file)
302
-
303
- if not compliance_feedback.get("iso_42001", False):
304
- compliance_issues.append(f"{file}: ISO 42001 AI governance framework not followed. Adjusting AI management protocols.")
305
- apply_iso_42001_compliance(file)
306
-
467
+ compliance_report_path = os.path.join("./configs/", "COMPLIANCE_REPORT.md")
468
+
469
+ try:
470
+ with open(file, "r", encoding="utf-8") as f:
471
+ code_content = f.read()
472
+
473
+ # Validate compliance (Placeholder function, replace with AI-based analysis)
474
+ compliance_feedback = validate_compliance_with_ai(code_content)
475
+
476
+ # Track issues and apply fixes
477
+ if not compliance_feedback.get("gdpr", False):
478
+ compliance_issues.append(f"{file}: GDPR compliance issues detected. Adjusting for data privacy.")
479
+ apply_gdpr_compliance(file)
480
+
481
+ if not compliance_feedback.get("ccpa", False):
482
+ compliance_issues.append(f"{file}: CCPA compliance issues detected. Ensuring consumer rights protection.")
483
+ apply_ccpa_compliance(file)
484
+
485
+ if not compliance_feedback.get("ai_act", False):
486
+ compliance_issues.append(f"{file}: AI Act risk classification missing. Implementing compliance measures.")
487
+ apply_ai_act_compliance(file)
488
+
489
+ if not compliance_feedback.get("iso_42001", False):
490
+ compliance_issues.append(f"{file}: ISO 42001 AI governance framework not followed. Adjusting AI management protocols.")
491
+ apply_iso_42001_compliance(file)
492
+
493
+ # Generate compliance report
494
+ with open(compliance_report_path, "w", encoding="utf-8") as report_file:
495
+ report_file.write(generate_compliance_report(file, compliance_feedback))
496
+
497
+ click.echo(f"✅ Compliance report generated for {file} -> {compliance_report_path}")
498
+
499
+ except Exception as e:
500
+ logging.error(f"❌ Error processing {file}: {str(e)}")
501
+ click.echo(f"❌ Error processing {file}: {str(e)}")
502
+
307
503
  if compliance_issues:
308
504
  for issue in compliance_issues:
309
505
  click.echo(f"⚠️ {issue}")
310
506
  click.echo("✅ Compliance measures have been enforced!")
311
507
  else:
312
508
  click.echo("✅ Code meets all compliance regulations. No changes needed.")
313
-
509
+
314
510
  logging.info("Compliance & Regulation Check Completed.")
315
511
 
316
512
  def validate_compliance_with_ai(code):
317
- """Use OpenAI to validate compliance measures in the given code."""
318
- prompt = f"""
319
- Analyze the following Python code for compliance with:
320
- 1. GDPR (Europe) - Ensure AI does not violate user data privacy.
321
- 2. CCPA (California) - Protect consumer rights in AI-driven applications.
322
- 3. AI Act (EU) - Classify AI systems under risk categories (Minimal, Limited, High).
323
- 4. ISO 42001 AI Management - Align with emerging AI governance frameworks.
324
-
325
- Return a JSON response with keys: gdpr, ccpa, ai_act, iso_42001, each set to True or False.
326
-
327
- Code:
328
- ```
329
- {code}
330
- ```
331
- """
332
-
333
- response = openai.ChatCompletion.create(
334
- model="gpt-4",
335
- messages=[{"role": "system", "content": prompt}]
336
- )
337
-
338
- result = response["choices"][0]["message"]["content"]
339
-
340
- try:
341
- return json.loads(result)
342
- except json.JSONDecodeError:
343
- return {"gdpr": False, "ccpa": False, "ai_act": False, "iso_42001": False}
513
+ """Analyze code for compliance with GDPR, CCPA, AI Act, and ISO 42001."""
514
+ return {
515
+ "gdpr": True,
516
+ "ccpa": True,
517
+ "ai_act": False,
518
+ "iso_42001": False
519
+ } # Replace with AI-based compliance validation
344
520
 
345
521
  def apply_gdpr_compliance(filepath):
346
- logging.info(f"Applied GDPR compliance measures to {filepath}.")
522
+ logging.info(f"Applying GDPR compliance to {filepath}.")
347
523
 
348
524
  def apply_ccpa_compliance(filepath):
349
- logging.info(f"Applied CCPA compliance measures to {filepath}.")
525
+ logging.info(f"Applying CCPA compliance to {filepath}.")
350
526
 
351
527
  def apply_ai_act_compliance(filepath):
352
- logging.info(f"Applied AI Act compliance measures to {filepath}.")
528
+ logging.info(f"Applying AI Act compliance to {filepath}.")
353
529
 
354
530
  def apply_iso_42001_compliance(filepath):
355
- logging.info(f"Applied ISO 42001 AI governance framework to {filepath}.")
531
+ logging.info(f"Applying ISO 42001 AI governance framework to {filepath}.")
532
+
533
+ def generate_compliance_report(filepath, feedback):
534
+ """Generate a structured compliance report."""
535
+ return f"""
536
+ # Compliance Report for {os.path.basename(filepath)}
537
+
538
+ ## Compliance Status:
539
+ - **GDPR:** {"✅ Compliant" if feedback.get("gdpr") else "❌ Not Compliant"}
540
+ - **CCPA:** {"✅ Compliant" if feedback.get("ccpa") else "❌ Not Compliant"}
541
+ - **AI Act:** {"✅ Compliant" if feedback.get("ai_act") else "❌ Not Compliant"}
542
+ - **ISO 42001:** {"✅ Compliant" if feedback.get("iso_42001") else "❌ Not Compliant"}
543
+
544
+ ## Recommendations:
545
+ - { "Ensure data privacy measures are in place." if not feedback.get("gdpr") else "GDPR compliance verified." }
546
+ - { "Strengthen consumer rights protection." if not feedback.get("ccpa") else "CCPA compliance verified." }
547
+ - { "Classify AI system under the AI Act risk framework." if not feedback.get("ai_act") else "AI Act compliance verified." }
548
+ - { "Align with ISO 42001 AI governance framework." if not feedback.get("iso_42001") else "ISO 42001 compliance verified." }
549
+
550
+ ---
356
551
 
552
+ 🛠 *Generated by Compliance Checker*
553
+ """
357
554
 
358
555
  # Add commands to Maya CLI
359
- maya.add_command(isSecured)
556
+ maya.add_command(is_secured)
360
557
  maya.add_command(check_ethics)
361
558
  maya.add_command(doc)
362
559
  maya.add_command(codex)
maya_cli/refactor.py CHANGED
@@ -45,8 +45,8 @@ def write_file(file_path, content):
45
45
  except Exception as e:
46
46
  error_msg = f"❌ Error writing {file_path}: {str(e)}"
47
47
 
48
- logging.error(error_msg)
49
- click.echo(error_msg)
48
+ logging.error(error_msg)
49
+ click.echo(error_msg)
50
50
 
51
51
  def refactor_code_with_openai(code):
52
52
  """Sends code to OpenAI for best-practices refactoring."""
@@ -75,15 +75,16 @@ def refactor_code_with_openai(code):
75
75
  optimized_code = response["choices"][0]["message"]["content"].strip()
76
76
  logging.debug(f"OpenAI API response received successfully.")
77
77
  return optimized_code
78
- except openai.error.OpenAIError as e:
78
+ except openai.OpenAIError as e: # Corrected
79
79
  error_msg = f"❌ OpenAI API Error: {str(e)}"
80
80
  except Exception as e:
81
81
  error_msg = f"❌ Unexpected Error: {str(e)}"
82
-
82
+
83
83
  logging.error(error_msg)
84
84
  click.echo(error_msg)
85
85
  return code # Return original code if API call fails
86
86
 
87
+
87
88
  def process_directory(directory, filename=None):
88
89
  """Scans the given directory and refactors specified files."""
89
90
  if not os.path.exists(directory):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: maya-cli
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Maya CLI - AI Project Generator
5
5
  Home-page: https://github.com/anointingmayami/Maya.ai
6
6
  Author: King Anointing Joseph Mayami
@@ -0,0 +1,11 @@
1
+ maya_cli/__init__.py,sha256=d7ktJFCti7GbZZJJHwTLpLy9EyI3lJmkqtL3YnR-cm8,69
2
+ maya_cli/cli.py,sha256=jwOLoXsmz9Af41-tyukTmGMORjBoz8hJ9QikxdgbIFs,21928
3
+ maya_cli/project_generator.py,sha256=AB9uV_lBe-KPywMJ3uDH9YPSTRHXFP7qzqpPdxDB5GY,2967
4
+ maya_cli/refactor.py,sha256=ipi3iabQOcyQyJn20PErpgi-Hb4cb8f8p7zW0HO22_s,3890
5
+ maya_cli/scripts/__init__.py,sha256=yY3Tbs-t4HSl4I0Ev0RcHMnHU7SwljlWRveiRJkeCB8,10
6
+ maya_cli/scripts/optimize.py,sha256=UqDIHyyYPXZkhAb4GSvjbN0IvwXM2aFnpSh4k0Jzobo,4820
7
+ maya_cli-0.1.3.dist-info/METADATA,sha256=mPsFwPZ9C399qTlHxcHC7TpSoHNn6hr-_46XlAjBaes,3469
8
+ maya_cli-0.1.3.dist-info/WHEEL,sha256=nn6H5-ilmfVryoAQl3ZQ2l8SH5imPWFpm1A5FgEuFV4,91
9
+ maya_cli-0.1.3.dist-info/entry_points.txt,sha256=K4mI6r7-idKvOmz7zpMpK6HaEnraRoRt4nSW1jTfCgE,43
10
+ maya_cli-0.1.3.dist-info/top_level.txt,sha256=nZzw8c5hxqres4pU9UUFCTjwBSHUDNjqCTM7yOFnnrE,9
11
+ maya_cli-0.1.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.8.0)
2
+ Generator: setuptools (75.8.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,11 +0,0 @@
1
- maya_cli/__init__.py,sha256=d7ktJFCti7GbZZJJHwTLpLy9EyI3lJmkqtL3YnR-cm8,69
2
- maya_cli/cli.py,sha256=SuTi2pzEEYPEHSVfVIoi75ts-QHKLFeXYWmUd53tm-s,13859
3
- maya_cli/project_generator.py,sha256=AB9uV_lBe-KPywMJ3uDH9YPSTRHXFP7qzqpPdxDB5GY,2967
4
- maya_cli/refactor.py,sha256=THX6VBKzFztFKEwjREGehQJaWABJYZ_4LaTHrqr20VE,3877
5
- maya_cli/scripts/__init__.py,sha256=yY3Tbs-t4HSl4I0Ev0RcHMnHU7SwljlWRveiRJkeCB8,10
6
- maya_cli/scripts/optimize.py,sha256=UqDIHyyYPXZkhAb4GSvjbN0IvwXM2aFnpSh4k0Jzobo,4820
7
- maya_cli-0.1.2.dist-info/METADATA,sha256=eYq9N-4CuBM4vawOf2xM-_Pc0u11TlcO2VvB6NATqDg,3469
8
- maya_cli-0.1.2.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
9
- maya_cli-0.1.2.dist-info/entry_points.txt,sha256=K4mI6r7-idKvOmz7zpMpK6HaEnraRoRt4nSW1jTfCgE,43
10
- maya_cli-0.1.2.dist-info/top_level.txt,sha256=nZzw8c5hxqres4pU9UUFCTjwBSHUDNjqCTM7yOFnnrE,9
11
- maya_cli-0.1.2.dist-info/RECORD,,