-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeator1.2.py
More file actions
254 lines (201 loc) · 8.88 KB
/
codeator1.2.py
File metadata and controls
254 lines (201 loc) · 8.88 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
import tkinter as tk
from tkinter import filedialog, messagebox, Toplevel
import ast
import os
import re
selected_to_remove = set()
current_code = ""
delete_comments_var = None # checkbox control
def analyze_code(code: str):
global current_code
current_code = code
try:
tree = ast.parse(code)
except Exception as e:
return f"⚠️ Could not parse code:\n{e}"
analysis = {
"imports": [],
"globals": [],
"functions": [],
"classes": {},
"comments": [],
"ui_elements": []
}
for node in tree.body:
if isinstance(node, ast.Import):
for alias in node.names:
analysis["imports"].append(alias.name)
elif isinstance(node, ast.ImportFrom):
mod = node.module if node.module else ""
for alias in node.names:
analysis["imports"].append(f"{mod}.{alias.name}")
elif isinstance(node, ast.FunctionDef):
analysis["functions"].append(node.name)
elif isinstance(node, ast.ClassDef):
methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
analysis["classes"][node.name] = methods
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
analysis["globals"].append(target.id)
for line in code.splitlines():
stripped = line.strip()
if stripped.startswith("#"):
analysis["comments"].append(stripped)
if "pygame.display" in code or "pygame.init" in code:
analysis["ui_elements"].append("pygame UI")
if "tkinter" in code:
analysis["ui_elements"].append("tkinter UI")
return analysis
def build_analysis_display(analysis):
output_box.config(state="normal")
output_box.delete("1.0", tk.END)
output_box.insert(tk.END, "=== 🧩 CODEATOR ANALYSIS ===\n\n")
output_box.insert(tk.END, "📦 Imports:\n")
for i in analysis["imports"]:
output_box.insert(tk.END, f" - {i}\n")
output_box.insert(tk.END, "\n🌍 Globals:\n")
for g in analysis["globals"]:
output_box.insert(tk.END, f" - {g}\n")
output_box.insert(tk.END, "\n🔧 Functions:\n")
for f in analysis["functions"]:
tag = f"func_{f}"
output_box.insert(tk.END, f" - {f}\n", tag)
output_box.tag_bind(tag, "<Button-1>", lambda e, name=f: toggle_selection(name))
output_box.tag_config(tag, foreground="blue", underline=True)
output_box.insert(tk.END, "\n🏗️ Classes & Methods:\n")
for cls, methods in analysis["classes"].items():
tag = f"class_{cls}"
output_box.insert(tk.END, f" - {cls}\n", tag)
output_box.tag_bind(tag, "<Button-1>", lambda e, name=cls: toggle_selection(name))
output_box.tag_config(tag, foreground="purple", underline=True)
for m in methods:
output_box.insert(tk.END, f" * {m}\n")
output_box.insert(tk.END, "\n💬 Comments:\n")
for c in analysis["comments"]:
output_box.insert(tk.END, f" {c}\n")
output_box.insert(tk.END, "\n🖥️ UI Elements:\n")
for ui in analysis["ui_elements"]:
output_box.insert(tk.END, f" - {ui}\n")
output_box.insert(tk.END, "\n✅ Done.\n")
output_box.config(state="disabled")
def toggle_selection(name):
tag = f"func_{name}" if f"func_{name}" in output_box.tag_names() else f"class_{name}"
if name in selected_to_remove:
selected_to_remove.remove(name)
output_box.tag_config(tag, foreground="blue" if tag.startswith("func") else "purple", background="white")
else:
selected_to_remove.add(name)
output_box.tag_config(tag, foreground="white", background="red")
def remove_selected_items(code, items_to_remove):
lines = code.splitlines()
new_lines = []
skip_block = False
indent_level = None
name_pattern = re.compile(r'^\s*(def|class)\s+(\w+)')
for i, line in enumerate(lines):
match = name_pattern.match(line)
if match:
kind, name = match.groups()
if name in items_to_remove:
skip_block = True
indent_level = len(line) - len(line.lstrip())
continue # skip the line
if skip_block:
current_indent = len(line) - len(line.lstrip())
if line.strip() == "":
continue
if current_indent <= indent_level:
skip_block = False
indent_level = None
else:
continue
if not skip_block:
new_lines.append(line)
cleaned = "\n".join(new_lines)
# remove multiple blank lines
cleaned = re.sub(r'\n\s*\n\s*\n+', '\n\n', cleaned)
return cleaned
def remove_comments(code):
# Remove full-line and inline comments
cleaned = re.sub(r'(?m)^\s*#.*$', '', code) # full-line comments
cleaned = re.sub(r'(?m)([^\'"#]*)(#.*$)', lambda m: m.group(1) if '"' not in m.group(0) and "'" not in m.group(0) else m.group(0), cleaned)
cleaned = re.sub(r'\n\s*\n+', '\n\n', cleaned) # tidy up empty lines
return cleaned
def export_cleaned():
if not current_code.strip():
messagebox.showwarning("No Code", "Please analyze code first.")
return
cleaned = remove_selected_items(current_code, selected_to_remove)
if delete_comments_var.get():
cleaned = remove_comments(cleaned)
popup = Toplevel(root)
popup.title("🧹 Cleaned Code Export")
popup.geometry("800x600")
tk.Label(popup, text="Your cleaned code:", font=("Arial", 12, "bold")).pack(pady=5)
text_box = tk.Text(popup, wrap="word", font=("Courier", 10))
text_box.pack(fill="both", expand=True)
text_box.insert(tk.END, cleaned)
def save_to_file():
path = filedialog.asksaveasfilename(defaultextension=".py", filetypes=[("Python Files", "*.py")])
if path:
with open(path, "w", encoding="utf-8") as f:
f.write(cleaned)
messagebox.showinfo("Exported", f"File saved to {path}")
tk.Button(popup, text="💾 Save as .py", command=save_to_file, bg="#4CAF50", fg="white").pack(pady=5)
def analyze_button_click():
code = code_input.get("1.0", tk.END)
analysis = analyze_code(code)
if isinstance(analysis, str):
output_box.config(state="normal")
output_box.delete("1.0", tk.END)
output_box.insert(tk.END, analysis)
output_box.config(state="disabled")
else:
build_analysis_display(analysis)
def open_file():
path = filedialog.askopenfilename(
title="Select a Python file",
filetypes=[("Python Files", "*.py")]
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as f:
code = f.read()
code_input.delete("1.0", tk.END)
code_input.insert(tk.END, code)
messagebox.showinfo("File Loaded", f"Loaded {os.path.basename(path)}")
except Exception as e:
messagebox.showerror("Error", f"Could not open file:\n{e}")
# --- UI SETUP ---
root = tk.Tk()
root.title("🧠 Codeator 3.0 - Interactive Python Code Analyzer")
root.geometry("950x950")
root.configure(bg="#f9f9f9")
title_label = tk.Label(root, text="🧠 Codeator 3.0", font=("Arial", 22, "bold"), bg="#f9f9f9", fg="#222")
title_label.pack(pady=10)
open_btn = tk.Button(root, text="📂 Open .py File", command=open_file, font=("Arial", 12))
open_btn.pack(pady=5)
code_label = tk.Label(root, text="Enter or paste Python code:", font=("Arial", 12), bg="#f9f9f9")
code_label.pack(pady=5)
code_input = tk.Text(root, height=15, width=110, font=("Courier", 10))
code_input.pack(pady=5)
btn_frame = tk.Frame(root, bg="#f9f9f9")
btn_frame.pack(pady=10)
analyze_btn = tk.Button(btn_frame, text="🔍 Analyze Code", command=analyze_button_click,
font=("Arial", 12, "bold"), bg="#0078D7", fg="white")
analyze_btn.grid(row=0, column=0, padx=10)
export_btn = tk.Button(btn_frame, text="🧹 Export Cleaned", command=export_cleaned,
font=("Arial", 12, "bold"), bg="#FF7043", fg="white")
export_btn.grid(row=0, column=1, padx=10)
# ✅ New checkbox for deleting comments
delete_comments_var = tk.BooleanVar()
delete_comments_check = tk.Checkbutton(root, text="🗑️ Delete comments on export", variable=delete_comments_var, bg="#f9f9f9", font=("Arial", 11))
delete_comments_check.pack(pady=5)
output_label = tk.Label(root, text="Analysis Result (click defs/classes to mark for deletion):",
font=("Arial", 12), bg="#f9f9f9")
output_label.pack(pady=5)
output_box = tk.Text(root, height=25, width=110, font=("Courier", 10), bg="#f0f0f0", state="disabled")
output_box.pack(pady=5)
root.mainloop()