-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmega_coder.py
More file actions
1514 lines (1253 loc) · 46.6 KB
/
Copy pathmega_coder.py
File metadata and controls
1514 lines (1253 loc) · 46.6 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import io
import os
import re
import sys
import time
import random
import subprocess
import warnings
from datetime import datetime
from typing import Optional
from dotenv import load_dotenv
from colorama import Fore, Style, init as colorama_init
from tqdm import tqdm
import google.generativeai as genai
try:
from gitingest import ingest
except ImportError:
ingest = None # type: ignore[assignment]
# screen capture dependencies
try:
import mss
import numpy as np
except ImportError:
mss = None
np = None
try:
from openai import OpenAI
except ImportError:
OpenAI = None
load_dotenv()
colorama_init(autoreset=True)
warnings.filterwarnings("ignore", category=DeprecationWarning)
APP_TITLE = "I’m Mega Coder. What would you like me to do today?"
MENU = (
"1. Develop a python program.\n"
"2. Fix/change something in a Github repository.\n"
"3. Look at my screen and give me realtime coding tips."
)
GENERATED_FILE = "generated-code-gemini.py"
GEMINI_MODEL = "gemini-2.5-flash-lite"
GEMINI_PRO_MODEL = "gemini-2.5-pro"
GPT5_MINI_MODEL = "gpt-5-mini"
RUN_LOG_FILE = "mega_coder.log"
# Max characters from the repository digest that we pass to the LLM.
# This is to avoid creating an extremely huge prompt.
MAX_REPO_DIGEST_CHARS = 200_000
SYSTEM_INSTRUCTION = (
"You are a Python code generator. Always output only complete Python source code, "
"with no markdown fences or explanations. Never use command-line arguments "
"(sys.argv, argparse, click, typer) and never call input() or wait for user input. "
"The program must run end-to-end with zero stops. "
"Use only Python's standard library; do not import any third-party packages. "
"Include meaningful assert statements that validate the core logic of the program, "
"not trivial truths like 'assert 1 == 1'. "
"If an assert fails, let the AssertionError propagate so the process exits with a non-zero status."
)
REPO_SYSTEM_INSTRUCTION = (
"You are an expert software engineer. You receive a text digest of a Git repository "
"and a natural language request from the user. Use only the information in the digest "
"to reason about the repository. When appropriate, point to concrete file paths and "
"symbols. If something is impossible to know from the digest, say that explicitly."
)
MAX_FIX_ATTEMPTS = 5
MAX_LINT_FIX_ATTEMPTS = 3
MUTATION_PROBABILITY = 0.3
SCREEN_GRAB_INTERVAL_SECONDS = 1.0
ANSI_ESCAPE_RE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")
CTRL_CHARS_RE = re.compile(r"[\x00-\x1F\x7F]")
FORBIDDEN_PATTERNS = [
r"\binput\s*\(",
r"\bsys\.argv\b",
r"\bargparse\b",
r"\bclick\b",
r"\btyper\b",
]
def ensure_no_cli_args() -> None:
"""
Enforce "no command-line arguments" requirement.
Exits with code 2 if arguments are provided.
"""
if len(sys.argv) > 1:
print(
Fore.RED
+ "This app does not accept command-line arguments. Please run without arguments."
+ Style.RESET_ALL
)
sys.exit(2)
def safe_input(prompt: str) -> Optional[str]:
"""
Read a single line safely.
Returns stripped string, or None if EOF or Ctrl+C is encountered.
"""
try:
s = input(prompt)
return s.strip()
except (EOFError, KeyboardInterrupt):
return None
def sanitize_user_description(text: str) -> str:
"""
Remove ANSI escape sequences and control characters from user input.
Also collapse excessive whitespace and strip leading and trailing spaces.
"""
if text is None:
return ""
cleaned = ANSI_ESCAPE_RE.sub("", text)
cleaned = CTRL_CHARS_RE.sub("", cleaned)
cleaned = re.sub(r"\s+", " ", cleaned).strip()
return cleaned
def is_meaningful_description(text: str, min_len: int = 10) -> bool:
"""
Heuristic: require some letters or digits and a minimum length after sanitization.
"""
if not text or len(text) < min_len:
return False
return bool(re.search(r"[A-Za-z0-9]", text))
def read_program_description() -> Optional[str]:
"""
Repeatedly ask the user for a meaningful program description.
Returns the cleaned description, or None if the user cancels and wants
to go back to the main menu.
Exits the app on EOF or Ctrl+C.
"""
while True:
desc = safe_input("\nYour description (or 'q' to go back to the main menu): ")
if desc is None:
print("No input (EOF or Ctrl+C). Exiting.")
sys.exit(0)
if desc.lower() in {"q", "quit", "exit"}:
print("Cancelled by user, returning to the main menu.")
return None
desc = sanitize_user_description(desc)
if not desc:
print(
"Description is empty. Please describe the Python program you want me to develop, "
"or type 'q' to cancel."
)
continue
if not is_meaningful_description(desc):
print(
"Description is not meaningful. Please give a clearer description of the Python program you want, "
"or type 'q' to cancel."
)
continue
return desc
def read_github_repo_url() -> Optional[str]:
"""
Ask the user for a public GitHub repository URL for gitingest.
Returns the URL or None if the user cancels and wants to go back to the menu.
"""
while True:
url = safe_input(
"\nGive me the full url of a public github repository (or 'q' to go back to the main menu): "
)
if url is None:
print("No input (EOF or Ctrl+C). Exiting.")
sys.exit(0)
url = url.strip()
if url.lower() in {"q", "quit", "exit"}:
print("Cancelled by user, returning to the main menu.")
return None
if not url:
print("Repository url is empty. Please paste a full GitHub url.")
continue
if "github.com" not in url:
print("This does not look like a GitHub url. Please paste a url that contains 'github.com'.")
continue
return url
def read_repo_request() -> Optional[str]:
"""
Ask the user what to fix, change, or explain in the selected repository.
Returns the cleaned text or None if the user cancels.
"""
while True:
text = safe_input(
"\nTell me what you want me to fix/change/explain in that repository (or 'q' to go back to the main menu): "
)
if text is None:
print("No input (EOF or Ctrl+C). Exiting.")
sys.exit(0)
if text.lower() in {"q", "quit", "exit"}:
print("Cancelled by user, returning to the main menu.")
return None
text = sanitize_user_description(text)
if not text:
print(
"Please describe what you want me to fix, change, or explain in that repository, "
"or type 'q' to cancel."
)
continue
return text
def read_menu_choice() -> Optional[int]:
"""
Prompt until a valid menu choice 1..3 is given, or return None to exit.
Accepts 'q' or 'quit' or 'exit' for a graceful exit.
"""
while True:
line = safe_input("\nEnter your choice (1, 2, or 3) or 'q' to quit: ")
if line is None:
return None
if line.lower() in {"q", "quit", "exit"}:
return None
if not line:
print("Please enter a choice: 1, 2, or 3 (or 'q' to quit).")
continue
if not line.isdigit():
print("Invalid input. Please enter a number: 1, 2, or 3.")
continue
choice = int(line)
if choice not in (1, 2, 3):
print("Out of range. Please choose 1, 2, or 3.")
continue
return choice
def build_gemini_prompt(user_description: str) -> str:
"""
Build a strict prompt for Gemini: no CLI args, no input, runnable end to end,
code only, with asserts.
"""
return f"""
You are an expert Python code generator. Create one complete, runnable Python 3 program.
Hard requirements:
- Do NOT use command-line arguments (assume none will ever be passed).
- Do NOT call input() or wait for user input. The program must run end-to-end with zero stops.
- Output ONLY raw Python source code. Do NOT include explanations or markdown fences.
- Include a short module-level docstring at the top describing the program.
- Use only Python's standard library; do not import any external or third-party packages.
- Include meaningful assert statements that validate the key logic of the program and avoid trivial checks
(do not write asserts like 'assert 1 == 1'). If something in the logic is wrong, these asserts must raise
an AssertionError.
- Follow PEP8 where reasonable.
User request:
\"\"\"{user_description}\"\"\"
Return ONLY the final Python source code. No backticks. No prose. No markdown.
"""
def _generate_with_gemini_model(
model_name: str,
prompt: str,
system_instruction: Optional[str] = None,
) -> str:
"""
Low level helper that calls a Gemini model and returns the raw text response.
Used by both the Flash Lite and Pro flows.
"""
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
print("Missing GOOGLE_API_KEY environment variable. Please export it and try again.")
sys.exit(1)
try:
genai.configure(api_key=api_key)
if system_instruction:
model = genai.GenerativeModel(
model_name,
system_instruction=system_instruction,
)
else:
model = genai.GenerativeModel(model_name)
response = model.generate_content(prompt)
except Exception as exc:
print(f"Gemini API error: {exc}")
sys.exit(1)
text = getattr(response, "text", None)
if not text:
try:
if response.candidates and response.candidates[0].content.parts:
parts = []
for part in response.candidates[0].content.parts:
t = getattr(part, "text", None)
if t:
parts.append(t)
text = "".join(parts)
except Exception:
text = None
if not text or not text.strip():
print("Gemini returned an empty response. Please try a different description or refine the prompt.")
sys.exit(1)
return text.strip()
def generate_with_gemini(prompt: str) -> str:
"""
Wrapper for Gemini 2.5 Flash Lite that you already use for option 1.
"""
return _generate_with_gemini_model(GEMINI_MODEL, prompt, SYSTEM_INSTRUCTION)
def generate_with_gemini_pro(prompt: str) -> str:
"""
Wrapper for Gemini 2.5 Pro used for repository analysis in option 2.
"""
return _generate_with_gemini_model(GEMINI_PRO_MODEL, prompt, REPO_SYSTEM_INSTRUCTION)
def extract_python_code(raw_text: str) -> str:
"""
Extract Python code from the model response.
If fenced blocks exist, prefer the first python-labeled block, else return trimmed text.
"""
fence = re.search(r"```python\s*(.*?)```", raw_text, flags=re.DOTALL | re.IGNORECASE)
if fence:
return fence.group(1).strip()
fence_any = re.search(r"```\s*(.*?)```", raw_text, flags=re.DOTALL)
if fence_any:
return fence_any.group(1).strip()
return raw_text.strip()
def build_repo_digest(repo_url: str) -> str:
"""
Use gitingest to turn a GitHub repository into a single text digest for LLM consumption.
"""
if ingest is None:
raise RuntimeError(
"gitingest is not installed. Please run 'pip install gitingest' in your virtualenv and try again."
)
try:
print(
Fore.CYAN
+ "\n[gitingest] Downloading and analyzing repository, this can take a while..."
+ Style.RESET_ALL
)
summary, tree, content = ingest(
repo_url,
include_submodules=False,
)
except Exception as exc:
raise RuntimeError(f"gitingest failed for url '{repo_url}': {exc}") from exc
parts: list[str] = []
if summary:
parts.append("### SUMMARY ###\n")
parts.append(str(summary).strip())
parts.append("\n\n")
if tree:
parts.append("### TREE ###\n")
parts.append(str(tree).strip())
parts.append("\n\n")
if content:
parts.append("### CONTENT ###\n")
parts.append(str(content).strip())
digest = "".join(parts).strip()
if not digest:
raise RuntimeError("gitingest returned an empty digest for this repository")
if len(digest) > MAX_REPO_DIGEST_CHARS:
print(
Fore.YELLOW
+ f"\n[gitingest] Digest is very large, keeping only the first {MAX_REPO_DIGEST_CHARS} characters for the LLM."
+ Style.RESET_ALL
)
digest = (
digest[:MAX_REPO_DIGEST_CHARS]
+ "\n\n[Digest truncated in mega_coder.py, repository is larger than this snippet.]"
)
return digest
def build_repo_prompt(repo_url: str, repo_digest: str, user_request: str) -> str:
"""
Build the prompt that will be sent to Gemini 2.5 Pro for repository analysis.
"""
return f"""
You are an expert software engineer and code reviewer.
You are given:
1. A GitHub repository url.
2. A text digest of the repository that was produced by gitingest.
3. A concrete request from the user about what to fix, change, or explain.
Important rules:
- Base your answer only on the information visible in the digest.
- If the digest does not contain enough information to answer something, say so clearly.
- When you refer to code, mention file names and function or class names when possible.
- If the user asked for a fix, describe the change in detail and provide example patches.
- If the user asked for an explanation, explain step by step and keep it practical.
GITHUB REPOSITORY URL:
{repo_url}
REPOSITORY DIGEST (gitingest):
<<<REPO_DIGEST_START>>>
{repo_digest}
<<<REPO_DIGEST_END>>>
USER REQUEST:
<<<USER_REQUEST_START>>>
{user_request}
<<<USER_REQUEST_END>>>
"""
def write_generated_file(code: str, path: str) -> None:
"""
Write generated code to a UTF-8 file. Ensure trailing newline for POSIX friendliness.
"""
with open(path, "w", encoding="utf-8") as f:
f.write(code if code.endswith("\n") else code + "\n")
def violates_io_constraints(code: str) -> bool:
"""
Return True if the code violates the no-input and no-CLI-args constraints.
"""
return any(re.search(pat, code) for pat in FORBIDDEN_PATTERNS)
def run_generated_code(path: str, timeout: int = 20) -> tuple[int, str, str]:
"""
Run the generated Python program as a separate process using the same interpreter.
Returns a tuple (exit_code, stdout, stderr).
"""
script_path = os.path.abspath(path)
print(Fore.BLUE + f"\n[runtime] Running generated program: {script_path}" + Style.RESET_ALL)
cmd = [sys.executable, script_path]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired as exc:
stdout = exc.stdout or ""
stderr = (exc.stderr or "") + f"\nTimeout after {timeout} seconds."
return 124, stdout, stderr
except FileNotFoundError:
return 127, "", f"File not found: {script_path}"
except PermissionError:
return 126, "", f"Permission denied: {script_path}"
except OSError as exc:
return 1, "", f"OS error while running '{script_path}': {exc}"
def maybe_mutate_code(code: str) -> tuple[str, bool]:
"""
With probability MUTATION_PROBABILITY, inject a tiny, deterministic syntax bug.
Returns (code_to_write, mutated_flag).
"""
if random.random() < MUTATION_PROBABILITY:
buggy = code.rstrip() + "\nprint('INTENTIONAL BUG'\n"
print(
Fore.MAGENTA
+ f"\n[mutator] Injected a tiny syntax bug into '{GENERATED_FILE}' on purpose, "
"just to keep the fixer busy."
+ Style.RESET_ALL
)
return buggy, True
print(
Fore.MAGENTA
+ f"\n[mutator] Wrote '{GENERATED_FILE}' without mutation this time."
+ Style.RESET_ALL
)
return code, False
def print_run_summary(exit_code: int, stdout: str, stderr: str) -> None:
"""
Pretty-print a summary of a single run of the generated program.
"""
print("\n=== Run summary ===")
print(f"Exit code: {exit_code}")
if stdout:
print("\nProgram output:")
print("---------------")
print(stdout.rstrip())
if stderr:
print("\nProgram errors:")
print("---------------")
print(stderr.rstrip())
if exit_code == 0:
print(
"\nResult: "
+ Fore.GREEN
+ "success"
+ Style.RESET_ALL
+ ", the program finished with exit code 0."
)
print(
"Assuming the asserts are meaningful, this suggests that the logic is consistent."
)
else:
print(
"\nResult: "
+ Fore.RED
+ "failure"
+ Style.RESET_ALL
+ ", the program did not finish cleanly. I will try to auto-fix it if possible."
)
def build_fix_prompt(
user_description: str,
buggy_code: str,
exit_code: int,
stdout: str,
stderr: str,
) -> str:
"""
Build a prompt that asks Gemini to fix the generated code, given
the error details from the last run.
"""
return f"""
You generated a Python 3 program for the following user request:
USER REQUEST:
\"\"\"{user_description}\"\"\"
When I ran the program, it failed with the following details:
EXIT CODE:
{exit_code}
STDOUT:
<<<STDOUT START>>>
{stdout}
<<<STDOUT END>>>
STDERR:
<<<STDERR START>>>
{stderr}
<<<STDERR END>>>
Here is the exact code that produced the error:
CURRENT CODE:
<<<CODE START>>>
{buggy_code}
<<<CODE END>>>
Please return a corrected FULL version of the same program that:
- Keeps the same functionality and overall structure.
- Preserves or improves the assert statements so they still validate the core logic.
- Does NOT use command-line arguments (no sys.argv, argparse, click, typer).
- Does NOT call input() or wait for user input.
- Uses only the Python standard library.
- Runs end-to-end without stopping for user input.
Return ONLY the complete corrected Python source code. No backticks. No prose. No markdown.
"""
def fix_code_with_gemini(
current_code: str,
exit_code: int,
stdout: str,
stderr: str,
user_description: str,
) -> str:
"""
Ask Gemini to fix the generated program based on the last run result.
Returns the fixed code, or the original code if the response is invalid.
"""
prompt = build_fix_prompt(user_description, current_code, exit_code, stdout, stderr)
print(Fore.CYAN + "\n[auto-fix] Asking Gemini to fix the program based on the error report..." + Style.RESET_ALL)
raw_text = generate_with_gemini(prompt)
fixed_code = extract_python_code(raw_text)
if not fixed_code or (
"def " not in fixed_code
and "class " not in fixed_code
and "import " not in fixed_code
):
print(
Fore.YELLOW
+ "[auto-fix] Gemini response does not look like valid Python code. "
"Keeping the previous version."
+ Style.RESET_ALL
)
return current_code
if violates_io_constraints(fixed_code):
print(
Fore.YELLOW
+ "[auto-fix] Gemini produced code that violates the IO constraints. "
"Keeping the previous version."
+ Style.RESET_ALL
)
return current_code
print(Fore.GREEN + "[auto-fix] Gemini returned a candidate fixed version of the program." + Style.RESET_ALL)
return fixed_code
def auto_fix_until_runs(initial_code: str, user_description: str) -> Optional[str]:
"""
Try to run and auto-fix the code up to MAX_FIX_ATTEMPTS times.
Returns the final working version of the code, or None if we give up.
"""
current_code = initial_code
print(
Fore.CYAN
+ "\n=== Step 1/3: generate and auto-fix the program ==="
+ Style.RESET_ALL
)
for attempt in range(1, MAX_FIX_ATTEMPTS + 1):
print(
Fore.CYAN
+ f"\n---------- Auto fix attempt {attempt}/{MAX_FIX_ATTEMPTS} ----------"
+ Style.RESET_ALL
)
code_to_write, mutated = maybe_mutate_code(current_code)
try:
write_generated_file(code_to_write, GENERATED_FILE)
except OSError as exc:
print(Fore.RED + f"Failed to write '{GENERATED_FILE}': {exc}" + Style.RESET_ALL)
return None
if mutated:
print(Fore.BLUE + "[runner] This run uses a deliberately mutated version of the program." + Style.RESET_ALL)
else:
print(Fore.BLUE + "[runner] This run uses the clean version of the program." + Style.RESET_ALL)
exit_code, stdout, stderr = run_generated_code(GENERATED_FILE)
print_run_summary(exit_code, stdout, stderr)
if exit_code == 0:
return code_to_write
if attempt == MAX_FIX_ATTEMPTS:
return None
current_code = fix_code_with_gemini(
code_to_write, exit_code, stdout, stderr, user_description
)
def run_pylint(path: str, timeout: int = 30) -> tuple[int, str]:
"""
Run pylint on the given file.
Returns (exit_code, full_output). Exit code 0 means no issues.
We disable C and R so we focus on warnings and errors, not style hints.
"""
cmd = ["pylint", "--disable=C,R", path]
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
output = (exc.stdout or "") + "\n[lint] pylint timed out."
return 124, output
except FileNotFoundError:
return 127, "[lint] pylint command not found. Is it installed?"
except OSError as exc:
return 1, f"[lint] OS error while running pylint: {exc}"
output = (result.stdout or "") + (result.stderr or "")
return result.returncode, output
def build_lint_fix_prompt(
user_description: str,
current_code: str,
pylint_output: str,
) -> str:
"""
Build a prompt that asks Gemini to fix lint warnings and errors from pylint.
"""
return f"""
You previously wrote this Python 3 program for the following user request:
USER REQUEST:
\"\"\"{user_description}\"\"\"
CURRENT CODE:
<<<CODE START>>>
{current_code}
<<<CODE END>>>
I ran pylint (with C and R messages disabled) on this file and got:
PYLINT OUTPUT:
<<<PYLINT START>>>
{pylint_output}
<<<PYLINT END>>>
Please return a new version of the program that:
- Fixes the pylint warnings and errors shown above.
- Keeps the same functionality and overall behavior.
- Preserves the existing assert statements or replaces them with equivalent ones
that validate the same conditions.
- Does NOT use command-line arguments (no sys.argv, argparse, click, typer).
- Does NOT call input() or wait for user input.
- Uses only the Python standard library.
- Runs end-to-end without stopping for user input.
Return ONLY the full corrected Python source code. No backticks. No prose. No markdown.
"""
def fix_lint_with_gemini(
current_code: str,
pylint_output: str,
user_description: str,
) -> str:
"""
Ask Gemini to fix pylint warnings and errors, given the current code and
the pylint output. Returns the fixed code or the original code if invalid.
"""
prompt = build_lint_fix_prompt(user_description, current_code, pylint_output)
print(Fore.CYAN + "\n[lint] Asking Gemini to fix pylint issues..." + Style.RESET_ALL)
raw_text = generate_with_gemini(prompt)
fixed_code = extract_python_code(raw_text)
if not fixed_code or (
"def " not in fixed_code
and "class " not in fixed_code
and "import " not in fixed_code
):
print(
Fore.YELLOW
+ "[lint] Gemini response does not look like valid Python. Keeping the previous version."
+ Style.RESET_ALL
)
return current_code
if violates_io_constraints(fixed_code):
print(
Fore.YELLOW
+ "[lint] Gemini produced code that violates the IO constraints. "
"Keeping the previous version."
+ Style.RESET_ALL
)
return current_code
print(Fore.GREEN + "[lint] Gemini returned a candidate lint-fixed version." + Style.RESET_ALL)
return fixed_code
def lint_and_auto_fix(initial_code: str, user_description: str) -> str:
"""
Run pylint up to MAX_LINT_FIX_ATTEMPTS times and try to auto fix issues with Gemini.
Returns the latest version of the code, possibly updated.
"""
current_code = initial_code
try:
write_generated_file(current_code, GENERATED_FILE)
except OSError as exc:
print(
Fore.RED
+ f"[lint] Failed to write initial code for linting: {exc}"
+ Style.RESET_ALL
)
return current_code
print(
Fore.CYAN
+ "\n[lint] Starting pylint checks and auto-fix loop..."
+ Style.RESET_ALL
)
with tqdm(
total=MAX_LINT_FIX_ATTEMPTS,
desc="Lint fixing",
unit="round",
leave=False,
) as pbar:
for round_index in range(1, MAX_LINT_FIX_ATTEMPTS + 1):
print(
Fore.CYAN
+ f"\n[lint] Lint round {round_index}/{MAX_LINT_FIX_ATTEMPTS} on '{GENERATED_FILE}'..."
+ Style.RESET_ALL
)
exit_code, lint_output = run_pylint(GENERATED_FILE)
pbar.update(1)
if exit_code == 0:
print(
Fore.GREEN
+ "[lint] pylint found no warnings/errors."
+ Style.RESET_ALL
)
print("Amazing. No lint errors/warnings")
if round_index == MAX_LINT_FIX_ATTEMPTS:
return current_code
continue
print(
Fore.YELLOW
+ "[lint] pylint reported warnings/errors:"
+ Style.RESET_ALL
)
print(lint_output.strip() or "[lint] (no detailed output)")
if round_index == MAX_LINT_FIX_ATTEMPTS:
print("There are still lint errors/warnings")
return current_code
try:
with open(GENERATED_FILE, "r", encoding="utf-8") as f:
current_code = f.read()
except OSError as exc:
print(
Fore.RED
+ f"[lint] Failed to read '{GENERATED_FILE}' before lint-fix: {exc}"
+ Style.RESET_ALL
)
print("There are still lint errors/warnings")
return current_code
fixed_code = fix_lint_with_gemini(current_code, lint_output, user_description)
current_code = fixed_code
try:
write_generated_file(current_code, GENERATED_FILE)
except OSError as exc:
print(
Fore.RED
+ f"[lint] Failed to write lint-fixed version: {exc}"
+ Style.RESET_ALL
)
print("There are still lint errors/warnings")
return current_code
return current_code
def time_program(path: str, timeout: int = 20) -> tuple[int, float, str, str]:
"""
Run the generated python file and measure how long it takes.
Returns (exit_code, elapsed_ms, stdout, stderr).
"""
start = time.perf_counter()
exit_code, stdout, stderr = run_generated_code(path, timeout=timeout)
elapsed_ms = (time.perf_counter() - start) * 1000.0
return exit_code, elapsed_ms, stdout, stderr
def build_optimization_prompt(user_description: str, current_code: str) -> str:
"""
Build a prompt that asks Gemini to keep the same asserts but create
a more efficient version of the program.
"""
return f"""
You previously wrote a Python program for this description:
USER REQUEST:
\"\"\"{user_description}\"\"\"
The program below works and already contains asserts that verify its logic.
Your task:
- Rewrite this program so that it is more efficient and runs faster.
- Keep all existing asserts and the same logical behavior.
Constraints:
- Do NOT use command-line arguments.
- Do NOT call input() or wait for any user input.
- The program must run end-to-end without stopping.
- Use only Python's standard library.
- Respond with Python code only, no explanations or comments.
- Do NOT use Markdown fences.
Here is the current program:
<<<CODE START>>>
{current_code}
<<<CODE END>>>
"""
def optimize_program_runtime(final_working_code: str, user_description: str) -> None:
"""
Measure the runtime of the current program, then ask Gemini to generate
a more efficient version with the same asserts. Compare runtimes and
print the required message if performance improved.
"""
print(
Fore.CYAN
+ "\n=== Step 3/3: measure and optimize runtime ==="
+ Style.RESET_ALL
)
print("\nMeasuring how long the current program takes to run...")
before_exit, before_ms, _, _ = time_program(GENERATED_FILE)
if before_exit != 0:
print(
Fore.YELLOW
+ f"\nWarning: the working program failed during the timing step (exit code {before_exit}). "
"Skipping optimization."
+ Style.RESET_ALL
)
return
before_ms_int = int(before_ms)
print(Fore.BLUE + f"Current program execution time: {before_ms_int} milliseconds." + Style.RESET_ALL)
print(Fore.CYAN + "\nAsking Gemini to generate a more efficient version of the program..." + Style.RESET_ALL)
optimization_prompt = build_optimization_prompt(user_description, final_working_code)
optimized_raw = generate_with_gemini(optimization_prompt)
optimized_code = extract_python_code(optimized_raw)
if not optimized_code or (
"def " not in optimized_code
and "class " not in optimized_code
and "import " not in optimized_code
):
print(
Fore.YELLOW
+ "\nThe optimized response does not look like valid Python code. Keeping the original program."
+ Style.RESET_ALL
)
return
if violates_io_constraints(optimized_code):
print(
Fore.YELLOW
+ "\nThe optimized code violates the IO constraints (uses input() or CLI args). "
"Keeping the original program."
+ Style.RESET_ALL