Upload __init__ .py
Browse files- __init__ .py +62 -0
__init__ .py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
class SelfCodingAI:
|
| 5 |
+
def __init__(self, name="SelfCoder", code_folder="generated_code"):
|
| 6 |
+
self.name = name
|
| 7 |
+
self.code_folder = code_folder
|
| 8 |
+
os.makedirs(self.code_folder, exist_ok=True)
|
| 9 |
+
|
| 10 |
+
def generate_code(self, task_description):
|
| 11 |
+
"""
|
| 12 |
+
Very basic code generation logic: generates code for some predefined tasks.
|
| 13 |
+
You can extend this to integrate GPT-like models or complex code synthesis.
|
| 14 |
+
"""
|
| 15 |
+
if "hello world" in task_description.lower():
|
| 16 |
+
code = 'print("Hello, world!")'
|
| 17 |
+
elif "factorial" in task_description.lower():
|
| 18 |
+
code = (
|
| 19 |
+
"def factorial(n):\n"
|
| 20 |
+
" return 1 if n==0 else n * factorial(n-1)\n\n"
|
| 21 |
+
"print(factorial(5))"
|
| 22 |
+
)
|
| 23 |
+
else:
|
| 24 |
+
code = "# Code generation for this task is not implemented yet.\n"
|
| 25 |
+
|
| 26 |
+
return code
|
| 27 |
+
|
| 28 |
+
def save_code(self, code, filename="generated_code.py"):
|
| 29 |
+
filepath = os.path.join(self.code_folder, filename)
|
| 30 |
+
with open(filepath, "w", encoding="utf-8") as f:
|
| 31 |
+
f.write(code)
|
| 32 |
+
print(f"Code saved to {filepath}")
|
| 33 |
+
return filepath
|
| 34 |
+
|
| 35 |
+
def self_improve(self, feedback):
|
| 36 |
+
"""
|
| 37 |
+
Placeholder for self-improvement method.
|
| 38 |
+
In future, AI could modify its own code based on feedback or test results.
|
| 39 |
+
"""
|
| 40 |
+
print(f"{self.name} received feedback: {feedback}")
|
| 41 |
+
print("Self-improvement not yet implemented.")
|
| 42 |
+
|
| 43 |
+
def run_code(self, filepath):
|
| 44 |
+
print(f"Running code from {filepath}:\n")
|
| 45 |
+
try:
|
| 46 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 47 |
+
code = f.read()
|
| 48 |
+
exec(code, {})
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error during code execution: {e}")
|
| 51 |
+
|
| 52 |
+
# Example usage
|
| 53 |
+
ai = SelfCodingAI()
|
| 54 |
+
|
| 55 |
+
task = "Write a factorial function in Python"
|
| 56 |
+
generated = ai.generate_code(task)
|
| 57 |
+
|
| 58 |
+
file_path = ai.save_code(generated, "factorial.py")
|
| 59 |
+
ai.run_code(file_path)
|
| 60 |
+
|
| 61 |
+
# Example of self-improvement placeholder call
|
| 62 |
+
ai.self_improve("The factorial function passed all test cases.")
|