maya-cli 0.1.2__tar.gz → 0.1.3__tar.gz

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.
@@ -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,567 @@
1
+ import os
2
+ import sys
3
+ import click
4
+ import logging
5
+ import importlib.util
6
+ from dotenv import load_dotenv, set_key
7
+ import openai
8
+ from .project_generator import create_project_structure, PROJECT_STRUCTURE
9
+ from .refactor import process_directory
10
+ from maya_cli.scripts import optimize # This will trigger optimize_event_handler automatically
11
+
12
+
13
+ # Setup logging
14
+ LOG_FILE = "maya_cli.log"
15
+ logging.basicConfig(
16
+ filename=LOG_FILE,
17
+ level=logging.DEBUG,
18
+ format="%(asctime)s - %(levelname)s - %(message)s"
19
+ )
20
+
21
+ # Load environment variables from .env
22
+ load_dotenv()
23
+
24
+
25
+ @click.group()
26
+ def maya():
27
+ """Maya CLI - AI Project Generator"""
28
+ pass
29
+
30
+
31
+ @click.command()
32
+ @click.argument("project_name")
33
+ def create(project_name):
34
+ """Create a new AI project structure"""
35
+ try:
36
+ base_path = os.path.join(os.getcwd(), project_name)
37
+ if os.path.exists(base_path):
38
+ click.echo(f"Error: Project '{project_name}' already exists.")
39
+ logging.error(f"Project '{project_name}' already exists.")
40
+ return
41
+
42
+ os.makedirs(base_path, exist_ok=True)
43
+ create_project_structure(base_path, PROJECT_STRUCTURE)
44
+ click.echo(f"✅ AI project '{project_name}' created successfully!")
45
+ logging.info(f"Project '{project_name}' created successfully at {base_path}")
46
+
47
+ except Exception as e:
48
+ logging.error(f"Error while creating project: {str(e)}")
49
+ click.echo(f"❌ An error occurred: {str(e)}")
50
+
51
+ @click.command()
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]"""
55
+ click.echo("🚀 Running Best Practices Check...")
56
+
57
+ base_path = os.getcwd()
58
+ target_path = os.path.join(base_path, *path)
59
+
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.")
70
+ return
71
+
72
+ click.echo("✅ Best practices check completed!")
73
+
74
+
75
+ @click.command()
76
+ @click.argument("key")
77
+ @click.argument("value")
78
+ def set_env(key, value):
79
+ """Set an environment variable in .env file"""
80
+ env_file = ".env"
81
+
82
+ try:
83
+ if not os.path.exists(env_file):
84
+ with open(env_file, "w") as f:
85
+ f.write("# Maya CLI Environment Variables\n")
86
+ logging.info("Created new .env file.")
87
+
88
+ set_key(env_file, key, value)
89
+ click.echo(f"✅ Environment variable '{key}' set successfully!")
90
+ logging.info(f"Set environment variable: {key}={value}")
91
+
92
+ except Exception as e:
93
+ logging.error(f"Error setting environment variable {key}: {str(e)}")
94
+ click.echo(f"❌ Error setting environment variable: {str(e)}")
95
+
96
+ @click.command()
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))
105
+
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
110
+
111
+ # Inject the import statement into the file
112
+ inject_import(target_path)
113
+
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}")
134
+
135
+ except Exception as e:
136
+ logging.error(f"Error injecting import into '{filepath}': {str(e)}")
137
+ click.echo(f"❌ Error injecting import into '{filepath}': {str(e)}")
138
+
139
+ import os
140
+ import json
141
+ import click
142
+ import logging
143
+ import openai
144
+
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...")
152
+
153
+ # Construct the full file path
154
+ target_path = os.path.abspath(os.path.join(parent_folder, sub_folder, filename))
155
+
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
160
+
161
+ try:
162
+ with open(target_path, "r", encoding="utf-8") as f:
163
+ code_content = f.read()
164
+
165
+ # Validate security using AI
166
+ validation_feedback = validate_security_with_ai(code_content)
167
+ security_issues = []
168
+
169
+ if not validation_feedback.get("authentication", False):
170
+ security_issues.append(f"❌ Missing API Authentication. Applying OAuth/API Key authentication.")
171
+ apply_api_authentication(target_path)
172
+
173
+ if not validation_feedback.get("encryption", False):
174
+ security_issues.append(f"❌ Missing Data Encryption. Implementing encryption protocols.")
175
+ apply_data_encryption(target_path)
176
+
177
+ if not validation_feedback.get("rate_limiting", False):
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
+
192
+ logging.info("API Security Check Completed.")
193
+
194
+
195
+ def validate_security_with_ai(code):
196
+ """Use OpenAI to validate security measures in the given code."""
197
+ prompt = f"""
198
+ Analyze the following Python code for API security vulnerabilities.
199
+ Identify if the code implements:
200
+ 1. Secure API Authentication (OAuth or API Keys)
201
+ 2. Proper Data Encryption Protocols for sensitive data
202
+ 3. Rate Limiting and Quotas to prevent API abuse
203
+
204
+ Return a JSON response with keys: authentication, encryption, rate_limiting, each set to True or False.
205
+
206
+ Code:
207
+ ```
208
+ {code}
209
+ ```
210
+ """
211
+
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"]
219
+ return json.loads(result)
220
+
221
+ except Exception as e:
222
+ logging.error(f"Error in AI validation: {str(e)}")
223
+ return {"authentication": False, "encryption": False, "rate_limiting": False}
224
+
225
+
226
+ def apply_api_authentication(filepath):
227
+ """Apply OAuth or API Key authentication to the specified file."""
228
+ logging.info(f"Applying OAuth/API Key Authentication to {filepath}.")
229
+ with open(filepath, "a", encoding="utf-8") as f:
230
+ f.write("\n# TODO: Implement OAuth/API Key Authentication\n")
231
+
232
+
233
+ def apply_data_encryption(filepath):
234
+ """Implement data encryption protocols in the specified file."""
235
+ logging.info(f"Applying Data Encryption Protocols to {filepath}.")
236
+ with open(filepath, "a", encoding="utf-8") as f:
237
+ f.write("\n# TODO: Implement Data Encryption\n")
238
+
239
+
240
+ def apply_rate_limiting(filepath):
241
+ """Implement API rate limiting and quotas in the specified file."""
242
+ logging.info(f"Applying Rate Limiting & Quotas to {filepath}.")
243
+ with open(filepath, "a", encoding="utf-8") as f:
244
+ f.write("\n# TODO: Enforce API Rate Limiting & Quotas\n")
245
+
246
+ @click.command()
247
+ @click.argument("parent_folder", required=True)
248
+ @click.argument("sub_folder", required=True)
249
+ @click.argument("filename", required=False)
250
+ def check_ethics(parent_folder, sub_folder, filename=None):
251
+ """Check code for efficiency, accuracy, and best practices."""
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}
334
+
335
+ @click.command()
336
+ @click.argument("parent_folder")
337
+ @click.argument("sub_folder")
338
+ @click.argument("filename")
339
+ def doc(parent_folder, sub_folder, filename):
340
+ """Generate README.md documentation for the given file."""
341
+ click.echo("📄 Generating Documentation...")
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```"
379
+
380
+ @click.command()
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."""
386
+ click.echo("📚 Creating Code Codex Report...")
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"
433
+
434
+ @click.command()
435
+ @click.argument("parent_folder")
436
+ @click.argument("sub_folder")
437
+ @click.argument("filename", required=False)
438
+ def regulate(parent_folder, sub_folder, filename=None):
439
+ """Ensure code compliance with GDPR, CCPA, AI Act, and ISO 42001 AI governance standards."""
440
+ click.echo("🔍 Running Compliance & Regulation Check...")
441
+
442
+ compliance_issues = []
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
453
+ if 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]
459
+ else:
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
+
466
+ for file in files_to_check:
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
+
503
+ if compliance_issues:
504
+ for issue in compliance_issues:
505
+ click.echo(f"⚠️ {issue}")
506
+ click.echo("✅ Compliance measures have been enforced!")
507
+ else:
508
+ click.echo("✅ Code meets all compliance regulations. No changes needed.")
509
+
510
+ logging.info("Compliance & Regulation Check Completed.")
511
+
512
+ def validate_compliance_with_ai(code):
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
520
+
521
+ def apply_gdpr_compliance(filepath):
522
+ logging.info(f"Applying GDPR compliance to {filepath}.")
523
+
524
+ def apply_ccpa_compliance(filepath):
525
+ logging.info(f"Applying CCPA compliance to {filepath}.")
526
+
527
+ def apply_ai_act_compliance(filepath):
528
+ logging.info(f"Applying AI Act compliance to {filepath}.")
529
+
530
+ def apply_iso_42001_compliance(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
+ ---
551
+
552
+ 🛠 *Generated by Compliance Checker*
553
+ """
554
+
555
+ # Add commands to Maya CLI
556
+ maya.add_command(is_secured)
557
+ maya.add_command(check_ethics)
558
+ maya.add_command(doc)
559
+ maya.add_command(codex)
560
+ maya.add_command(regulate)
561
+ maya.add_command(create)
562
+ maya.add_command(check_best_practices)
563
+ maya.add_command(set_env)
564
+ maya.add_command(optimize)
565
+
566
+ if __name__ == "__main__":
567
+ maya()
@@ -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
@@ -5,7 +5,7 @@ from setuptools import setup, find_packages
5
5
 
6
6
  setup(
7
7
  name="maya-cli",
8
- version="0.1.2",
8
+ version="0.1.3",
9
9
  author="King Anointing Joseph Mayami",
10
10
  author_email="anointingmayami@gmail.com",
11
11
  description="Maya CLI - AI Project Generator",
@@ -1,370 +0,0 @@
1
- import os
2
- import sys
3
- import click
4
- import logging
5
- import importlib.util
6
- from dotenv import load_dotenv, set_key
7
- import openai
8
- from .project_generator import create_project_structure, PROJECT_STRUCTURE
9
- from .refactor import process_directory
10
- from maya_cli.scripts import optimize # This will trigger optimize_event_handler automatically
11
-
12
-
13
- # Setup logging
14
- LOG_FILE = "maya_cli.log"
15
- logging.basicConfig(
16
- filename=LOG_FILE,
17
- level=logging.DEBUG,
18
- format="%(asctime)s - %(levelname)s - %(message)s"
19
- )
20
-
21
- # Load environment variables from .env
22
- load_dotenv()
23
-
24
-
25
- @click.group()
26
- def maya():
27
- """Maya CLI - AI Project Generator"""
28
- pass
29
-
30
-
31
- @click.command()
32
- @click.argument("project_name")
33
- def create(project_name):
34
- """Create a new AI project structure"""
35
- try:
36
- base_path = os.path.join(os.getcwd(), project_name)
37
- if os.path.exists(base_path):
38
- click.echo(f"Error: Project '{project_name}' already exists.")
39
- logging.error(f"Project '{project_name}' already exists.")
40
- return
41
-
42
- os.makedirs(base_path, exist_ok=True)
43
- create_project_structure(base_path, PROJECT_STRUCTURE)
44
- click.echo(f"✅ AI project '{project_name}' created successfully!")
45
- logging.info(f"Project '{project_name}' created successfully at {base_path}")
46
-
47
- except Exception as e:
48
- logging.error(f"Error while creating project: {str(e)}")
49
- click.echo(f"❌ An error occurred: {str(e)}")
50
-
51
-
52
- @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]"""
57
- click.echo("🚀 Running Best Practices Check...")
58
- base_path = os.getcwd()
59
- target_directory = os.path.join(base_path, folder)
60
-
61
- if not os.path.exists(target_directory):
62
- click.echo(f"❌ Folder '{folder}' does not exist.")
63
- return
64
-
65
- process_directory(target_directory, filename)
66
- click.echo("✅ Best practices check completed!")
67
-
68
-
69
- @click.command()
70
- @click.argument("key")
71
- @click.argument("value")
72
- def set_env(key, value):
73
- """Set an environment variable in .env file"""
74
- env_file = ".env"
75
-
76
- try:
77
- if not os.path.exists(env_file):
78
- with open(env_file, "w") as f:
79
- f.write("# Maya CLI Environment Variables\n")
80
- logging.info("Created new .env file.")
81
-
82
- set_key(env_file, key, value)
83
- click.echo(f"✅ Environment variable '{key}' set successfully!")
84
- logging.info(f"Set environment variable: {key}={value}")
85
-
86
- except Exception as e:
87
- logging.error(f"Error setting environment variable {key}: {str(e)}")
88
- click.echo(f"❌ Error setting environment variable: {str(e)}")
89
-
90
-
91
- @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
-
109
-
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)
117
-
118
- click.echo(f"✅ Optimization applied to {filepath}")
119
- logging.info(f"Optimization applied to {filepath}")
120
-
121
- if fine_tune_enabled and hasattr(optimize_module, "fine_tune_model"):
122
- optimize_module.fine_tune_model()
123
- click.echo("🚀 Fine-tuning enabled!")
124
-
125
- 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
-
137
-
138
- def optimize_project(fine_tune_enabled):
139
- """Optimize the entire project by importing optimize.py globally."""
140
- try:
141
- import scripts.optimize
142
-
143
- click.echo("✅ Project-wide optimization applied!")
144
- logging.info("Project-wide optimization applied.")
145
-
146
- if fine_tune_enabled and hasattr(scripts.optimize, "fine_tune_model"):
147
- scripts.optimize.fine_tune_model()
148
- click.echo("🚀 Fine-tuning enabled!")
149
-
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)}")
153
-
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:
170
- code_content = f.read()
171
-
172
- # Validate security using OpenAI
173
- validation_feedback = validate_security_with_ai(code_content)
174
-
175
- 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
-
179
- 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
-
183
- 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
-
194
- logging.info("API Security Check Completed.")
195
-
196
- def validate_security_with_ai(code):
197
- """Use OpenAI to validate security measures in the given code."""
198
- prompt = f"""
199
- Analyze the following Python code for API security vulnerabilities.
200
- Identify if the code implements:
201
- 1. Secure API Authentication (OAuth or API Keys)
202
- 2. Proper Data Encryption Protocols for sensitive data
203
- 3. Rate Limiting and Quotas to prevent API abuse
204
-
205
- Return a JSON response with keys: authentication, encryption, rate_limiting, each set to True or False.
206
-
207
- Code:
208
- ```
209
- {code}
210
- ```
211
- """
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
-
220
- try:
221
- return json.loads(result)
222
- except json.JSONDecodeError:
223
- return {"authentication": False, "encryption": False, "rate_limiting": False}
224
-
225
- def apply_api_authentication(filepath):
226
- """Apply OAuth or API Key authentication to the specified file."""
227
- 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")
230
-
231
- def apply_data_encryption(filepath):
232
- """Implement data encryption protocols in the specified file."""
233
- 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
-
237
- def apply_rate_limiting(filepath):
238
- """Implement API rate limiting and quotas in the specified file."""
239
- 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")
242
-
243
- @click.command()
244
- @click.argument("target")
245
- @click.argument("filename", required=False)
246
- def check_ethics(target, filename=None):
247
- """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!")
251
-
252
- @click.command()
253
- @click.argument("target")
254
- @click.argument("filename")
255
- def doc(target, filename):
256
- """Generate README.md documentation for the given file."""
257
- click.echo("📄 Generating Documentation...")
258
- # Implement AI-based documentation generation here
259
- click.echo("✅ Documentation Created!")
260
-
261
- @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."""
266
- click.echo("📚 Creating Code Codex Report...")
267
- # Implement AI-based code explanation and recommendations here
268
- click.echo("✅ Codex Report Generated!")
269
-
270
- @click.command()
271
- @click.argument("target")
272
- @click.argument("filename", required=False)
273
- def regulate(target, filename=None):
274
- """Ensure code compliance with GDPR, CCPA, AI Act, and ISO 42001 AI governance standards."""
275
- click.echo("🔍 Running Compliance & Regulation Check...")
276
- compliance_issues = []
277
-
278
- # Determine path to check
279
- if filename:
280
- files_to_check = [os.path.join(target, filename)]
281
- else:
282
- files_to_check = [os.path.join(target, f) for f in os.listdir(target) if f.endswith(".py")]
283
-
284
- 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
-
307
- if compliance_issues:
308
- for issue in compliance_issues:
309
- click.echo(f"⚠️ {issue}")
310
- click.echo("✅ Compliance measures have been enforced!")
311
- else:
312
- click.echo("✅ Code meets all compliance regulations. No changes needed.")
313
-
314
- logging.info("Compliance & Regulation Check Completed.")
315
-
316
- 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}
344
-
345
- def apply_gdpr_compliance(filepath):
346
- logging.info(f"Applied GDPR compliance measures to {filepath}.")
347
-
348
- def apply_ccpa_compliance(filepath):
349
- logging.info(f"Applied CCPA compliance measures to {filepath}.")
350
-
351
- def apply_ai_act_compliance(filepath):
352
- logging.info(f"Applied AI Act compliance measures to {filepath}.")
353
-
354
- def apply_iso_42001_compliance(filepath):
355
- logging.info(f"Applied ISO 42001 AI governance framework to {filepath}.")
356
-
357
-
358
- # Add commands to Maya CLI
359
- maya.add_command(isSecured)
360
- maya.add_command(check_ethics)
361
- maya.add_command(doc)
362
- maya.add_command(codex)
363
- maya.add_command(regulate)
364
- maya.add_command(create)
365
- maya.add_command(check_best_practices)
366
- maya.add_command(set_env)
367
- maya.add_command(optimize)
368
-
369
- if __name__ == "__main__":
370
- maya()
File without changes
File without changes
File without changes
File without changes