repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/generate_readme.py | generate_readme.py | # coding=utf-8
import re
from rich.console import Console
from rich.theme import Theme
from core import HackingTool
from core import HackingToolsCollection
from hackingtool import all_tools
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
def sanitize_anchor(s):
return re.sub(r"\W", "-", s.lower())
def get_toc(tools, indentation = ""):
md = ""
for tool in tools:
if isinstance(tool, HackingToolsCollection):
md += (indentation + "- [{}](#{})\n".format(
tool.TITLE, sanitize_anchor(tool.TITLE)))
md += get_toc(tool.TOOLS, indentation = indentation + ' ')
return md
def get_tools_toc(tools, indentation = "##"):
md = ""
for tool in tools:
if isinstance(tool, HackingToolsCollection):
md += (indentation + "# {}\n".format(tool.TITLE))
md += get_tools_toc(tool.TOOLS, indentation = indentation + '#')
elif isinstance(tool, HackingTool):
if tool.PROJECT_URL:
md += ("- [{}]({})\n".format(tool.TITLE, tool.PROJECT_URL))
else:
md += ("- {}\n".format(tool.TITLE))
return md
def generate_readme():
toc = get_toc(all_tools[:-1])
tools_desc = get_tools_toc(all_tools[:-1])
with open("README_template.md") as fh:
readme_template = fh.read()
readme_template = readme_template.replace("{{toc}}", toc)
readme_template = readme_template.replace("{{tools}}", tools_desc)
with open("README.md", "w") as fh:
fh.write(readme_template)
if __name__ == '__main__':
generate_readme() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/payload_creator.py | tools/payload_creator.py | # coding=utf-8
import os
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class TheFatRat(HackingTool):
TITLE = "The FatRat"
DESCRIPTION = "TheFatRat Provides An Easy way to create Backdoors and Payloads " \
"which can bypass most anti-virus"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Screetsec/TheFatRat.git",
"cd TheFatRat && sudo chmod +x setup.sh"
]
RUN_COMMANDS = ["cd TheFatRat && sudo bash setup.sh"]
PROJECT_URL = "https://github.com/Screetsec/TheFatRat"
def __init__(self):
super(TheFatRat, self).__init__([
('Update', self.update),
('Troubleshoot', self.troubleshoot)
])
def update(self):
os.system("cd TheFatRat && bash update && chmod +x setup.sh && bash setup.sh")
def troubleshoot(self):
os.system("cd TheFatRat && sudo chmod +x chk_tools && ./chk_tools")
class Brutal(HackingTool):
TITLE = "Brutal"
DESCRIPTION = "Brutal is a toolkit to quickly create various payloads, powershell attacks, " \
"virus attacks and launch listener for a Human Interface Device"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Screetsec/Brutal.git",
"cd Brutal && sudo chmod +x Brutal.sh"
]
RUN_COMMANDS = ["cd Brutal && sudo bash Brutal.sh"]
PROJECT_URL = "https://github.com/Screetsec/Brutal"
def show_info(self):
super(Brutal, self).show_info()
console.print("""
[!] Requirement
>> Arduino Software (I used v1.6.7)
>> TeensyDuino
>> Linux udev rules
>> Copy and paste the PaensyLib folder inside your Arduino libraries
[!] Visit for Installation for Arduino:
>> https://github.com/Screetsec/Brutal/wiki/Install-Requirements
""")
class Stitch(HackingTool):
TITLE = "Stitch"
DESCRIPTION = "Stitch is Cross Platform Python Remote Administrator Tool\n" \
"[!] Refer Below Link For Wins & Mac OS"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/nathanlopez/Stitch.git",
"cd Stitch && sudo pip install -r lnx_requirements.txt"
]
RUN_COMMANDS = ["cd Stitch && sudo python main.py"]
PROJECT_URL = "https://nathanlopez.github.io/Stitch"
class MSFVenom(HackingTool):
TITLE = "MSFvenom Payload Creator"
DESCRIPTION = "MSFvenom Payload Creator (MSFPC) is a wrapper to generate multiple types of payloads, " \
"based on user choice. Simplifies payload creation."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/g0tmi1k/msfpc.git",
"cd msfpc;sudo chmod +x msfpc.sh"
]
RUN_COMMANDS = ["cd msfpc;sudo bash msfpc.sh -h -v"]
PROJECT_URL = "https://github.com/g0tmi1k/msfpc"
class Venom(HackingTool):
TITLE = "Venom Shellcode Generator"
DESCRIPTION = "Venom 1.0.11 (malicious_server) exploits apache2 webserver to deliver LAN payloads via fake webpages."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/r00t-3xp10it/venom.git",
"sudo chmod -R 775 venom*/ && cd venom*/ && cd aux && sudo bash setup.sh",
"sudo ./venom.sh -u"
]
RUN_COMMANDS = ["cd venom && sudo ./venom.sh"]
PROJECT_URL = "https://github.com/r00t-3xp10it/venom"
class Spycam(HackingTool):
TITLE = "Spycam"
DESCRIPTION = "Generates a Win32 payload that captures webcam images every 1 minute and sends them to the attacker."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/indexnotfound404/spycam.git",
"cd spycam && bash install.sh && chmod +x spycam"
]
RUN_COMMANDS = ["cd spycam && ./spycam"]
PROJECT_URL = "https://github.com/indexnotfound404/spycam"
class MobDroid(HackingTool):
TITLE = "Mob-Droid"
DESCRIPTION = "Generates metasploit payloads easily without typing long commands."
INSTALL_COMMANDS = [
"git clone https://github.com/kinghacker0/mob-droid.git"
]
RUN_COMMANDS = ["cd mob-droid;sudo python mob-droid.py"]
PROJECT_URL = "https://github.com/kinghacker0/Mob-Droid"
class Enigma(HackingTool):
TITLE = "Enigma"
DESCRIPTION = "Enigma is a Multiplatform payload dropper."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/UndeadSec/Enigma.git"
]
RUN_COMMANDS = ["cd Enigma;sudo python enigma.py"]
PROJECT_URL = "https://github.com/UndeadSec/Enigma"
class PayloadCreatorTools(HackingToolsCollection):
TITLE = "Payload creation tools"
TOOLS = [
TheFatRat(),
Brutal(),
Stitch(),
MSFVenom(),
Venom(),
Spycam(),
MobDroid(),
Enigma()
]
def pretty_print(self):
table = Table(title="Payload Creation Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
console.print(Panel(table, title="[purple]Available Tools[/purple]", border_style="purple"))
def show_options(self):
console.print("\n")
console.print(Panel.fit(
"[bold purple]Payload Creator Collection[/bold purple]\n"
"Select a tool to run it or exit.",
border_style="purple"
))
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
desc = getattr(tool, "DESCRIPTION", "") or "—"
table.add_row(str(i + 1), tool.TITLE, desc.replace("\n", " "))
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_actions"):
selected.show_actions()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options()
if __name__ == "__main__":
tools = PayloadCreatorTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/information_gathering_tools.py | tools/information_gathering_tools.py | # coding=utf-8
import os
import socket
import subprocess
import webbrowser
import sys
from core import HackingTool
from core import HackingToolsCollection
from core import clear_screen
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.prompt import Prompt
from rich.table import Table
console = Console()
PURPLE_STYLE = "bold magenta"
class NMAP(HackingTool):
TITLE = "Network Map (nmap)"
DESCRIPTION = "Free and open source utility for network discovery and security auditing"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/nmap/nmap.git",
"sudo chmod -R 755 nmap && cd nmap && sudo ./configure && make && sudo make install"
]
PROJECT_URL = "https://github.com/nmap/nmap"
def __init__(self):
super(NMAP, self).__init__(runnable=False)
class Dracnmap(HackingTool):
TITLE = "Dracnmap"
DESCRIPTION = "Dracnmap is an open source program which is using to \n" \
"exploit the network and gathering information with nmap help."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Screetsec/Dracnmap.git",
"cd Dracnmap && chmod +x dracnmap-v2.2-dracOs.sh dracnmap-v2.2.sh"
]
RUN_COMMANDS = ["cd Dracnmap;sudo ./dracnmap-v2.2.sh"]
PROJECT_URL = "https://github.com/Screetsec/Dracnmap"
class PortScan(HackingTool):
TITLE = "Port scanning"
def __init__(self):
super(PortScan, self).__init__(installable=False)
def run(self):
clear_screen()
console.print(Panel(Text(self.TITLE, justify="center"), style=PURPLE_STYLE))
target = Prompt.ask("[bold]Select a Target IP[/]", default="", show_default=False)
subprocess.run(["sudo", "nmap", "-O", "-Pn", target])
class Host2IP(HackingTool):
TITLE = "Host to IP "
def __init__(self):
super(Host2IP, self).__init__(installable=False)
def run(self):
clear_screen()
console.print(Panel(Text(self.TITLE, justify="center"), style=PURPLE_STYLE))
host = Prompt.ask("Enter host name (e.g. www.google.com):- ")
ips = socket.gethostbyname(host)
console.print(f"[{PURPLE_STYLE}]{host} -> {ips}[/]")
class XeroSploit(HackingTool):
TITLE = "Xerosploit"
DESCRIPTION = "Xerosploit is a penetration testing toolkit whose goal is to perform\n" \
"man-in-the-middle attacks for testing purposes"
INSTALL_COMMANDS = [
"git clone https://github.com/LionSec/xerosploit.git",
"cd xerosploit && sudo python install.py"
]
RUN_COMMANDS = ["sudo xerosploit"]
PROJECT_URL = "https://github.com/LionSec/xerosploit"
class RedHawk(HackingTool):
TITLE = "RED HAWK (All In One Scanning)"
DESCRIPTION = "All in one tool for Information Gathering and Vulnerability Scanning."
INSTALL_COMMANDS = [
"git clone https://github.com/Tuhinshubhra/RED_HAWK.git"]
RUN_COMMANDS = ["cd RED_HAWK;php rhawk.php"]
PROJECT_URL = "https://github.com/Tuhinshubhra/RED_HAWK"
class ReconSpider(HackingTool):
TITLE = "ReconSpider(For All Scanning)"
DESCRIPTION = "ReconSpider is most Advanced Open Source Intelligence (OSINT)" \
" Framework for scanning IP Address, Emails, \n" \
"Websites, Organizations and find out information from" \
" different sources.\n"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/bhavsec/reconspider.git",
"sudo apt install python3 python3-pip && cd reconspider && sudo python3 setup.py install"
]
RUN_COMMANDS = ["cd reconspider;python3 reconspider.py"]
PROJECT_URL = "https://github.com/bhavsec/reconspider"
class IsItDown(HackingTool):
TITLE = "IsItDown (Check Website Down/Up)"
DESCRIPTION = "Check Website Is Online or Not"
def __init__(self):
super(IsItDown, self).__init__(
[('Open', self.open)], installable=False, runnable=False)
def open(self):
console.print(Panel("Opening isitdownrightnow.com", style=PURPLE_STYLE))
webbrowser.open_new_tab("https://www.isitdownrightnow.com/")
class Infoga(HackingTool):
TITLE = "Infoga - Email OSINT"
DESCRIPTION = "Infoga is a tool gathering email accounts information\n" \
"(ip, hostname, country,...) from different public source"
INSTALL_COMMANDS = [
"git clone https://github.com/m4ll0k/Infoga.git",
"cd Infoga;sudo python3 setup.py install"
]
RUN_COMMANDS = ["cd Infoga;python3 infoga.py"]
PROJECT_URL = "https://github.com/m4ll0k/Infoga"
class ReconDog(HackingTool):
TITLE = "ReconDog"
DESCRIPTION = "ReconDog Information Gathering Suite"
INSTALL_COMMANDS = ["git clone https://github.com/s0md3v/ReconDog.git"]
RUN_COMMANDS = ["cd ReconDog;sudo python dog"]
PROJECT_URL = "https://github.com/s0md3v/ReconDog"
class Striker(HackingTool):
TITLE = "Striker"
DESCRIPTION = "Recon & Vulnerability Scanning Suite"
INSTALL_COMMANDS = [
"git clone https://github.com/s0md3v/Striker.git",
"cd Striker && pip3 install -r requirements.txt"
]
PROJECT_URL = "https://github.com/s0md3v/Striker"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=PURPLE_STYLE))
site = Prompt.ask("Enter Site Name (example.com) >> ")
os.chdir("Striker")
subprocess.run(["sudo", "python3", "striker.py", site])
class SecretFinder(HackingTool):
TITLE = "SecretFinder (like API & etc)"
DESCRIPTION = "SecretFinder - A python script for find sensitive data \n" \
"like apikeys, accesstoken, authorizations, jwt,..etc \n " \
"and search anything on javascript files.\n\n " \
"Usage: python SecretFinder.py -h"
INSTALL_COMMANDS = [
"git clone https://github.com/m4ll0k/SecretFinder.git secretfinder",
"cd secretfinder; sudo pip3 install -r requirements.txt"
]
PROJECT_URL = "https://github.com/m4ll0k/SecretFinder"
def __init__(self):
super(SecretFinder, self).__init__(runnable=False)
class Shodan(HackingTool):
TITLE = "Find Info Using Shodan"
DESCRIPTION = "Get ports, vulnerabilities, information, banners,..etc \n " \
"for any IP with Shodan (no apikey! no rate limit!)\n" \
"[X] Don't use this tool because your ip will be blocked by Shodan!"
INSTALL_COMMANDS = ["git clone https://github.com/m4ll0k/Shodanfy.py.git"]
PROJECT_URL = "https://github.com/m4ll0k/Shodanfy.py"
def __init__(self):
super(Shodan, self).__init__(runnable=False)
class PortScannerRanger(HackingTool):
TITLE = "Port Scanner - rang3r"
DESCRIPTION = "rang3r is a python script which scans in multi thread\n " \
"all alive hosts within your range that you specify."
INSTALL_COMMANDS = [
"git clone https://github.com/floriankunushevci/rang3r.git;"
"sudo pip install termcolor"]
PROJECT_URL = "https://github.com/floriankunushevci/rang3r"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=PURPLE_STYLE))
ip = Prompt.ask("Enter Ip >> ")
os.chdir("rang3r")
subprocess.run(["sudo", "python", "rang3r.py", "--ip", ip])
class Breacher(HackingTool):
TITLE = "Breacher"
DESCRIPTION = "An advanced multithreaded admin panel finder written in python."
INSTALL_COMMANDS = ["git clone https://github.com/s0md3v/Breacher.git"]
PROJECT_URL = "https://github.com/s0md3v/Breacher"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=PURPLE_STYLE))
domain = Prompt.ask("Enter domain (example.com) >> ")
os.chdir("Breacher")
subprocess.run(["python3", "breacher.py", "-u", domain])
class InformationGatheringTools(HackingToolsCollection):
TITLE = "Information gathering tools"
TOOLS = [
NMAP(),
Dracnmap(),
PortScan(),
Host2IP(),
XeroSploit(),
RedHawk(),
ReconSpider(),
IsItDown(),
Infoga(),
ReconDog(),
Striker(),
SecretFinder(),
Shodan(),
PortScannerRanger(),
Breacher()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Information Gathering Tools", show_lines=True, expand=True)
table.add_column("Title", style=PURPLE_STYLE, no_wrap=True)
table.add_column("Description", style=PURPLE_STYLE)
table.add_column("Project URL", style=PURPLE_STYLE, no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc).replace("\n", " "), str(url))
console.print(Panel(table, title=f"[magenta]Available Tools[/magenta]", border_style=PURPLE_STYLE))
def show_options(self, parent=None):
console.print("\n")
console.print(Panel.fit(
"[bold magenta]Information Gathering Collection[/bold magenta]\n"
"Select a tool to view/run it or return to the previous menu.",
border_style=PURPLE_STYLE
))
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# delegate to collection-style tools if available
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# if tool exposes actions/menu, try to call it
elif hasattr(selected, "show_actions"):
selected.show_actions(parent=self)
# otherwise try to call run if present
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = InformationGatheringTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/tool_manager.py | tools/tool_manager.py | # coding=utf-8
import os
import sys
from time import sleep
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class UpdateTool(HackingTool):
TITLE = "Update Tool or System"
DESCRIPTION = "Update Tool or System"
def __init__(self):
super(UpdateTool, self).__init__([
("Update System", self.update_sys),
("Update Hackingtool", self.update_ht)
], installable=False, runnable=False)
def update_sys(self):
os.system("sudo apt update && sudo apt full-upgrade -y")
os.system("sudo apt-get install tor openssl curl && sudo apt-get update tor openssl curl")
os.system("sudo apt-get install python3-pip")
def update_ht(self):
os.system("sudo chmod +x /etc/;"
"sudo chmod +x /usr/share/doc;"
"sudo rm -rf /usr/share/doc/hackingtool/;"
"cd /etc/;"
"sudo rm -rf /etc/hackingtool/;"
"mkdir hackingtool;"
"cd hackingtool;"
"git clone https://github.com/Z4nzu/hackingtool.git;"
"cd hackingtool;"
"sudo chmod +x install.sh;"
"./install.sh")
class UninstallTool(HackingTool):
TITLE = "Uninstall HackingTool"
DESCRIPTION = "Uninstall HackingTool"
def __init__(self):
super(UninstallTool, self).__init__([
('Uninstall', self.uninstall)
], installable=False, runnable=False)
def uninstall(self):
console.print("hackingtool started to uninstall..\n")
sleep(1)
os.system("sudo chmod +x /etc/;"
"sudo chmod +x /usr/share/doc;"
"sudo rm -rf /usr/share/doc/hackingtool/;"
"cd /etc/;"
"sudo rm -rf /etc/hackingtool/;")
console.print("\n[bold green]Hackingtool Successfully Uninstalled... Goodbye.[/bold green]")
sys.exit()
class ToolManager(HackingToolsCollection):
TITLE = "Update or Uninstall | Hackingtool"
TOOLS = [
UpdateTool(),
UninstallTool()
]
def pretty_print(self):
table = Table(title="Tool Manager — Update / Uninstall", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "))
panel = Panel(table, title="[purple]Available Manager Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Tool Manager[/bold magenta]\nSelect an action to run.", border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Options[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc)
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = int(Prompt.ask("[bold cyan]Select an option[/bold cyan]", default="99"))
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
manager = ToolManager()
manager.pretty_print()
manager.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/reverse_engineering.py | tools/reverse_engineering.py | # coding=utf-8
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class AndroGuard(HackingTool):
TITLE = "Androguard"
DESCRIPTION = "Androguard is a Reverse engineering, Malware and goodware " \
"analysis of Android applications and more"
INSTALL_COMMANDS = ["sudo pip3 install -U androguard"]
PROJECT_URL = "https://github.com/androguard/androguard "
def __init__(self):
super(AndroGuard, self).__init__(runnable=False)
class Apk2Gold(HackingTool):
TITLE = "Apk2Gold"
DESCRIPTION = "Apk2Gold is a CLI tool for decompiling Android apps to Java"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/lxdvs/apk2gold.git",
"cd apk2gold;sudo bash make.sh"
]
PROJECT_URL = "https://github.com/lxdvs/apk2gold "
def run(self):
uinput = input("Enter (.apk) File >> ")
subprocess.run(["sudo", "apk2gold", uinput])
class Jadx(HackingTool):
TITLE = "JadX"
DESCRIPTION = "Jadx is Dex to Java decompiler.\n" \
"[*] decompile Dalvik bytecode to java classes from APK, dex," \
" aar and zip files\n" \
"[*] decode AndroidManifest.xml and other resources from " \
"resources.arsc"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/skylot/jadx.git",
"cd jadx;./gradlew dist"
]
PROJECT_URL = "https://github.com/skylot/jadx"
def __init__(self):
super(Jadx, self).__init__(runnable=False)
class ReverseEngineeringTools(HackingToolsCollection):
TITLE = "Reverse engineering tools"
TOOLS = [
AndroGuard(),
Apk2Gold(),
Jadx()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Reverse Engineering Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="").strip().replace("\n", " ")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc or "—"), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Reverse Engineering Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "before_run"):
selected.before_run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = ReverseEngineeringTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/wordlist_generator.py | tools/wordlist_generator.py | # coding=utf-8
import os
import subprocess
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
from core import HackingTool
from core import HackingToolsCollection
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class Cupp(HackingTool):
TITLE = "Cupp"
DESCRIPTION = "WlCreator is a C program that can create all possibilities of passwords,\n " \
"and you can choose Length, Lowercase, Capital, Numbers and Special Chars"
INSTALL_COMMANDS = ["git clone https://github.com/Mebus/cupp.git"]
RUN_COMMANDS = ["cd cupp && python3 cupp.py -i"]
PROJECT_URL = "https://github.com/Mebus/cupp"
def show_info(self):
panel = Panel(
f"[bold purple]{self.TITLE}[/bold purple]\n\n"
f"[cyan]{self.DESCRIPTION}[/cyan]\n\n"
f"[green]Repository:[/green] [underline blue]{self.PROJECT_URL}[/underline blue]",
border_style="purple",
box=box.ROUNDED,
)
console.print(panel)
class WlCreator(HackingTool):
TITLE = "WordlistCreator"
DESCRIPTION = "WlCreator is a C program that can create all possibilities" \
" of passwords,\n and you can choose Length, Lowercase, " \
"Capital, Numbers and Special Chars"
INSTALL_COMMANDS = ["sudo git clone https://github.com/Z4nzu/wlcreator.git"]
RUN_COMMANDS = [
"cd wlcreator && sudo gcc -o wlcreator wlcreator.c && ./wlcreator 5"]
PROJECT_URL = "https://github.com/Z4nzu/wlcreator"
def show_info(self):
panel = Panel(
f"[bold purple]{self.TITLE}[/bold purple]\n\n"
f"[cyan]{self.DESCRIPTION}[/cyan]\n\n"
f"[green]Repository:[/green] [underline blue]{self.PROJECT_URL}[/underline blue]",
border_style="purple",
box=box.ROUNDED,
)
console.print(panel)
class GoblinWordGenerator(HackingTool):
TITLE = "Goblin WordGenerator"
DESCRIPTION = "Goblin WordGenerator"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/UndeadSec/GoblinWordGenerator.git"]
RUN_COMMANDS = ["cd GoblinWordGenerator && python3 goblin.py"]
PROJECT_URL = "https://github.com/UndeadSec/GoblinWordGenerator.git"
def show_info(self):
panel = Panel(
f"[bold purple]{self.TITLE}[/bold purple]\n\n"
f"[cyan]{self.DESCRIPTION}[/cyan]\n\n"
f"[green]Repository:[/green] [underline blue]{self.PROJECT_URL}[/underline blue]",
border_style="purple",
box=box.ROUNDED,
)
console.print(panel)
class showme(HackingTool):
TITLE = "Password list (1.4 Billion Clear Text Password)"
DESCRIPTION = "This tool allows you to perform OSINT and reconnaissance on " \
"an organisation or an individual. It allows one to search " \
"1.4 Billion clear text credentials which was dumped as " \
"part of BreachCompilation leak. This database makes " \
"finding passwords faster and easier than ever before."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Viralmaniar/SMWYG-Show-Me-What-You-Got.git",
"cd SMWYG-Show-Me-What-You-Got && pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd SMWYG-Show-Me-What-You-Got && python SMWYG.py"]
PROJECT_URL = "https://github.com/Viralmaniar/SMWYG-Show-Me-What-You-Got"
def show_info(self):
panel = Panel(
f"[bold purple]{self.TITLE}[/bold purple]\n\n"
f"[cyan]{self.DESCRIPTION}[/cyan]\n\n"
f"[green]Repository:[/green] [underline blue]{self.PROJECT_URL}[/underline blue]",
border_style="purple",
box=box.ROUNDED,
)
console.print(panel)
class WordlistGeneratorTools(HackingToolsCollection):
TITLE = "Wordlist Generator"
TOOLS = [
Cupp(),
WlCreator(),
GoblinWordGenerator(),
showme()
]
def show_info(self):
header = Panel(f"[bold white on purple] {self.TITLE} [/bold white on purple]",
border_style="purple", box=box.DOUBLE)
console.print(header)
table = Table(box=box.SIMPLE, show_header=True, header_style="bold purple")
table.add_column("#", justify="center", style="cyan", width=4)
table.add_column("Tool", style="bold")
table.add_column("Description", style="dim", overflow="fold")
for idx, t in enumerate(self.TOOLS, start=1):
desc = getattr(t, "DESCRIPTION", "") or ""
table.add_row(str(idx), t.TITLE, desc)
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Wordlist Generator Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_info"):
selected.show_info()
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = WordlistGeneratorTools()
tools.show_info()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/xss_attack.py | tools/xss_attack.py | # coding=utf-8
import os
import subprocess
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from rich.table import Table
from core import HackingTool
from core import HackingToolsCollection
console = Console()
class Dalfox(HackingTool):
TITLE = "DalFox (Finder of XSS)"
DESCRIPTION = "XSS Scanning and Parameter Analysis tool."
INSTALL_COMMANDS = [
"sudo apt-get install golang",
"sudo git clone https://github.com/hahwul/dalfox",
"cd dalfox;go install"
]
RUN_COMMANDS = [
"~/go/bin/dalfox",
'echo "You Need To Run manually by using [!]~/go/bin/dalfox [options]"'
]
PROJECT_URL = "https://github.com/hahwul/dalfox"
class XSSPayloadGenerator(HackingTool):
TITLE = "XSS Payload Generator"
DESCRIPTION = "XSS PAYLOAD GENERATOR - XSS SCANNER - XSS DORK FINDER"
INSTALL_COMMANDS = [
"git clone https://github.com/capture0x/XSS-LOADER.git",
"cd XSS-LOADER;sudo pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd XSS-LOADER;sudo python3 payloader.py"]
PROJECT_URL = "https://github.com/capture0x/XSS-LOADER.git"
class XSSFinder(HackingTool):
TITLE = "Extended XSS Searcher and Finder"
DESCRIPTION = "Extended XSS Searcher and Finder"
INSTALL_COMMANDS = [
"git clone https://github.com/Damian89/extended-xss-search.git"]
PROJECT_URL = "https://github.com/Damian89/extended-xss-search"
def after_install(self):
console.print(Panel.fit(
"[bold cyan]Follow These Steps After Installation:[/bold cyan]\n"
"[red]*[/red] Go to [yellow]extended-xss-search[/yellow] directory\n"
"[green]*[/green] Rename [bold]example.app-settings.conf[/bold] → [bold]app-settings.conf[/bold]",
title="[ Install Notes ]",
border_style="magenta"
))
input("Press ENTER to continue")
def run(self):
console.print(Panel.fit(
"[bold cyan]You need to add links to scan[/bold cyan]\n"
"[red]*[/red] Go to [yellow]extended-xss-search/config/urls-to-test.txt[/yellow]\n"
"[green]*[/green] Run: [bold]python3 extended-xss-search.py[/bold]",
title="[ Run Instructions ]",
border_style="blue"
))
class XSSFreak(HackingTool):
TITLE = "XSS-Freak"
DESCRIPTION = "An XSS scanner fully written in Python 3 from scratch."
INSTALL_COMMANDS = [
"git clone https://github.com/PR0PH3CY33/XSS-Freak.git",
"cd XSS-Freak;sudo pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd XSS-Freak;sudo python3 XSS-Freak.py"]
PROJECT_URL = "https://github.com/PR0PH3CY33/XSS-Freak"
class XSpear(HackingTool):
TITLE = "XSpear"
DESCRIPTION = "XSpear is an XSS Scanner built on Ruby Gems."
INSTALL_COMMANDS = ["gem install XSpear"]
RUN_COMMANDS = ["XSpear -h"]
PROJECT_URL = "https://github.com/hahwul/XSpear"
class XSSCon(HackingTool):
TITLE = "XSSCon"
INSTALL_COMMANDS = [
"git clone https://github.com/menkrep1337/XSSCon.git",
"sudo chmod 755 -R XSSCon"
]
PROJECT_URL = "https://github.com/menkrep1337/XSSCon"
def run(self):
console.print(Panel.fit(
"Enter target website to scan with XSSCon:",
title="[bold yellow]XSSCon[/bold yellow]",
border_style="bright_yellow"
))
website = Prompt.ask("[bold cyan]Enter Website[/bold cyan]")
os.system("cd XSSCon;")
subprocess.run(["python3", "xsscon.py", "-u", website])
class XanXSS(HackingTool):
TITLE = "XanXSS"
DESCRIPTION = "Reflected XSS searching tool that creates payloads from templates."
INSTALL_COMMANDS = ["git clone https://github.com/Ekultek/XanXSS.git"]
PROJECT_URL = "https://github.com/Ekultek/XanXSS"
def run(self):
os.system("cd XanXSS; python xanxss.py -h")
console.print(
"[cyan]You have to run it manually using:[/cyan]\n[bold yellow]python xanxss.py [options][/bold yellow]"
)
class XSSStrike(HackingTool):
TITLE = "Advanced XSS Detection Suite"
DESCRIPTION = "XSStrike is a Python-based tool designed to detect and exploit XSS vulnerabilities."
INSTALL_COMMANDS = [
"sudo rm -rf XSStrike",
"git clone https://github.com/UltimateHackers/XSStrike.git "
"&& cd XSStrike && pip install -r requirements.txt"
]
PROJECT_URL = "https://github.com/UltimateHackers/XSStrike"
def __init__(self):
super(XSSStrike, self).__init__(runnable=False)
class RVuln(HackingTool):
TITLE = "RVuln"
DESCRIPTION = "Multi-threaded and Automated Web Vulnerability Scanner written in Rust."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/iinc0gnit0/RVuln.git;"
"curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh;"
"source $HOME/.cargo/env;"
"sudo apt install librust-openssl-dev;"
"cd RVuln;sudo su;cargo build --release;mv target/release/RVuln"
]
RUN_COMMANDS = ["RVuln"]
PROJECT_URL = "https://github.com/iinc0gnit0/RVuln"
class XSSAttackTools(HackingToolsCollection):
TITLE = "XSS Attack Tools"
TOOLS = [
Dalfox(),
XSSPayloadGenerator(),
XSSFinder(),
XSSFreak(),
XSpear(),
XSSCon(),
XanXSS(),
XSSStrike(),
RVuln()
]
def show_info(self):
console.print(Panel.fit(
"[bold magenta]XSS Attack Tools Collection[/bold magenta]\n"
"A curated set of tools for XSS vulnerability analysis and exploitation.",
border_style="bright_magenta"
))
def show_options(self, parent=None):
console.print("\n")
self.show_info()
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
table.add_row(str(i + 1), tool.TITLE, tool.DESCRIPTION or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to Main Menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
self.TOOLS[choice - 1].show_options(parent=self)
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/anonsurf.py | tools/anonsurf.py | # coding=utf-8
import os
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from rich.text import Text
from rich.table import Table
from core import HackingTool
from core import HackingToolsCollection
console = Console()
P_COLOR = "magenta"
class AnonymouslySurf(HackingTool):
TITLE = "Anonymously Surf"
DESCRIPTION = (
"It automatically overwrites the RAM when\n"
"the system is shutting down and also change Ip."
)
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Und3rf10w/kali-anonsurf.git",
"cd kali-anonsurf && sudo ./installer.sh && cd .. && sudo rm -r kali-anonsurf",
]
RUN_COMMANDS = ["sudo anonsurf start"]
PROJECT_URL = "https://github.com/Und3rf10w/kali-anonsurf"
def __init__(self):
super(AnonymouslySurf, self).__init__([("Stop", self.stop)])
def stop(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=f"bold {P_COLOR}"))
console.print("Stopping Anonsurf...", style=f"bold {P_COLOR}")
os.system("sudo anonsurf stop")
class Multitor(HackingTool):
TITLE = "Multitor"
DESCRIPTION = "How to stay in multi places at the same time"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/trimstray/multitor.git",
"cd multitor;sudo bash setup.sh install",
]
RUN_COMMANDS = [
"multitor --init 2 --user debian-tor --socks-port 9000 --control-port 9900 --proxy privoxy --haproxy"
]
PROJECT_URL = "https://github.com/trimstray/multitor"
def __init__(self):
# keep original behavior (non-runnable) while still initializing
super(Multitor, self).__init__(runnable=False)
class AnonSurfTools(HackingToolsCollection):
TITLE = "Anonymously Hiding Tools"
DESCRIPTION = ""
TOOLS = [
AnonymouslySurf(),
Multitor(),
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Anonymously Hiding Tools", show_lines=True, expand=True)
table.add_column("Title", style="magenta", no_wrap=True)
table.add_column("Description", style="magenta")
table.add_column("Project URL", style="magenta", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc).strip().replace("\n", " "), str(url))
panel = Panel(table, title=f"[{P_COLOR}]Available Tools[/ {P_COLOR}]", border_style=P_COLOR)
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
console.print(Panel.fit(
"[bold magenta]Anonymously Hiding Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style=P_COLOR
))
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# delegate if collection-style interface exists
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# otherwise, if the tool has actions or a run method, prefer those
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = AnonSurfTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/webattack.py | tools/webattack.py | # coding=utf-8
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class Web2Attack(HackingTool):
TITLE = "Web2Attack"
DESCRIPTION = "Web hacking framework with tools, exploits by python"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/santatic/web2attack.git"
]
RUN_COMMANDS = ["cd web2attack && sudo python3 w2aconsole"]
PROJECT_URL = "https://github.com/santatic/web2attack"
class Skipfish(HackingTool):
TITLE = "Skipfish"
DESCRIPTION = (
"Skipfish – Fully automated, active web application "
"security reconnaissance tool \n "
"Usage: skipfish -o [FolderName] targetip/site"
)
RUN_COMMANDS = [
"sudo skipfish -h",
'echo "skipfish -o [FolderName] targetip/site"|boxes -d headline | lolcat'
]
def __init__(self):
super(Skipfish, self).__init__(installable=False)
class SubDomainFinder(HackingTool):
TITLE = "SubDomain Finder"
DESCRIPTION = (
"Sublist3r is a python tool designed to enumerate "
"subdomains of websites using OSINT \n "
"Usage:\n\t[1] python3 sublist3r.py -d example.com \n"
"[2] python3 sublist3r.py -d example.com -p 80,443"
)
INSTALL_COMMANDS = [
"sudo pip3 install requests argparse dnspython",
"sudo git clone https://github.com/aboul3la/Sublist3r.git",
"cd Sublist3r && sudo pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd Sublist3r && python3 sublist3r.py -h"]
PROJECT_URL = "https://github.com/aboul3la/Sublist3r"
class CheckURL(HackingTool):
TITLE = "CheckURL"
DESCRIPTION = (
"Detect evil urls that uses IDN Homograph Attack.\n\t"
"[!] python3 checkURL.py --url google.com"
)
INSTALL_COMMANDS = ["sudo git clone https://github.com/UndeadSec/checkURL.git"]
RUN_COMMANDS = ["cd checkURL && python3 checkURL.py --help"]
PROJECT_URL = "https://github.com/UndeadSec/checkURL"
class Blazy(HackingTool):
TITLE = "Blazy(Also Find ClickJacking)"
DESCRIPTION = "Blazy is a modern login page bruteforcer"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/UltimateHackers/Blazy.git",
"cd Blazy && sudo pip2.7 install -r requirements.txt"
]
RUN_COMMANDS = ["cd Blazy && sudo python2.7 blazy.py"]
PROJECT_URL = "https://github.com/UltimateHackers/Blazy"
class SubDomainTakeOver(HackingTool):
TITLE = "Sub-Domain TakeOver"
DESCRIPTION = (
"Sub-domain takeover vulnerability occur when a sub-domain "
"\n (subdomain.example.com) is pointing to a service "
"(e.g: GitHub, AWS/S3,..)\nthat has been removed or deleted.\n"
"Usage:python3 takeover.py -d www.domain.com -v"
)
INSTALL_COMMANDS = [
"git clone https://github.com/edoardottt/takeover.git",
"cd takeover;sudo python3 setup.py install"
]
PROJECT_URL = "https://github.com/edoardottt/takeover"
def __init__(self):
super(SubDomainTakeOver, self).__init__(runnable=False)
class Dirb(HackingTool):
TITLE = "Dirb"
DESCRIPTION = (
"DIRB is a Web Content Scanner. It looks for existing "
"(and/or hidden) Web Objects.\n"
"It basically works by launching a dictionary based "
"attack against \n a web server and analyzing the response."
)
INSTALL_COMMANDS = [
"sudo git clone https://gitlab.com/kalilinux/packages/dirb.git",
"cd dirb;sudo bash configure;make"
]
PROJECT_URL = "https://gitlab.com/kalilinux/packages/dirb"
def run(self):
uinput = input("Enter Url >> ")
subprocess.run(["sudo", "dirb", uinput])
class WebAttackTools(HackingToolsCollection):
TITLE = "Web Attack tools"
DESCRIPTION = ""
TOOLS = [
Web2Attack(),
Skipfish(),
SubDomainFinder(),
CheckURL(),
Blazy(),
SubDomainTakeOver(),
Dirb()
]
def pretty_print(self):
table = Table(title="Web Attack Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Web Attack Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = WebAttackTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/wireless_attack_tools.py | tools/wireless_attack_tools.py | # coding=utf-8
import os
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class WIFIPumpkin(HackingTool):
TITLE = "WiFi-Pumpkin"
DESCRIPTION = (
"The WiFi-Pumpkin is a rogue AP framework to easily create "
"these fake networks\n"
"all while forwarding legitimate traffic to and from the "
"unsuspecting target."
)
INSTALL_COMMANDS = [
"sudo apt install libssl-dev libffi-dev build-essential",
"sudo git clone https://github.com/P0cL4bs/wifipumpkin3.git",
"chmod -R 755 wifipumpkin3",
"sudo apt install python3-pyqt5",
"cd wifipumpkin3;sudo python3 setup.py install",
]
RUN_COMMANDS = ["sudo wifipumpkin3"]
PROJECT_URL = "https://github.com/P0cL4bs/wifipumpkin3"
class pixiewps(HackingTool):
TITLE = "pixiewps"
DESCRIPTION = (
"Pixiewps is a tool written in C used to bruteforce offline "
"the WPS pin\n "
"exploiting the low or non-existing entropy of some Access "
"Points, the so-called pixie dust attack"
)
INSTALL_COMMANDS = [
"sudo git clone https://github.com/wiire/pixiewps.git && apt-get -y install build-essential",
"cd pixiewps*/ && make",
"cd pixiewps*/ && sudo make install && wget https://pastebin.com/y9Dk1Wjh",
]
PROJECT_URL = "https://github.com/wiire/pixiewps"
def run(self):
os.system(
'echo "'
'1.> Put your interface into monitor mode using '
"'airmon-ng start {wireless interface}\n'"
"'2.> wash -i {monitor-interface like mon0}\'\n'"
"'3.> reaver -i {monitor interface} -b {BSSID of router} -c {router channel} -vvv -K 1 -f"
'| boxes -d boy'
)
print("You Have To Run Manually By USing >>pixiewps -h ")
class BluePot(HackingTool):
TITLE = "Bluetooth Honeypot GUI Framework"
DESCRIPTION = (
"You need to have at least 1 bluetooth receiver "
"(if you have many it will work with those, too).\n"
"You must install/libbluetooth-dev on "
"Ubuntu/bluez-libs-devel on Fedora/bluez-devel on openSUSE"
)
INSTALL_COMMANDS = [
"sudo wget https://raw.githubusercontent.com/andrewmichaelsmith/bluepot/master/bin/bluepot-0.2.tar.gz"
"sudo tar xfz bluepot-0.2.tar.gz;sudo rm bluepot-0.2.tar.gz"
]
RUN_COMMANDS = ["cd bluepot && sudo java -jar bluepot.jar"]
PROJECT_URL = "https://github.com/andrewmichaelsmith/bluepot"
class Fluxion(HackingTool):
TITLE = "Fluxion"
DESCRIPTION = "Fluxion is a remake of linset by vk496 with enhanced functionality."
INSTALL_COMMANDS = [
"git clone https://github.com/FluxionNetwork/fluxion.git",
"cd fluxion && sudo chmod +x fluxion.sh",
]
RUN_COMMANDS = ["cd fluxion;sudo bash fluxion.sh -i"]
PROJECT_URL = "https://github.com/FluxionNetwork/fluxion"
class Wifiphisher(HackingTool):
TITLE = "Wifiphisher"
DESCRIPTION = """
Wifiphisher is a rogue Access Point framework for conducting red team engagements or Wi-Fi security testing.
Using Wifiphisher, penetration testers can easily achieve a man-in-the-middle position against wireless clients by performing
targeted Wi-Fi association attacks. Wifiphisher can be further used to mount victim-customized web phishing attacks against the
connected clients in order to capture credentials (e.g. from third party login pages or WPA/WPA2 Pre-Shared Keys) or infect the
victim stations with malware..\n
For More Details Visit >> https://github.com/wifiphisher/wifiphisher
"""
INSTALL_COMMANDS = [
"git clone https://github.com/wifiphisher/wifiphisher.git",
"cd wifiphisher;sudo python3 setup.py install",
]
RUN_COMMANDS = ["cd wifiphisher;sudo wifiphisher"]
PROJECT_URL = "https://github.com/wifiphisher/wifiphisher"
class Wifite(HackingTool):
TITLE = "Wifite"
DESCRIPTION = "Wifite is an automated wireless attack tool"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/derv82/wifite2.git",
"cd wifite2 && sudo python3 setup.py install",
]
RUN_COMMANDS = ["cd wifite2; sudo wifite"]
PROJECT_URL = "https://github.com/derv82/wifite2"
class EvilTwin(HackingTool):
TITLE = "EvilTwin"
DESCRIPTION = (
"Fakeap is a script to perform Evil Twin Attack, by getting"
" credentials using a Fake page and Fake Access Point"
)
INSTALL_COMMANDS = ["sudo git clone https://github.com/Z4nzu/fakeap.git"]
RUN_COMMANDS = ["cd fakeap && sudo bash fakeap.sh"]
PROJECT_URL = "https://github.com/Z4nzu/fakeap"
class Fastssh(HackingTool):
TITLE = "Fastssh"
DESCRIPTION = (
"Fastssh is an Shell Script to perform multi-threaded scan"
" \n and brute force attack against SSH protocol using the "
"most commonly credentials."
)
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Z4nzu/fastssh.git && cd fastssh && sudo chmod +x fastssh.sh",
"sudo apt-get install -y sshpass netcat",
]
RUN_COMMANDS = ["cd fastssh && sudo bash fastssh.sh --scan"]
PROJECT_URL = "https://github.com/Z4nzu/fastssh"
class Howmanypeople(HackingTool):
TITLE = "Howmanypeople"
DESCRIPTION = (
"Count the number of people around you by monitoring wifi "
"signals.\n"
"[@] WIFI ADAPTER REQUIRED* \n[*]"
"It may be illegal to monitor networks for MAC addresses, \n"
"especially on networks that you do not own. "
"Please check your country's laws"
)
INSTALL_COMMANDS = [
"sudo apt-get install tshark"
";sudo python3 -m pip install howmanypeoplearearound"
]
RUN_COMMANDS = ["howmanypeoplearearound"]
class WirelessAttackTools(HackingToolsCollection):
TITLE = "Wireless attack tools"
DESCRIPTION = ""
TOOLS = [
WIFIPumpkin(),
pixiewps(),
BluePot(),
Fluxion(),
Wifiphisher(),
Wifite(),
EvilTwin(),
Fastssh(),
Howmanypeople(),
]
def pretty_print(self):
table = Table(title="Wireless Attack Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Wireless Attack Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = WirelessAttackTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/other_tools.py | tools/other_tools.py | # coding=utf-8
import os
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from tools.others.android_attack import AndroidAttackTools
from tools.others.email_verifier import EmailVerifyTools
from tools.others.hash_crack import HashCrackingTools
from tools.others.homograph_attacks import IDNHomographAttackTools
from tools.others.mix_tools import MixTools
from tools.others.payload_injection import PayloadInjectorTools
from tools.others.socialmedia import SocialMediaBruteforceTools
from tools.others.socialmedia_finder import SocialMediaFinderTools
from tools.others.web_crawling import WebCrawlingTools
from tools.others.wifi_jamming import WifiJammingTools
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class HatCloud(HackingTool):
TITLE = "HatCloud(Bypass CloudFlare for IP)"
DESCRIPTION = "HatCloud build in Ruby. It makes bypass in CloudFlare for " \
"discover real IP."
INSTALL_COMMANDS = ["git clone https://github.com/HatBashBR/HatCloud.git"]
PROJECT_URL = "https://github.com/HatBashBR/HatCloud"
def run(self):
site = input("Enter Site >> ")
os.chdir("HatCloud")
subprocess.run(["sudo", "ruby", "hatcloud.rb", "-b", site])
class OtherTools(HackingToolsCollection):
TITLE = "Other tools"
TOOLS = [
SocialMediaBruteforceTools(),
AndroidAttackTools(),
HatCloud(),
IDNHomographAttackTools(),
EmailVerifyTools(),
HashCrackingTools(),
WifiJammingTools(),
SocialMediaFinderTools(),
PayloadInjectorTools(),
WebCrawlingTools(),
MixTools()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Other Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc).strip().replace("\n", " "), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Other Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# If tool exposes show_options (collection-style), delegate to it
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# Otherwise, if runnable, call its run method
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = OtherTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/ddos.py | tools/ddos.py | # coding=utf-8
import os
import subprocess
from rich.console import Console
from rich.prompt import Prompt
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from core import HackingTool
from core import HackingToolsCollection
console = Console()
P_COLOR = "magenta" # primary purple/magenta theme for styling
class ddos(HackingTool):
TITLE = "ddos"
DESCRIPTION = (
"Best DDoS Attack Script With 36 Plus Methods."
"DDoS attacks\n\b "
"for SECURITY TESTING PURPOSES ONLY! "
)
INSTALL_COMMANDS = [
"git clone https://github.com/the-deepnet/ddos.git",
"cd ddos;sudo pip3 install -r requirements.txt",
]
PROJECT_URL = "https://github.com/the-deepnet/ddos.git"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=f"bold {P_COLOR}"))
method = Prompt.ask("Enter Method >>")
url = Prompt.ask("Enter URL >>")
threads = Prompt.ask("Enter Threads >>")
proxylist = Prompt.ask("Enter ProxyList >>")
multiple = Prompt.ask("Enter Multiple >>")
timer = Prompt.ask("Enter Timer >>")
os.system("cd ddos;")
subprocess.run(
[
"sudo",
"python3 ddos",
method,
url,
"socks_type5.4.1",
threads,
proxylist,
multiple,
timer,
]
)
class SlowLoris(HackingTool):
TITLE = "SlowLoris"
DESCRIPTION = (
"Slowloris is basically an HTTP Denial of Service attack."
"It send lots of HTTP Request"
)
INSTALL_COMMANDS = ["sudo pip3 install slowloris"]
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=f"bold {P_COLOR}"))
target_site = Prompt.ask("Enter Target Site:-")
subprocess.run(["slowloris", target_site])
class Asyncrone(HackingTool):
TITLE = "Asyncrone | Multifunction SYN Flood DDoS Weapon"
DESCRIPTION = (
"aSYNcrone is a C language based, mulltifunction SYN Flood "
"DDoS Weapon.\nDisable the destination system by sending a "
"SYN packet intensively to the destination."
)
INSTALL_COMMANDS = [
"git clone https://github.com/fatih4842/aSYNcrone.git",
"cd aSYNcrone;sudo gcc aSYNcrone.c -o aSYNcrone -lpthread",
]
PROJECT_URL = "https://github.com/fatihsnsy/aSYNcrone"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=f"bold {P_COLOR}"))
source_port = Prompt.ask("Enter Source Port >>")
target_ip = Prompt.ask("Enter Target IP >>")
target_port = Prompt.ask("Enter Target port >>")
os.system("cd aSYNcrone;")
subprocess.run(
["sudo", "./aSYNcrone", source_port, target_ip, target_port, 1000]
)
class UFONet(HackingTool):
TITLE = "UFOnet"
DESCRIPTION = (
"UFONet - is a free software, P2P and cryptographic "
"-disruptive \n toolkit- that allows to perform DoS and "
"DDoS attacks\n\b "
"More Usage Visit"
)
INSTALL_COMMANDS = [
"sudo git clone https://github.com/epsylon/ufonet.git",
"cd ufonet;sudo python3 setup.py install;sudo pip3 install GeoIP;sudo pip3 install python-geoip;sudo pip3 install pygeoip;sudo pip3 install requests;sudo pip3 install pycrypto;sudo pip3 install pycurl;sudo pip3 install whois;sudo pip3 install scapy-python3",
]
RUN_COMMANDS = ["sudo python3 ufonet --gui"]
PROJECT_URL = "https://github.com/epsylon/ufonet"
class GoldenEye(HackingTool):
TITLE = "GoldenEye"
DESCRIPTION = (
"GoldenEye is a python3 app for SECURITY TESTING PURPOSES ONLY!\n"
"GoldenEye is a HTTP DoS Test Tool."
)
INSTALL_COMMANDS = [
"sudo git clone https://github.com/jseidl/GoldenEye.git;"
"chmod -R 755 GoldenEye"
]
PROJECT_URL = "https://github.com/jseidl/GoldenEye"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=f"bold {P_COLOR}"))
os.system("cd GoldenEye ;sudo ./goldeneye.py")
console.print("Go to Directory\n[*] USAGE: ./goldeneye.py <url> [OPTIONS]")
class Saphyra(HackingTool):
TITLE = "SaphyraDDoS"
DESCRIPTION = "A complex python code to DDoS any website with a very easy usage.!\n"
INSTALL_COMMANDS = [
"sudo su",
"git clone https://github.com/anonymous24x7/Saphyra-DDoS.git",
"cd Saphyra-DDoS",
"chmod +x saphyra.py",
"python saphyra.py",
]
PROJECT_URL = "https://github.com/anonymous24x7/Saphyra-DDoS"
def run(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=f"bold {P_COLOR}"))
url = Prompt.ask("Enter url>>>")
try:
os.system("python saphyra.py " + url)
except Exception:
console.print("Enter a valid url.", style="bold red")
class DDOSTools(HackingToolsCollection):
TITLE = "DDOS Attack Tools"
TOOLS = [SlowLoris(), Asyncrone(), UFONet(), GoldenEye(), Saphyra()]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="DDOS Attack Tools", show_lines=True, expand=True)
table.add_column("Title", style="magenta", no_wrap=True)
table.add_column("Description", style="magenta")
table.add_column("Project URL", style="magenta", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc).strip().replace("\n", " "), str(url))
panel = Panel(table, title=f"[{P_COLOR}]Available Tools[/ {P_COLOR}]", border_style=P_COLOR)
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
console.print(Panel.fit(
"[bold magenta]DDOS Attack Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style=P_COLOR
))
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# If tool exposes show_options (collection-style), delegate to it
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# Otherwise, if runnable, call its run method
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = DDOSTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/steganography.py | tools/steganography.py | # coding=utf-8
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from core import validate_input
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class SteganoHide(HackingTool):
TITLE = "SteganoHide"
INSTALL_COMMANDS = ["sudo apt-get install steghide -y"]
def run(self):
choice_run = input(
"[1] Hide\n"
"[2] Extract\n"
"[99]Cancel\n"
">> "
)
choice_run = validate_input(choice_run, [1, 2, 99])
if choice_run is None:
console.print("[bold red]Please choose a valid input[/bold red]")
return self.run()
if choice_run == 99:
return
if choice_run == 1:
file_hide = input("Enter Filename to Embed (1.txt) >> ")
file_to_be_hide = input("Enter Cover Filename (test.jpeg) >> ")
subprocess.run(["steghide", "embed", "-cf", file_to_be_hide, "-ef", file_hide])
elif choice_run == 2:
from_file = input("Enter Filename to Extract Data From >> ")
subprocess.run(["steghide", "extract", "-sf", from_file])
class StegnoCracker(HackingTool):
TITLE = "StegnoCracker"
DESCRIPTION = "SteganoCracker uncovers hidden data inside files using brute-force utility"
INSTALL_COMMANDS = ["pip3 install stegcracker && pip3 install stegcracker -U --force-reinstall"]
def run(self):
filename = input("Enter Filename >> ")
passfile = input("Enter Wordlist Filename >> ")
subprocess.run(["stegcracker", filename, passfile])
class StegoCracker(HackingTool):
TITLE = "StegoCracker"
DESCRIPTION = "StegoCracker lets you hide and retrieve data in image or audio files"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/W1LDN16H7/StegoCracker.git",
"sudo chmod -R 755 StegoCracker"
]
RUN_COMMANDS = [
"cd StegoCracker && python3 -m pip install -r requirements.txt",
"./install.sh"
]
PROJECT_URL = "https://github.com/W1LDN16H7/StegoCracker"
class Whitespace(HackingTool):
TITLE = "Whitespace"
DESCRIPTION = "Use whitespace and unicode characters for steganography"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/beardog108/snow10.git",
"sudo chmod -R 755 snow10"
]
RUN_COMMANDS = ["cd snow10 && ./install.sh"]
PROJECT_URL = "https://github.com/beardog108/snow10"
class SteganographyTools(HackingToolsCollection):
TITLE = "Steganography Tools"
TOOLS = [SteganoHide(), StegnoCracker(), StegoCracker(), Whitespace()]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Steganography Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="").strip().replace("\n", " ")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc or "—"), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Steganography Tools Collection[/bold magenta]\nSelect a tool to run or view options.", border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = int(Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99"))
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "before_run"):
selected.before_run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = SteganographyTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/remote_administration.py | tools/remote_administration.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class Stitch(HackingTool):
TITLE = "Stitch"
DESCRIPTION = "Stitch is a cross platform python framework.\n" \
"which allows you to build custom payloads\n" \
"For Windows, Mac and Linux."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/nathanlopez/Stitch.git",
"cd Stitch;sudo pip install -r lnx_requirements.txt"
]
RUN_COMMANDS = ["cd Stitch;python main.py"]
PROJECT_URL = "https://github.com/nathanlopez/Stitch"
class Pyshell(HackingTool):
TITLE = "Pyshell"
DESCRIPTION = "Pyshell is a Rat Tool that can be able to download & upload " \
"files,\n Execute OS Command and more.."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/knassar702/Pyshell.git;"
"sudo pip install pyscreenshot python-nmap requests"
]
RUN_COMMANDS = ["cd Pyshell;./Pyshell"]
PROJECT_URL = "https://github.com/knassar702/pyshell"
class RemoteAdministrationTools(HackingToolsCollection):
TITLE = "Remote Administrator Tools (RAT)"
TOOLS = [
Stitch(),
Pyshell()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Remote Administration Tools (RAT)", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="").strip().replace("\n", " ")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc or "—"), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Remote Administration Tools (RAT) Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# If tool exposes show_options (collection-style), delegate to it
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# Otherwise, if runnable, call its run method
elif hasattr(selected, "run"):
selected.run()
# Preserve any before_run hooks if present
elif hasattr(selected, "before_run"):
selected.before_run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = RemoteAdministrationTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/exploit_frameworks.py | tools/exploit_frameworks.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from tools.webattack import Web2Attack
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from rich.prompt import Prompt
console = Console()
PURPLE_STYLE = "bold magenta"
class RouterSploit(HackingTool):
TITLE = "RouterSploit"
DESCRIPTION = "The RouterSploit Framework is an open-source exploitation " \
"framework dedicated to embedded devices"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/threat9/routersploit.git",
"cd routersploit && sudo python3 -m pip install -r requirements.txt"
]
RUN_COMMANDS = ["cd routersploit && sudo python3 rsf.py"]
PROJECT_URL = "https://github.com/threat9/routersploit"
class WebSploit(HackingTool):
TITLE = "WebSploit"
DESCRIPTION = "Websploit is an advanced MITM framework."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/The404Hacking/websploit.git;cd websploit/Setup;sudo chmod +x install.sh && sudo bash install.sh"
]
RUN_COMMANDS = ["sudo websploit"]
PROJECT_URL = "https://github.com/The404Hacking/websploit "
class Commix(HackingTool):
TITLE = "Commix"
DESCRIPTION = "Automated All-in-One OS command injection and exploitation " \
"tool.\nCommix can be used from web developers, penetration " \
"testers or even security researchers\n in order to test " \
"web-based applications with the view to find bugs,\n " \
"errors or vulnerabilities related to command injection " \
"attacks.\n Usage: python commix.py [option(s)]"
INSTALL_COMMANDS = [
"git clone https://github.com/commixproject/commix.git commix",
"cd commix;sudo python setup.py install"
]
RUN_COMMANDS = ["sudo python commix.py --wizard"]
PROJECT_URL = "https://github.com/commixproject/commix"
def __init__(self):
super(Commix, self).__init__(runnable=False)
class ExploitFrameworkTools(HackingToolsCollection):
TITLE = "Exploit framework"
TOOLS = [
RouterSploit(),
WebSploit(),
Commix(),
Web2Attack()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Exploit framework", show_lines=True, expand=True)
table.add_column("Title", style="magenta", no_wrap=True)
table.add_column("Description", style="magenta")
table.add_column("Project URL", style="magenta", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc).strip().replace("\n", " "), str(url))
panel = Panel(table, title=f"[magenta]Available Tools[/magenta]", border_style=PURPLE_STYLE)
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
console.print(Panel.fit(
"[bold magenta]Exploit Framework Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style=PURPLE_STYLE
))
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# If tool exposes show_options (collection-style), delegate to it
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# Otherwise, if runnable, call its run method
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
# --- Optional helper: pretty-print the tools list into a magenta-styled table.
# This helper is non-invasive and does not change tool logic.
def render_tools_table(tools, title: str | None = None):
"""
Render a list of HackingTool instances (or objects with TITLE/DESCRIPTION/PROJECT_URL)
as a rich table in magenta style.
"""
tbl = Table(title=title or "Tools", show_lines=False, header_style=PURPLE_STYLE)
tbl.add_column("Name", style=PURPLE_STYLE, no_wrap=True)
tbl.add_column("Description")
tbl.add_column("Project URL", overflow="fold")
for t in tools:
name = getattr(t, "TITLE", "<unknown>")
desc = getattr(t, "DESCRIPTION", "")
url = getattr(t, "PROJECT_URL", "")
tbl.add_row(name, desc, url)
console.print(Panel(tbl, border_style=PURPLE_STYLE, title=Text(title or "Toolset", style=PURPLE_STYLE)))
if __name__ == "__main__":
tools = ExploitFrameworkTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/phising_attack.py | tools/phising_attack.py | # coding=utf-8
import os
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class autophisher(HackingTool):
TITLE = "Autophisher RK"
DESCRIPTION = "Automated Phishing Toolkit"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/CodingRanjith/autophisher.git",
"cd autophisher"
]
RUN_COMMANDS = ["cd autophisher;sudo bash autophisher.sh"]
PROJECT_URL = "https://github.com/CodingRanjith/autophisher"
class Pyphisher(HackingTool):
TITLE = "Pyphisher"
DESCRIPTION = "Easy to use phishing tool with 77 website templates"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/KasRoudra/PyPhisher",
"cd PyPhisher/files",
"pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd PyPhisher;sudo python3 pyphisher.py"]
PROJECT_URL = "git clone https://github.com/KasRoudra/PyPhisher"
class AdvPhishing(HackingTool):
TITLE = "AdvPhishing"
DESCRIPTION = "This is Advance Phishing Tool ! OTP PHISHING"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Ignitetch/AdvPhishing.git",
"cd AdvPhishing;chmod 777 *;bash Linux-Setup.sh"]
RUN_COMMANDS = ["cd AdvPhishing && sudo bash AdvPhishing.sh"]
PROJECT_URL = "https://github.com/Ignitetch/AdvPhishing"
class Setoolkit(HackingTool):
TITLE = "Setoolkit"
DESCRIPTION = "The Social-Engineer Toolkit is an open-source penetration\n" \
"testing framework designed for social engine"
INSTALL_COMMANDS = [
"git clone https://github.com/trustedsec/social-engineer-toolkit/",
"cd social-engineer-toolkit && sudo python3 setup.py"
]
RUN_COMMANDS = ["sudo setoolkit"]
PROJECT_URL = "https://github.com/trustedsec/social-engineer-toolkit"
class SocialFish(HackingTool):
TITLE = "SocialFish"
DESCRIPTION = "Automated Phishing Tool & Information Collector NOTE: username is 'root' and password is 'pass'"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/UndeadSec/SocialFish.git && sudo apt-get install python3 python3-pip python3-dev -y",
"cd SocialFish && sudo python3 -m pip install -r requirements.txt"
]
RUN_COMMANDS = ["cd SocialFish && sudo python3 SocialFish.py root pass"]
PROJECT_URL = "https://github.com/UndeadSec/SocialFish"
class HiddenEye(HackingTool):
TITLE = "HiddenEye"
DESCRIPTION = "Modern Phishing Tool With Advanced Functionality And " \
"Multiple Tunnelling Services \n" \
"\t [!]https://github.com/DarkSecDevelopers/HiddenEye"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Morsmalleo/HiddenEye.git ;sudo chmod 777 HiddenEye",
"cd HiddenEye;sudo pip3 install -r requirements.txt;sudo pip3 install requests;pip3 install pyngrok"
]
RUN_COMMANDS = ["cd HiddenEye;sudo python3 HiddenEye.py"]
PROJECT_URL = "https://github.com/Morsmalleo/HiddenEye.git"
class Evilginx2(HackingTool):
TITLE = "Evilginx2"
DESCRIPTION = "evilginx2 is a man-in-the-middle attack framework used " \
"for phishing login credentials along with session cookies,\n" \
"which in turn allows to bypass 2-factor authentication protection.\n\n\t " \
"[+]Make sure you have installed GO of version at least 1.14.0 \n" \
"[+]After installation, add this to your ~/.profile, assuming that you installed GO in /usr/local/go\n\t " \
"[+]export GOPATH=$HOME/go \n " \
"[+]export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin \n" \
"[+]Then load it with source ~/.profiles."
INSTALL_COMMANDS = [
"sudo apt-get install git make;go get -u github.com/kgretzky/evilginx2",
"cd $GOPATH/src/github.com/kgretzky/evilginx2;make",
"sudo make install;sudo evilginx"
]
RUN_COMMANDS = ["sudo evilginx"]
PROJECT_URL = "https://github.com/kgretzky/evilginx2"
class ISeeYou(HackingTool):
TITLE = "I-See_You"
DESCRIPTION = "[!] ISeeYou is a tool to find Exact Location of Victom By" \
" User SocialEngineering or Phishing Engagement..\n" \
"[!] Users can expose their local servers to the Internet " \
"and decode the location coordinates by looking at the log file"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Viralmaniar/I-See-You.git",
"cd I-See-You && sudo chmod u+x ISeeYou.sh"
]
RUN_COMMANDS = ["cd I-See-You && sudo bash ISeeYou.sh"]
PROJECT_URL = "https://github.com/Viralmaniar/I-See-You"
class SayCheese(HackingTool):
TITLE = "SayCheese"
DESCRIPTION = "Take webcam shots from target just sending a malicious link"
INSTALL_COMMANDS = ["sudo git clone https://github.com/hangetzzu/saycheese"]
RUN_COMMANDS = ["cd saycheese && sudo bash saycheese.sh"]
PROJECT_URL = "https://github.com/hangetzzu/saycheese"
class QRJacking(HackingTool):
TITLE = "QR Code Jacking"
DESCRIPTION = "QR Code Jacking (Any Website)"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/cryptedwolf/ohmyqr.git && sudo apt -y install scrot"]
RUN_COMMANDS = ["cd ohmyqr && sudo bash ohmyqr.sh"]
PROJECT_URL = "https://github.com/cryptedwolf/ohmyqr"
class WifiPhisher(HackingTool):
TITLE = "WifiPhisher"
DESCRIPTION = "The Rogue Access Point Framework"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/wifiphisher/wifiphisher.git",
"cd wifiphisher"]
RUN_COMMANDS = ["cd wifiphisher && sudo python setup.py"]
PROJECT_URL = "https://github.com/wifiphisher/wifiphisher"
class BlackEye(HackingTool):
TITLE = "BlackEye"
DESCRIPTION = "The ultimate phishing tool with 38 websites available!"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/thelinuxchoice/blackeye",
"cd blackeye "]
RUN_COMMANDS = ["cd blackeye && sudo bash blackeye.sh"]
PROJECT_URL = "https://github.com/An0nUD4Y/blackeye"
class ShellPhish(HackingTool):
TITLE = "ShellPhish"
DESCRIPTION = "Phishing Tool for 18 social media"
INSTALL_COMMANDS = ["git clone https://github.com/An0nUD4Y/shellphish.git"]
RUN_COMMANDS = ["cd shellphish;sudo bash shellphish.sh"]
PROJECT_URL = "https://github.com/An0nUD4Y/shellphish"
class Thanos(HackingTool):
TITLE = "Thanos"
DESCRIPTION = "Browser to Browser Phishingtoolkit"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/TridevReddy/Thanos.git",
"cd Thanos && sudo chmod -R 777 Thanos.sh"
]
RUN_COMMANDS = ["cd Thanos;sudo bash Thanos.sh"]
PROJECT_URL = "https://github.com/TridevReddy/Thanos"
class QRLJacking(HackingTool):
TITLE = "QRLJacking"
DESCRIPTION = "QRLJacking"
INSTALL_COMMANDS = [
"git clone https://github.com/OWASP/QRLJacking.git",
"cd QRLJacking",
"git clone https://github.com/mozilla/geckodriver.git",
"chmod +x geckodriver",
"sudo mv -f geckodriver /usr/local/share/geckodriver",
"sudo ln -s /usr/local/share/geckodriver /usr/local/bin/geckodriver",
"sudo ln -s /usr/local/share/geckodriver /usr/bin/geckodriver",
"cd QRLJacker;pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd QRLJacking/QRLJacker;python3 QrlJacker.py"]
PROJECT_URL = "https://github.com/OWASP/QRLJacking"
class Maskphish(HackingTool):
TITLE = "Miskphish"
DESCRIPTION = "Hide phishing URL under a normal looking URL (google.com or facebook.com)"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/jaykali/maskphish.git",
"cd maskphish"]
RUN_COMMANDS = ["cd maskphish;sudo bash maskphish.sh"]
PROJECT_URL = "https://github.com/jaykali/maskphish"
class BlackPhish(HackingTool):
TITLE = "BlackPhish"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/iinc0gnit0/BlackPhish.git",
"cd BlackPhish;sudo bash install.sh"
]
RUN_COMMANDS = ["cd BlackPhish;sudo python3 blackphish.py"]
PROJECT_URL = "https://github.com/iinc0gnit0/BlackPhish"
def __init__(self):
super(BlackPhish, self).__init__([('Update', self.update)])
def update(self):
os.system("cd BlackPhish;sudo bash update.sh")
class dnstwist(HackingTool):
Title = 'dnstwist'
Install_commands = ['sudo git clone https://github.com/elceef/dnstwist.git','cd dnstwist']
Run_commands = ['cd dnstwist;sudo python3 dnstwist.py']
project_url = 'https://github.com/elceef/dnstwist'
class PhishingAttackTools(HackingToolsCollection):
TITLE = "Phishing attack tools"
TOOLS = [
autophisher(),
Pyphisher(),
AdvPhishing(),
Setoolkit(),
SocialFish(),
HiddenEye(),
Evilginx2(),
ISeeYou(),
SayCheese(),
QRJacking(),
BlackEye(),
ShellPhish(),
Thanos(),
QRLJacking(),
BlackPhish(),
Maskphish(),
dnstwist()
]
def _get_attr_fallback(self, item, *names, default=""):
for n in names:
if hasattr(item, n):
return getattr(item, n)
return default
def pretty_print(self):
table = Table(title="Phishing Attack Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
# try typical attribute names, then fall back to common variations
title = (
self._get_attr_fallback(t, "TITLE", "Title", "title")
or t.__class__.__name__
)
desc = self._get_attr_fallback(t, "DESCRIPTION", "Description", "description", "INSTALL_COMMANDS", default="") or ""
# prefer PROJECT_URL but also accept project_url or project_url-like fields
url = self._get_attr_fallback(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="") or ""
table.add_row(str(title), str(desc).strip().replace("\n", " "), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Phishing Attack Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr_fallback(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr_fallback(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# If tool exposes show_options (collection-style), delegate to it
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# Otherwise, if runnable, call its run method
elif hasattr(selected, "run"):
selected.run()
# Preserve any before_run hooks if present
elif hasattr(selected, "before_run"):
selected.before_run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = PhishingAttackTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/post_exploitation.py | tools/post_exploitation.py | # coding=utf-8
import os
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class Vegile(HackingTool):
TITLE = "Vegile - Ghost In The Shell"
DESCRIPTION = "This tool will set up your backdoor/rootkits when " \
"backdoor is already setup it will be \n" \
"hidden your specific process,unlimited your session in " \
"metasploit and transparent."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Screetsec/Vegile.git",
"cd Vegile && sudo chmod +x Vegile"
]
RUN_COMMANDS = ["cd Vegile && sudo bash Vegile"]
PROJECT_URL = "https://github.com/Screetsec/Vegile"
def before_run(self):
os.system('echo "You can Use Command: \n'
'[!] Vegile -i / --inject [backdoor/rootkit] \n'
'[!] Vegile -u / --unlimited [backdoor/rootkit] \n'
'[!] Vegile -h / --help"|boxes -d parchment')
class ChromeKeyLogger(HackingTool):
TITLE = "Chrome Keylogger"
DESCRIPTION = "Hera Chrome Keylogger"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/UndeadSec/HeraKeylogger.git",
"cd HeraKeylogger && sudo apt-get install python3-pip -y && sudo pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd HeraKeylogger && sudo python3 hera.py"]
PROJECT_URL = "https://github.com/UndeadSec/HeraKeylogger"
class PostExploitationTools(HackingToolsCollection):
TITLE = "Post exploitation tools"
TOOLS = [
Vegile(),
ChromeKeyLogger()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Post-Exploitation Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="").strip().replace("\n", " ")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc or "—"), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Post-Exploitation Tools Collection[/bold magenta]\n"
"Select a tool to view options or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# Delegate to collection-style show_options if available
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# Otherwise call run if available
elif hasattr(selected, "run"):
selected.run()
# If tool exposes before_run (like Vegile), call it to preserve original behavior
elif hasattr(selected, "before_run"):
selected.before_run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = PostExploitationTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/forensic_tools.py | tools/forensic_tools.py | # coding=utf-8
import os
import sys
# Fetching parent directory for importing core.py
current_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich.prompt import Prompt
console = Console()
PURPLE_STYLE = "bold magenta"
class Autopsy(HackingTool):
TITLE = "Autopsy"
DESCRIPTION = "Autopsy is a platform that is used by Cyber Investigators.\n" \
"[!] Works in any OS\n" \
"[!] Recover Deleted Files from any OS & Media \n" \
"[!] Extract Image Metadata"
RUN_COMMANDS = ["sudo autopsy"]
def __init__(self):
super(Autopsy, self).__init__(installable=False)
class Wireshark(HackingTool):
TITLE = "Wireshark"
DESCRIPTION = "Wireshark is a network capture and analyzer \n" \
"tool to see what’s happening in your network.\n " \
"And also investigate Network related incident"
RUN_COMMANDS = ["sudo wireshark"]
def __init__(self):
super(Wireshark, self).__init__(installable=False)
class BulkExtractor(HackingTool):
TITLE = "Bulk extractor"
DESCRIPTION = "Extract useful information without parsing the file system"
PROJECT_URL = "https://github.com/simsong/bulk_extractor"
def __init__(self):
super(BulkExtractor, self).__init__([
('GUI Mode (Download required)', self.gui_mode),
('CLI Mode', self.cli_mode)
], installable=False, runnable=False)
def gui_mode(self):
console.print(Panel(Text(self.TITLE, justify="center"), style=PURPLE_STYLE))
console.print("[bold magenta]Cloning repository and attempting to run GUI...[/]")
os.system("sudo git clone https://github.com/simsong/bulk_extractor.git")
os.system("ls src/ && cd .. && cd java_gui && ./BEViewer")
console.print(
"[magenta]If you get an error after clone go to /java_gui/src/ and compile the .jar file && run ./BEViewer[/]")
console.print(
"[magenta]Please visit for more details about installation: https://github.com/simsong/bulk_extractor[/]")
def cli_mode(self):
console.print(Panel(Text(self.TITLE + " - CLI Mode", justify="center"), style=PURPLE_STYLE))
os.system("sudo apt install bulk-extractor")
console.print("[magenta]Showing bulk_extractor help and options:[/]")
os.system("bulk_extractor -h")
os.system('echo "bulk_extractor [options] imagefile" | boxes -d headline | lolcat')
class Guymager(HackingTool):
TITLE = "Disk Clone and ISO Image Acquire"
DESCRIPTION = "Guymager is a free forensic imager for media acquisition."
INSTALL_COMMANDS = ["sudo apt install guymager"]
RUN_COMMANDS = ["sudo guymager"]
PROJECT_URL = "https://guymager.sourceforge.io/"
def __init__(self):
super(Guymager, self).__init__(installable=False)
class Toolsley(HackingTool):
TITLE = "Toolsley"
DESCRIPTION = "Toolsley got more than ten useful tools for investigation.\n" \
"[+]File signature verifier\n" \
"[+]File identifier \n" \
"[+]Hash & Validate \n" \
"[+]Binary inspector \n " \
"[+]Encode text \n" \
"[+]Data URI generator \n" \
"[+]Password generator"
PROJECT_URL = "https://www.toolsley.com/"
def __init__(self):
super(Toolsley, self).__init__(installable=False, runnable=False)
class ForensicTools(HackingToolsCollection):
TITLE = "Forensic tools"
TOOLS = [
Autopsy(),
Wireshark(),
BulkExtractor(),
Guymager(),
Toolsley()
]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="Forensic Tools", show_lines=True, expand=True)
table.add_column("Title", style=PURPLE_STYLE, no_wrap=True)
table.add_column("Description", style=PURPLE_STYLE)
table.add_column("Project URL", style=PURPLE_STYLE, no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc).replace("\n", " "), str(url))
console.print(Panel(table, title=f"[magenta]Available Tools[/magenta]", border_style=PURPLE_STYLE))
def show_options(self, parent=None):
console.print("\n")
console.print(Panel.fit(
"[bold magenta]Forensic Tools Collection[/bold magenta]\n"
"Select a tool to run or view options.",
border_style=PURPLE_STYLE
))
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
# delegate to collection-like tools if available
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
# if tool exposes actions (like BulkExtractor) and has a menu, try to show it
elif hasattr(selected, "show_actions"):
selected.show_actions(parent=self)
# otherwise try to call run if present
elif hasattr(selected, "run"):
selected.run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = ForensicTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/sql_tools.py | tools/sql_tools.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class Sqlmap(HackingTool):
TITLE = "Sqlmap tool"
DESCRIPTION = "sqlmap is an open source penetration testing tool that " \
"automates the process of detecting and exploiting SQL injection flaws " \
"and taking over database servers. [!] python3 sqlmap.py -u [http://example.com] --batch --banner. More usage: https://github.com/sqlmapproject/sqlmap/wiki/Usage"
INSTALL_COMMANDS = ["sudo git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev"]
RUN_COMMANDS = ["cd sqlmap-dev;python3 sqlmap.py --wizard"]
PROJECT_URL = "https://github.com/sqlmapproject/sqlmap"
class NoSqlMap(HackingTool):
TITLE = "NoSqlMap"
DESCRIPTION = "NoSQLMap is an open source Python tool designed to audit and automate injection attacks. [*] Please install MongoDB."
INSTALL_COMMANDS = ["git clone https://github.com/codingo/NoSQLMap.git",
"sudo chmod -R 755 NoSQLMap;cd NoSQLMap;python setup.py install"]
RUN_COMMANDS = ["python NoSQLMap"]
PROJECT_URL = "https://github.com/codingo/NoSQLMap"
class SQLiScanner(HackingTool):
TITLE = "Damn Small SQLi Scanner"
DESCRIPTION = "DSSS is a fully functional SQL injection vulnerability scanner also supporting GET and POST parameters. Usage: python3 dsss.py -h | -u [URL]"
INSTALL_COMMANDS = ["git clone https://github.com/stamparm/DSSS.git"]
PROJECT_URL = "https://github.com/stamparm/DSSS"
def __init__(self):
super(SQLiScanner, self).__init__(runnable=False)
class Explo(HackingTool):
TITLE = "Explo"
DESCRIPTION = "Explo is a simple tool to describe web security issues in human and machine readable format. Usage: explo [--verbose|-v] testcase.yaml | explo [--verbose|-v] examples/*.yaml"
INSTALL_COMMANDS = ["git clone https://github.com/dtag-dev-sec/explo.git",
"cd explo;sudo python setup.py install"]
PROJECT_URL = "https://github.com/dtag-dev-sec/explo"
def __init__(self):
super(Explo, self).__init__(runnable=False)
class Blisqy(HackingTool):
TITLE = "Blisqy - Exploit Time-based blind-SQL injection"
DESCRIPTION = "Blisqy helps web security researchers find time-based blind SQL injections on HTTP headers and exploit them."
INSTALL_COMMANDS = ["git clone https://github.com/JohnTroony/Blisqy.git"]
PROJECT_URL = "https://github.com/JohnTroony/Blisqy"
def __init__(self):
super(Blisqy, self).__init__(runnable=False)
class Leviathan(HackingTool):
TITLE = "Leviathan - Wide Range Mass Audit Toolkit"
DESCRIPTION = "Leviathan is a mass audit toolkit with service discovery, brute force, SQL injection detection, and custom exploit capabilities. Requires API keys."
INSTALL_COMMANDS = ["git clone https://github.com/leviathan-framework/leviathan.git",
"cd leviathan;sudo pip install -r requirements.txt"]
RUN_COMMANDS = ["cd leviathan;python leviathan.py"]
PROJECT_URL = "https://github.com/leviathan-framework/leviathan"
class SQLScan(HackingTool):
TITLE = "SQLScan"
DESCRIPTION = "SQLScan is a quick web scanner to find SQL injection points. Not for educational purposes."
INSTALL_COMMANDS = ["sudo apt install php php-bz2 php-curl php-mbstring curl",
"sudo curl https://raw.githubusercontent.com/Cvar1984/sqlscan/dev/build/main.phar --output /usr/local/bin/sqlscan",
"chmod +x /usr/local/bin/sqlscan"]
RUN_COMMANDS = ["sudo sqlscan"]
PROJECT_URL = "https://github.com/Cvar1984/sqlscan"
class SqlInjectionTools(HackingToolsCollection):
TITLE = "SQL Injection Tools"
TOOLS = [Sqlmap(), NoSqlMap(), SQLiScanner(), Explo(), Blisqy(), Leviathan(), SQLScan()]
def _get_attr(self, obj, *names, default=""):
for n in names:
if hasattr(obj, n):
return getattr(obj, n)
return default
def pretty_print(self):
table = Table(title="SQL Injection Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
title = self._get_attr(t, "TITLE", "Title", "title", default=t.__class__.__name__)
desc = self._get_attr(t, "DESCRIPTION", "Description", "description", default="").strip().replace("\n", " ")
url = self._get_attr(t, "PROJECT_URL", "PROJECT_URL", "PROJECT", "project_url", "projectUrl", default="")
table.add_row(str(title), str(desc or "—"), str(url))
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]SQL Injection Tools Collection[/bold magenta]\nSelect a tool to view options or run it.", border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = self._get_attr(tool, "TITLE", "Title", "title", default=tool.__class__.__name__)
desc = self._get_attr(tool, "DESCRIPTION", "Description", "description", default="—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = int(Prompt.ask("[bold cyan]Select a tool to run[/bold cyan]", default="99"))
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "before_run"):
selected.before_run()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = SqlInjectionTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/email_verifier.py | tools/others/email_verifier.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class KnockMail(HackingTool):
TITLE = "Knockmail"
DESCRIPTION = "KnockMail Tool Verify If Email Exists"
INSTALL_COMMANDS = [
"git clone https://github.com/heywoodlh/KnockMail.git",
"cd KnockMail;sudo pip3 install -r requirements.txt"
]
RUN_COMMANDS = ["cd KnockMail;python3 knockmail.py"]
PROJECT_URL = "https://github.com/heywoodlh/KnockMail"
class EmailVerifyTools(HackingToolsCollection):
TITLE = "Email Verify tools"
TOOLS = [KnockMail()]
def pretty_print(self):
table = Table(title="Email Verify Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Email Verify Tools Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = EmailVerifyTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/mix_tools.py | tools/others/mix_tools.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class TerminalMultiplexer(HackingTool):
TITLE = "Terminal Multiplexer"
DESCRIPTION = "Terminal Multiplexer is a tiling terminal emulator that " \
"allows us to open \n several terminal sessions inside one " \
"single window."
INSTALL_COMMANDS = ["sudo apt-get install tilix"]
def __init__(self):
super(TerminalMultiplexer, self).__init__(runnable = False)
class Crivo(HackingTool):
TITLE = "Crivo"
DESCRIPTION = "A tool for extracting and filtering URLs, IPs, domains, " \
"\n and subdomains from web pages or text, " \
"with built-in web scraping capabilities.\n" \
"See: python3 crivo_cli.py -h"
INSTALL_COMMANDS = [
"git clone https://github.com/GMDSantana/crivo.git",
"cd crivo;pip install -r requirements.txt"
]
PROJECT_URL = "https://github.com/GMDSantana/crivo"
def __init__(self):
super(Crivo, self).__init__(runnable = False)
class MixTools(HackingToolsCollection):
TITLE = "Mix tools"
TOOLS = [
TerminalMultiplexer(),
Crivo()
]
def pretty_print(self):
table = Table(title="Mix Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Mix Tools Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = MixTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/android_attack.py | tools/others/android_attack.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class Keydroid(HackingTool):
TITLE = "Keydroid"
DESCRIPTION = "Android Keylogger + Reverse Shell\n" \
"[!] You have to install Some Manually Refer Below Link:\n " \
"[+] https://github.com/F4dl0/keydroid"
INSTALL_COMMANDS = ["sudo git clone https://github.com/F4dl0/keydroid.git"]
RUN_COMMANDS = ["cd keydroid && bash keydroid.sh"]
PROJECT_URL = "https://github.com/F4dl0/keydroid"
class MySMS(HackingTool):
TITLE = "MySMS"
DESCRIPTION = "Script that generates an Android App to hack SMS through WAN \n" \
"[!] You have to install Some Manually Refer Below Link:\n\t " \
"[+] https://github.com/papusingh2sms/mysms"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/papusingh2sms/mysms.git"]
RUN_COMMANDS = ["cd mysms && bash mysms.sh"]
PROJECT_URL = "https://github.com/papusingh2sms/mysms"
class LockPhish(HackingTool):
TITLE = "Lockphish (Grab target LOCK PIN)"
DESCRIPTION = "Lockphish it's the first tool for phishing attacks on the " \
"lock screen, designed to\n Grab Windows credentials,Android" \
" PIN and iPhone Passcode using a https link."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/JasonJerry/lockphish.git"]
RUN_COMMANDS = ["cd lockphish && bash lockphish.sh"]
PROJECT_URL = "https://github.com/JasonJerry/lockphish"
class Droidcam(HackingTool):
TITLE = "DroidCam (Capture Image)"
DESCRIPTION = "Powerful Tool For Grab Front Camera Snap Using A Link"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/kinghacker0/WishFish.git;"
"sudo apt install php wget openssh-client"
]
RUN_COMMANDS = ["cd WishFish && sudo bash wishfish.sh"]
PROJECT_URL = "https://github.com/kinghacker0/WishFish"
class EvilApp(HackingTool):
TITLE = "EvilApp (Hijack Session)"
DESCRIPTION = "EvilApp is a script to generate Android App that can " \
"hijack authenticated sessions in cookies."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/crypticterminal/EvilApp.git"]
RUN_COMMANDS = ["cd EvilApp && bash evilapp.sh"]
PROJECT_URL = "https://github.com/crypticterminal/EvilApp"
class AndroidAttackTools(HackingToolsCollection):
TITLE = "Android Hacking tools"
TOOLS = [
Keydroid(),
MySMS(),
LockPhish(),
Droidcam(),
EvilApp()
]
def pretty_print(self):
table = Table(title="Android Attack Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Android Attack Tools Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = AndroidAttackTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/hash_crack.py | tools/others/hash_crack.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class HashBuster(HackingTool):
TITLE = "Hash Buster"
DESCRIPTION = "Features: \n " \
"Automatic hash type identification \n " \
"Supports MD5, SHA1, SHA256, SHA384, SHA512"
INSTALL_COMMANDS = [
"git clone https://github.com/s0md3v/Hash-Buster.git",
"cd Hash-Buster;make install"
]
RUN_COMMANDS = ["buster -h"]
PROJECT_URL = "https://github.com/s0md3v/Hash-Buster"
class HashCrackingTools(HackingToolsCollection):
TITLE = "Hash cracking tools"
TOOLS = [HashBuster()]
def pretty_print(self):
table = Table(title="Hash Cracking Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Hash Cracking Tools Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = HashCrackingTools()
tools.pretty_print()
tools.show_options()
| python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/socialmedia_finder.py | tools/others/socialmedia_finder.py | # coding=utf-8
import os
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class FacialFind(HackingTool):
TITLE = "Find SocialMedia By Facial Recognation System"
DESCRIPTION = "A Social Media Mapping Tool that correlates profiles\n " \
"via facial recognition across different sites."
INSTALL_COMMANDS = [
"sudo apt install -y software-properties-common",
"sudo add-apt-repository ppa:mozillateam/firefox-next && sudo apt update && sudo apt upgrade",
"sudo git clone https://github.com/Greenwolf/social_mapper.git",
"sudo apt install -y build-essential cmake libgtk-3-dev libboost-all-dev",
"cd social_mapper/setup",
"sudo python3 -m pip install --no-cache-dir -r requirements.txt",
'echo "[!]Now You have To do some Manually\n'
'[!] Install the Geckodriver for your operating system\n'
'[!] Copy & Paste Link And Download File As System Configuration\n'
'[#] https://github.com/mozilla/geckodriver/releases\n'
'[!!] On Linux you can place it in /usr/bin "| boxes | lolcat'
]
PROJECT_URL = "https://github.com/Greenwolf/social_mapper"
def run(self):
os.system("cd social_mapper/setup")
os.system("sudo python social_mapper.py -h")
print("""\033[95m
You have to set Username and password of your AC Or Any Fack Account
[#] Type in Terminal nano social_mapper.py
""")
os.system(
'echo "python social_mapper.py -f [<imageFoldername>] -i [<imgFolderPath>] -m fast [<AcName>] -fb -tw"| boxes | lolcat')
class FindUser(HackingTool):
TITLE = "Find SocialMedia By UserName"
DESCRIPTION = "Find usernames across over 75 social networks"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/xHak9x/finduser.git",
"cd finduser && sudo chmod +x finduser.sh"
]
RUN_COMMANDS = ["cd finduser && sudo bash finduser.sh"]
PROJECT_URL = "https://github.com/xHak9x/finduser"
class Sherlock(HackingTool):
TITLE = "Sherlock"
DESCRIPTION = "Hunt down social media accounts by username across social networks \n " \
"For More Usage \n" \
"\t >>python3 sherlock --help"
INSTALL_COMMANDS = [
"git clone https://github.com/sherlock-project/sherlock.git",
"cd sherlock;sudo python3 -m pip install -r requirements.txt"
]
PROJECT_URL = "https://github.com/sherlock-project/sherlock"
def run(self):
name = input("Enter Username >> ")
os.chdir('sherlock')
subprocess.run(["sudo", "python3", "sherlock", f"{name}"])
class SocialScan(HackingTool):
TITLE = "SocialScan | Username or Email"
DESCRIPTION = "Check email address and username availability on online " \
"platforms with 100% accuracy"
INSTALL_COMMANDS = ["sudo pip install socialscan"]
PROJECT_URL = "https://github.com/iojw/socialscan"
def run(self):
name = input(
"Enter Username or Emailid (if both then please space between email & username) >> ")
subprocess.run(["sudo", "socialscan", f"{name}"])
class SocialMediaFinderTools(HackingToolsCollection):
TITLE = "SocialMedia Finder"
TOOLS = [
FacialFind(),
FindUser(),
Sherlock(),
SocialScan()
]
def pretty_print(self):
table = Table(title="Social Media Finder Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Social Media Finder Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = SocialMediaFinderTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/web_crawling.py | tools/others/web_crawling.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class GoSpider(HackingTool):
TITLE = "Gospider"
DESCRIPTION = "Gospider - Fast web spider written in Go"
INSTALL_COMMANDS = ["sudo go get -u github.com/jaeles-project/gospider"]
PROJECT_URL = "https://github.com/jaeles-project/gospider"
def __init__(self):
super(GoSpider, self).__init__(runnable = False)
class WebCrawlingTools(HackingToolsCollection):
TITLE = "Web crawling"
TOOLS = [GoSpider()]
def pretty_print(self):
table = Table(title="Web Crawling Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Web Crawling Tools Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = WebCrawlingTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/socialmedia.py | tools/others/socialmedia.py | # coding=utf-8
import contextlib
import os
import subprocess
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class InstaBrute(HackingTool):
TITLE = "Instagram Attack"
DESCRIPTION = "Brute force attack against Instagram"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/chinoogawa/instaBrute.git",
"cd instaBrute;sudo pip2.7 install -r requirements.txt"
]
PROJECT_URL = "https://github.com/chinoogawa/instaBrute"
def run(self):
name = input("Enter Username >> ")
wordlist = input("Enter wordword list >> ")
os.chdir("instaBrute")
subprocess.run(
["sudo", "python", "instaBrute.py", "-u", f"{name}", "-d",
f"{wordlist}"])
class BruteForce(HackingTool):
TITLE = "AllinOne SocialMedia Attack"
DESCRIPTION = "Brute_Force_Attack Gmail Hotmail Twitter Facebook Netflix \n" \
"[!] python3 Brute_Force.py -g <Account@gmail.com> -l <File_list>"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Matrix07ksa/Brute_Force.git",
"cd Brute_Force;sudo pip3 install proxylist;pip3 install mechanize"
]
RUN_COMMANDS = ["cd Brute_Force;python3 Brute_Force.py -h"]
PROJECT_URL = "https://github.com/Matrix07ksa/Brute_Force"
class Faceshell(HackingTool):
TITLE = "Facebook Attack"
DESCRIPTION = "Facebook BruteForcer"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/Matrix07ksa/Brute_Force.git",
"cd Brute_Force;sudo pip3 install proxylist;pip3 install mechanize"
]
PROJECT_URL = "https://github.com/Matrix07ksa/Brute_Force"
def run(self):
name = input("Enter Username >> ")
wordlist = input("Enter Wordlist >> ")
with contextlib.suppress(FileNotFoundError):
os.chdir("Brute_Force")
subprocess.run(
["python3", "Brute_Force.py", "-f", f"{name}", "-l", f"{wordlist}"])
class AppCheck(HackingTool):
TITLE = "Application Checker"
DESCRIPTION = "Tool to check if an app is installed on the target device through a link."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/jakuta-tech/underhanded.git",
"cd underhanded && sudo chmod +x underhanded.sh"
]
RUN_COMMANDS = ["cd underhanded;sudo bash underhanded.sh"]
PROJECT_URL = "https://github.com/jakuta-tech/underhanded"
class SocialMediaBruteforceTools(HackingToolsCollection):
TITLE = "SocialMedia Bruteforce"
TOOLS = [
InstaBrute(),
BruteForce(),
Faceshell(),
AppCheck()
]
def pretty_print(self):
table = Table(title="Social Media Bruteforce Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Social Media Bruteforce Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = SocialMediaBruteforceTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/payload_injection.py | tools/others/payload_injection.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class DebInject(HackingTool):
TITLE = "Debinject"
DESCRIPTION = "Debinject is a tool that inject malicious code into *.debs"
INSTALL_COMMANDS = [
"sudo git clone https://github.com/UndeadSec/Debinject.git"]
RUN_COMMANDS = ["cd Debinject;python debinject.py"]
PROJECT_URL = "https://github.com/UndeadSec/Debinject"
class Pixload(HackingTool):
TITLE = "Pixload"
DESCRIPTION = "Pixload -- Image Payload Creating tools \n " \
"Pixload is Set of tools for creating/injecting payload into images."
INSTALL_COMMANDS = [
"sudo apt install libgd-perl libimage-exiftool-perl libstring-crc32-perl",
"sudo git clone https://github.com/chinarulezzz/pixload.git"
]
PROJECT_URL = "https://github.com/chinarulezzz/pixload"
def __init__(self):
super(Pixload, self).__init__(runnable = False)
class PayloadInjectorTools(HackingToolsCollection):
TITLE = "Payload Injector"
TOOLS = [
DebInject(),
Pixload()
]
def pretty_print(self):
table = Table(title="Payload Injector Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Payload Injector Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = PayloadInjectorTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/homograph_attacks.py | tools/others/homograph_attacks.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class EvilURL(HackingTool):
TITLE = "EvilURL"
DESCRIPTION = "Generate unicode evil domains for IDN Homograph Attack " \
"and detect them."
INSTALL_COMMANDS = ["git clone https://github.com/UndeadSec/EvilURL.git"]
RUN_COMMANDS = ["cd EvilURL;python3 evilurl.py"]
PROJECT_URL = "https://github.com/UndeadSec/EvilURL"
class IDNHomographAttackTools(HackingToolsCollection):
TITLE = "IDN Homograph Attack"
TOOLS = [EvilURL()]
def pretty_print(self):
table = Table(title="IDN Homograph Attack Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]IDN Homograph Attack Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = IDNHomographAttackTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
Z4nzu/hackingtool | https://github.com/Z4nzu/hackingtool/blob/7df27d8383095257e05c9dfd5af3ea696039d793/tools/others/wifi_jamming.py | tools/others/wifi_jamming.py | # coding=utf-8
from core import HackingTool
from core import HackingToolsCollection
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel
from rich.prompt import Prompt
from rich import box
_theme = Theme({"purple": "#7B61FF"})
console = Console(theme=_theme)
class WifiJammerNG(HackingTool):
TITLE = "WifiJammer-NG"
DESCRIPTION = "Continuously jam all wifi clients and access points within range."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/MisterBianco/wifijammer-ng.git",
"cd wifijammer-ng;sudo pip install -r requirements.txt"
]
RUN_COMMANDS = [
'echo "python wifijammer.py [-a AP MAC] [-c CHANNEL] [-d] [-i INTERFACE] [-m MAXIMUM] [-k] [-p PACKETS] [-s SKIP] [-t TIME INTERVAL] [-D]"| boxes | lolcat',
"cd wifijammer-ng;sudo python wifijammer.py"
]
PROJECT_URL = "https://github.com/MisterBianco/wifijammer-ng"
class KawaiiDeauther(HackingTool):
TITLE = "KawaiiDeauther"
DESCRIPTION = "Kawaii Deauther is a pentest toolkit whose goal is to perform \n " \
"jam on WiFi clients/routers and spam many fake AP for testing purposes."
INSTALL_COMMANDS = [
"sudo git clone https://github.com/aryanrtm/KawaiiDeauther.git",
"cd KawaiiDeauther;sudo bash install.sh"
]
RUN_COMMANDS = ["cd KawaiiDeauther;sudo bash KawaiiDeauther.sh"]
PROJECT_URL = "https://github.com/aryanrtm/KawaiiDeauther"
class WifiJammingTools(HackingToolsCollection):
TITLE = "Wifi Deauthenticate"
TOOLS = [
WifiJammerNG(),
KawaiiDeauther()
]
def pretty_print(self):
table = Table(title="Wifi Jamming Tools", show_lines=True, expand=True)
table.add_column("Title", style="purple", no_wrap=True)
table.add_column("Description", style="purple")
table.add_column("Project URL", style="purple", no_wrap=True)
for t in self.TOOLS:
desc = getattr(t, "DESCRIPTION", "") or ""
url = getattr(t, "PROJECT_URL", "") or ""
table.add_row(t.TITLE, desc.strip().replace("\n", " "), url)
panel = Panel(table, title="[purple]Available Tools[/purple]", border_style="purple")
console.print(panel)
def show_options(self, parent=None):
console.print("\n")
panel = Panel.fit("[bold magenta]Wifi Jamming Tools Collection[/bold magenta]\n"
"Select a tool to view details or run it.",
border_style="purple")
console.print(panel)
table = Table(title="[bold cyan]Available Tools[/bold cyan]", show_lines=True, expand=True)
table.add_column("Index", justify="center", style="bold yellow")
table.add_column("Tool Name", justify="left", style="bold green")
table.add_column("Description", justify="left", style="white")
for i, tool in enumerate(self.TOOLS):
title = getattr(tool, "TITLE", tool.__class__.__name__)
desc = getattr(tool, "DESCRIPTION", "—")
table.add_row(str(i + 1), title, desc or "—")
table.add_row("[red]99[/red]", "[bold red]Exit[/bold red]", "Return to previous menu")
console.print(table)
try:
choice = Prompt.ask("[bold cyan]Select a tool to view/run[/bold cyan]", default="99")
choice = int(choice)
if 1 <= choice <= len(self.TOOLS):
selected = self.TOOLS[choice - 1]
if hasattr(selected, "show_options"):
selected.show_options(parent=self)
elif hasattr(selected, "run"):
selected.run()
elif hasattr(selected, "show_info"):
selected.show_info()
else:
console.print("[bold yellow]Selected tool has no runnable interface.[/bold yellow]")
elif choice == 99:
return 99
except Exception:
console.print("[bold red]Invalid choice. Try again.[/bold red]")
return self.show_options(parent=parent)
if __name__ == "__main__":
tools = WifiJammingTools()
tools.pretty_print()
tools.show_options() | python | MIT | 7df27d8383095257e05c9dfd5af3ea696039d793 | 2026-01-04T14:39:20.027553Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/scripts/legacy_benchmark.py | scripts/legacy_benchmark.py | """
This module provides functionality to run benchmarks on different folders within
the 'benchmark' directory, wait for their completion, and generate a report.
"""
# list all folders in benchmark folder
# for each folder, run the benchmark
import contextlib
import json
import os
import subprocess
from datetime import datetime
from itertools import islice
from pathlib import Path
from typing import Iterable, Union
from tabulate import tabulate
from typer import run
def main(
n_benchmarks: Union[int, None] = None,
):
"""
Main function that runs benchmarks on folders within the 'benchmark' directory.
Parameters
----------
n_benchmarks : Union[int, None], optional
The number of benchmarks to run. If None, all benchmarks are run.
"""
path = Path("benchmark")
folders: Iterable[Path] = path.iterdir()
if n_benchmarks:
folders = islice(folders, n_benchmarks)
benchmarks = []
results = []
for bench_folder in folders:
if os.path.isdir(bench_folder):
print(f"Running benchmark for {bench_folder}")
log_path = bench_folder / "log.txt"
log_file = open(log_path, "w")
process = subprocess.Popen(
[
"python",
"-u", # Unbuffered output
"-m",
"gpt_engineer.cli.main",
bench_folder,
"--steps",
"benchmark",
],
stdout=log_file,
stderr=log_file,
bufsize=0,
)
benchmarks.append(bench_folder)
results.append((process, log_file))
print("You can stream the log file by running:")
print(f"tail -f {log_path}")
print()
for bench_folder, (process, file) in zip(benchmarks, results):
process.wait()
file.close()
print("process", bench_folder.name, "finished with code", process.returncode)
print("Running it. Original benchmark prompt:")
print()
with open(bench_folder / "prompt") as f:
print(f.read())
print()
with contextlib.suppress(KeyboardInterrupt):
subprocess.run(
[
"python",
"-m",
"gpt_engineer.cli.main",
bench_folder,
"--steps",
"evaluate",
],
)
generate_report(benchmarks, path)
def generate_report(benchmarks, benchmark_path):
"""
Generates a report of the benchmark results and optionally appends it to a markdown file.
Parameters
----------
benchmarks : list
A list of benchmark folder paths that have been processed.
benchmark_path : Path
The path to the benchmark directory.
"""
headers = ["Benchmark", "Ran", "Works", "Perfect", "Notes"]
rows = []
for bench_folder in benchmarks:
memory = bench_folder / ".gpteng" / "memory"
with open(memory / "review") as f:
review = json.loads(f.read())
rows.append(
[
bench_folder.name,
to_emoji(review.get("ran", None)),
to_emoji(review.get("works", None)),
to_emoji(review.get("perfect", None)),
review.get("comments", None),
]
)
table: str = tabulate(rows, headers, tablefmt="pipe")
print("\nBenchmark report:\n")
print(table)
print()
append_to_results = ask_yes_no("Append report to the results file?")
if append_to_results:
results_path = benchmark_path / "RESULTS.md"
current_date = datetime.now().strftime("%Y-%m-%d")
insert_markdown_section(results_path, current_date, table, 2)
def to_emoji(value: bool) -> str:
"""
Converts a boolean value to its corresponding emoji representation.
Parameters
----------
value : bool
The boolean value to convert.
Returns
-------
str
An emoji string representing the boolean value.
"""
return "\U00002705" if value else "\U0000274C"
def insert_markdown_section(file_path, section_title, section_text, level):
"""
Inserts a new section into a markdown file at the specified level.
Parameters
----------
file_path : Path
The path to the markdown file.
section_title : str
The title of the section to insert.
section_text : str
The text content of the section to insert.
level : int
The header level of the section.
"""
with open(file_path, "r") as file:
lines = file.readlines()
header_prefix = "#" * level
new_section = f"{header_prefix} {section_title}\n\n{section_text}\n\n"
# Find the first section with the specified level
line_number = -1
for i, line in enumerate(lines):
if line.startswith(header_prefix):
line_number = i
break
if line_number != -1:
lines.insert(line_number, new_section)
else:
print(
f"Markdown file was of unexpected format. No section of level {level} found. "
"Did not write results."
)
return
# Write the file
with open(file_path, "w") as file:
file.writelines(lines)
def ask_yes_no(question: str) -> bool:
"""
Asks a yes/no question and returns the response as a boolean value.
Parameters
----------
question : str
The yes/no question to ask.
Returns
-------
bool
True if the answer is 'yes', False if 'no'.
"""
while True:
response = input(question + " (y/n): ").lower().strip()
if response == "y":
return True
elif response == "n":
return False
else:
print("Please enter either 'y' or 'n'.")
if __name__ == "__main__":
run(main)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/scripts/test_api.py | scripts/test_api.py | """This is just a demo to test api.py."""
from time import sleep
import requests
def post_data(url, extra_arguments):
"""
Make an HTTP POST request with extra_arguments as data.
Parameters
----------
url : str
The URL to which the POST request should be sent.
extra_arguments : dict
A dictionary of data that needs to be sent in the POST request.
Returns
-------
response
The response from the server.
"""
response = requests.post(url, json=extra_arguments)
return response
if __name__ == "__main__":
URL_BASE = "http://127.0.0.1:8000"
arguments = {
"input": "We are writing snake in python. MVC components split \
in separate files. Keyboard control.", # our prompt
"additional_input": {"improve_option": False},
}
# create a task
response = post_data(f"{URL_BASE}/agent/tasks", arguments)
print(response.json())
task_id = response.json()["task_id"]
sleep(1) # this is not needed
# execute the step for our task
response = post_data(f"{URL_BASE}/agent/tasks/{task_id}/steps", {})
print(response.json())
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/scripts/clean_benchmarks.py | scripts/clean_benchmarks.py | """
This module provides functionality to clean up benchmark directories by removing
all files and folders except for 'prompt' and 'main_prompt'.
"""
# list all folders in benchmark folder
# for each folder, run the benchmark
import os
import shutil
from pathlib import Path
from typer import run
def main():
"""
Main function that iterates through all directories in the 'benchmark' folder
and cleans them by removing all files and directories except for 'prompt' and
'main_prompt'.
"""
benchmarks = Path("benchmark")
for benchmark in benchmarks.iterdir():
if benchmark.is_dir():
print(f"Cleaning {benchmark}")
for path in benchmark.iterdir():
if path.name in ["prompt", "main_prompt"]:
continue
# Get filename of Path object
if path.is_dir():
# delete the entire directory
shutil.rmtree(path)
else:
# delete the file
os.remove(path)
if __name__ == "__main__":
run(main)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/scripts/print_chat.py | scripts/print_chat.py | """
This module provides functionality to print a conversation with messages
colored according to the role of the speaker.
"""
import json
import typer
from termcolor import colored
app = typer.Typer()
def pretty_print_conversation(messages):
"""
Prints a conversation with messages formatted and colored by role.
Parameters
----------
messages : list
A list of message dictionaries, each containing 'role', 'name', and 'content' keys.
"""
role_to_color = {
"system": "red",
"user": "green",
"assistant": "blue",
"function": "magenta",
}
formatted_messages = []
for message in messages:
if message["role"] == "function":
formatted_messages.append(
f"function ({message['name']}): {message['content']}\n"
)
else:
assistant_content = (
message["function_call"]
if message.get("function_call")
else message["content"]
)
role_to_message = {
"system": f"system: {message['content']}\n",
"user": f"user: {message['content']}\n",
"assistant": f"assistant: {assistant_content}\n",
}
formatted_messages.append(role_to_message[message["role"]])
for formatted_message in formatted_messages:
role = messages[formatted_messages.index(formatted_message)]["role"]
color = role_to_color[role]
print(colored(formatted_message, color))
@app.command()
def main(
messages_path: str,
):
"""
Main function that loads messages from a JSON file and prints them using pretty formatting.
Parameters
----------
messages_path : str
The file path to the JSON file containing the messages.
"""
with open(messages_path) as f:
messages = json.load(f)
pretty_print_conversation(messages)
if __name__ == "__main__":
app()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/test_project_config.py | tests/test_project_config.py | import tempfile
import pytest
from gpt_engineer.core.project_config import (
Config,
_GptEngineerAppConfig,
_OpenApiConfig,
example_config,
filter_none,
)
def test_config_load():
# write example config to a file
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write(example_config)
# load the config from the file
config = Config.from_toml(f.name)
assert config.paths.base == "./frontend"
assert config.paths.src == "./src"
assert config.run.build == "npm run build"
assert config.run.test == "npm run test"
assert config.run.lint == "quick-lint-js"
assert config.gptengineer_app
assert config.gptengineer_app.project_id == "..."
assert config.gptengineer_app.openapi
assert (
config.gptengineer_app.openapi[0].url
== "https://api.gptengineer.app/openapi.json"
)
assert (
config.gptengineer_app.openapi[1].url
== "https://some-color-translating-api/openapi.json"
)
assert config.to_dict()
assert config.to_toml(f.name, save=False)
# check that write+read is idempotent
assert Config.from_toml(f.name) == config
def test_config_defaults():
config = Config()
assert config.paths.base is None
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
config.to_toml(f.name)
# check that read+write is idempotent
assert Config.from_toml(f.name) == config
# check that empty (default) config is written as empty string
toml_str = config.to_toml(f.name, save=False)
assert toml_str == ""
def test_config_from_dict():
d = {"gptengineer-app": {"project_id": "..."}} # minimal example
config = Config.from_dict(d)
assert config.gptengineer_app
assert config.gptengineer_app.project_id == "..."
config_dict = config.to_dict()
# check that the config dict matches the input dict exactly (no keys/defaults added)
assert config_dict == d
def test_config_from_dict_with_openapi():
# A good test because it has 3 levels of nesting
d = {
"gptengineer-app": {
"project_id": "...",
"openapi": [
{"url": "https://api.gptengineer.app/openapi.json"},
],
}
}
config = Config.from_dict(d)
assert config.gptengineer_app
assert config.gptengineer_app.project_id == "..."
assert config.gptengineer_app.openapi
assert (
config.gptengineer_app.openapi[0].url
== "https://api.gptengineer.app/openapi.json"
)
def test_config_load_partial():
# Loads a partial config, and checks that the rest is not set (i.e. None)
example_config = """
[gptengineer-app]
project_id = "..."
""".strip()
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write(example_config)
config = Config.from_toml(f.name)
assert config.gptengineer_app
assert config.gptengineer_app.project_id == "..."
assert config.to_dict()
toml_str = config.to_toml(f.name, save=False)
assert toml_str == example_config
# check that write+read is idempotent
assert Config.from_toml(f.name) == config
def test_config_update():
example_config = """
[gptengineer-app]
project_id = "..."
""".strip()
with tempfile.NamedTemporaryFile(mode="w", delete=False) as f:
f.write(example_config)
config = Config.from_toml(f.name)
config.gptengineer_app = _GptEngineerAppConfig(
project_id="...",
openapi=[_OpenApiConfig(url="https://api.gptengineer.app/openapi.json")],
)
config.to_toml(f.name)
assert Config.from_toml(f.name) == config
@pytest.mark.parametrize(
"input_dict,expected",
[
({"a": 1, "b": None}, {"a": 1}),
({"a": 1, "b": {"c": None, "d": 2}}, {"a": 1, "b": {"d": 2}}),
({"a": 1, "b": {}}, {"a": 1}),
({"a": 1, "b": {"c": None}}, {"a": 1}),
(
{"a": {"b": {"c": None}}, "d": {"e": {"f": 2}}, "g": None},
{"d": {"e": {"f": 2}}},
),
(
{"a": 1, "b": {"c": None, "d": {"e": None, "f": {}}}, "g": {"h": 2}},
{"a": 1, "g": {"h": 2}},
),
],
)
def test_filter_none(input_dict, expected):
assert filter_none(input_dict) == expected
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/test_install.py | tests/test_install.py | """
Tests for successful installation of the package.
"""
import shutil
import subprocess
import sys
import venv
from pathlib import Path
import pytest
# Define the directory for the virtual environment.
VENV_DIR = "./venv_test_installation"
@pytest.fixture(scope="module", autouse=True)
def venv_setup_teardown():
"""
A pytest fixture that sets up and tears down a virtual environment for testing.
This fixture is automatically used for all tests in this module.
The fixture:
- Creates a virtual environment.
- Installs Poetry in the virtual environment.
- Installs dependencies using Poetry.
- Cleans up by removing the virtual environment after tests are completed.
"""
try:
# Create a virtual environment with pip available.
venv.create(VENV_DIR, with_pip=True, clear=True)
# Install Poetry in the virtual environment.
subprocess.run(
[f"{VENV_DIR}/bin/python", "-m", "pip", "install", "poetry"], check=True
)
# Install the package and its dependencies using Poetry.
subprocess.run([f"{VENV_DIR}/bin/poetry", "install"], cwd=".", check=True)
# Provide the setup environment to the test functions.
yield
except Exception as e:
# Skip tests if the environment setup fails.
pytest.skip(f"Could not create venv or install dependencies: {str(e)}")
finally:
# Clean up by removing the virtual environment after tests.
shutil.rmtree(VENV_DIR)
def test_installation():
"""
Test to ensure that the package can be installed using Poetry in the virtual environment.
"""
# Determine the correct Poetry executable path based on the operating system.
poetry_executable = (
f"{VENV_DIR}/bin/poetry"
if sys.platform != "win32"
else f"{VENV_DIR}/Scripts/poetry.exe"
)
# Run Poetry install and capture its output.
result = subprocess.run([poetry_executable, "install"], capture_output=True)
# Assert that the installation was successful.
assert (
result.returncode == 0
), f"Install via poetry failed: {result.stderr.decode()}"
def test_cli_execution():
"""
Test to verify that the command-line interface (CLI) of the package works as expected.
This test assumes that the 'gpt-engineer' command is available and operational after installation.
"""
# Run the 'gpt-engineer' command with the '--help' option and capture its output.
result = subprocess.run(
args=["gpt-engineer", "--help"], capture_output=True, text=True
)
# Assert that the CLI command executed successfully.
assert (
result.returncode == 0
), f"gpt-engineer command failed with message: {result.stderr}"
@pytest.mark.requires_key
def test_installed_main_execution(tmp_path, monkeypatch):
# Ignore git installation check
monkeypatch.setattr("gpt_engineer.core.git.is_git_installed", lambda: False)
tmp_path = Path(tmp_path)
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text("make a program that prints the outcome of 4+4")
proc = subprocess.Popen(
["gpte", str(p)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
cwd=tmp_path,
)
inputs = "Y\nn"
output, _ = proc.communicate(inputs)
assert "8" in output
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/__init__.py | tests/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/mock_ai.py | tests/mock_ai.py | from typing import Any, List, Optional
class MockAI:
def __init__(self, response: List):
self.responses = iter(response)
def start(self, system: str, user: Any, *, step_name: str) -> List[str]:
return [next(self.responses)]
def next(
self, messages: List[str], prompt: Optional[str] = None, *, step_name: str
) -> List[str]:
return [next(self.responses)]
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/tools/example_snake_files.py | tests/tools/example_snake_files.py | PYTHON = """
import keyboard
import random
from dataclasses import dataclass
class View:
def __init__(self, game):
self.game = game
def render(self):
# Print the game state
for y in range(10):
for x in range(10):
if Point(x, y) in self.game.snake:
print('S', end='')
elif Point(x, y) == self.game.food:
print('F', end='')
else:
print('.', end='')
print()
print()
@dataclass
class Point:
x: int
y: int
class Game:
def __init__(self):
self.snake = [Point(5, 5)]
self.food = self.generate_food()
self.is_running = True
def generate_food(self):
return Point(random.randint(0, 10), random.randint(0, 10))
def update(self):
# Move the snake
self.snake.move()
# Check for collision with food
if self.snake.head == self.food:
self.snake.grow()
self.food = self.generate_food()
# Check for collision with boundaries
if not (0 <= self.snake.head.x < 10 and 0 <= self.snake.head.y < 10):
self.is_running = False
class Controller:
def __init__(self, game, view):
self.game = game
self.view = view
def handle_input(self):
if keyboard.is_pressed('up'):
self.game.move('up')
elif keyboard.is_pressed('down'):
self.game.move('down')
elif keyboard.is_pressed('left'):
self.game.move('left')
elif keyboard.is_pressed('right'):
self.game.move('right')
def main():
game = Game()
view = View(game)
controller = Controller(game, view)
while game.is_running:
controller.handle_input()
game.update()
view.render()
if __name__ == "__main__":
main()
"""
HTML = """
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Snake Game</h1>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<h2 id="score">Score: 0</h2>
<script src="script.js"></script>
</body>
</html>
"""
CSS = """
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000;
color: #fff;
font-family: Arial, sans-serif;
}
#gameCanvas {
border: 1px solid #fff;
}
h1, h2 {
text-align: center;
}
"""
JAVASCRIPT = """
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
var box = 20;
var score = 0;
var food = null;
var snake = [];
snake[0] = { x: 10 * box, y: 10 * box };
document.addEventListener('keydown', direction);
var d;
function direction(event) {
if (event.keyCode == 37 && d != "RIGHT") {
d = "LEFT";
} else if (event.keyCode == 38 && d != "DOWN") {
d = "UP";
} else if (event.keyCode == 39 && d != "LEFT") {
d = "RIGHT";
} else if (event.keyCode == 40 && d != "UP") {
d = "DOWN";
}
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < snake.length; i++) {
context.fillStyle = (i == 0) ? "green" : "white";
context.fillRect(snake[i].x, snake[i].y, box, box);
}
if (food == null) {
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
}
}
context.fillStyle = "red";
context.fillRect(food.x, food.y, box, box);
var snakeX = snake[0].x;
var snakeY = snake[0].y;
if (d == "LEFT") snakeX -= box;
if (d == "UP") snakeY -= box;
if (d == "RIGHT") snakeX += box;
if (d == "DOWN") snakeY += box;
if (snakeX == food.x && snakeY == food.y) {
score++;
food = null;
} else {
snake.pop();
}
var newHead = {
x: snakeX,
y: snakeY
}
if (snakeX < 0 || snakeY < 0 || snakeX > 19 * box || snakeY > 19 * box || collision(newHead, snake)) {
clearInterval(game);
}
snake.unshift(newHead);
document.getElementById('score').innerHTML = "Score: " + score;
}
function collision(head, array) {
for (var i = 0; i < array.length; i++) {
if (head.x == array[i].x && head.y == array[i].y) {
return true;
}
}
return false;
}
var game = setInterval(draw, 100);
"""
JAVA = """
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class SnakeGame extends JPanel implements ActionListener {
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private final int x[] = new int[ALL_DOTS];
private final int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
private Image ball;
private Image apple;
private Image head;
public SnakeGame() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("src/resources/dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("src/resources/apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("src/resources/head.png");
head = iih.getImage();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * 10;
y[z] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
private void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] >= B_HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= B_WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}
"""
C_SHARP = """
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SnakeGame
{
// Model
public class Game
{
public Snake Snake { get; set; }
public Point Food { get; set; }
public int Score { get; set; }
public bool Over { get; set; }
public Game()
{
Snake = new Snake();
Food = new Point();
Score = 0;
Over = false;
}
}
public class Snake
{
public Queue<Point> Body { get; set; }
public Direction Direction { get; set; }
public Snake()
{
Body = new Queue<Point>();
Direction = Direction.Right;
}
}
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
public enum Direction
{
Up,
Down,
Left,
Right
}
// View
public class GameView
{
public void Draw(Game game)
{
Console.Clear();
foreach (var point in game.Snake.Body)
{
Console.SetCursorPosition(point.X, point.Y);
Console.Write("O");
}
Console.SetCursorPosition(game.Food.X, game.Food.Y);
Console.Write("F");
Console.SetCursorPosition(0, 0);
Console.Write("Score: " + game.Score);
}
}
// Controller
public class GameController
{
private Game game;
private GameView view;
public GameController(Game game, GameView view)
{
this.game = game;
this.view = view;
}
public void Start()
{
while (!game.Over)
{
Thread.Sleep(100);
MoveSnake();
CheckCollision();
view.Draw(game);
}
}
private void MoveSnake()
{
var head = game.Snake.Body.Last();
var newHead = new Point { X = head.X, Y = head.Y };
switch (game.Snake.Direction)
{
case Direction.Up:
newHead.Y--;
break;
case Direction.Down:
newHead.Y++;
break;
case Direction.Left:
newHead.X--;
break;
case Direction.Right:
newHead.X++;
break;
}
game.Snake.Body.Enqueue(newHead);
if (newHead.X == game.Food.X && newHead.Y == game.Food.Y)
{
game.Score++;
game.Food = new Point { X = new Random().Next(1, 10), Y = new Random().Next(1, 10) };
}
else
{
game.Snake.Body.Dequeue();
}
}
private void CheckCollision()
{
var head = game.Snake.Body.Last();
if (head.X < 0 || head.Y < 0 || head.X >= 10 || head.Y >= 10)
{
game.Over = true;
}
if (game.Snake.Body.Take(game.Snake.Body.Count - 1).Any(p => p.X == head.X && p.Y == head.Y))
{
game.Over = true;
}
}
}
class Program
{
static void Main(string[] args)
{
var game = new Game();
var view = new GameView();
var controller = new GameController(game, view);
controller.Start();
}
}
}
"""
TYPESCRIPT = """
// Importing necessary modules
import { Application, Graphics, Keyboard } from 'pixi.js';
// Defining the Model class
class Model {
// The snake's body is represented as an array of points
body: Array<{x: number, y: number}>;
constructor() {
this.body = [{x: 0, y: 0}];
}
// Method to move the snake
move(direction: {x: number, y: number}) {
// Add a new head in the direction of movement
this.body.unshift({
x: this.body[0].x + direction.x,
y: this.body[0].y + direction.y
});
// Remove the tail
this.body.pop();
}
}
// Defining the View class
class View {
// The view needs a reference to the model and the PIXI application
model: Model;
app: Application;
graphics: Graphics;
constructor(model: Model, app: Application) {
this.model = model;
this.app = app;
this.graphics = new Graphics();
this.app.stage.addChild(this.graphics);
}
// Method to render the snake
render() {
// Clear the previous frame
this.graphics.clear();
// Draw each part of the snake's body
for (let part of this.model.body) {
this.graphics.beginFill(0xFFFFFF);
this.graphics.drawRect(part.x * 10, part.y * 10, 10, 10);
this.graphics.endFill();
}
}
}
// Defining the Controller class
class Controller {
// The controller needs a reference to the model and the view
model: Model;
view: View;
direction: {x: number, y: number};
constructor(model: Model, view: View) {
this.model = model;
this.view = view;
this.direction = {x: 1, y: 0};
// Set up keyboard controls
window.addEventListener('keydown', (e) => this.handleKeydown(e));
}
// Method to handle keyboard input
handleKeydown(event: KeyboardEvent) {
switch (event.key) {
case 'ArrowUp':
this.direction = {x: 0, y: -1};
break;
case 'ArrowDown':
this.direction = {x: 0, y: 1};
break;
case 'ArrowLeft':
this.direction = {x: -1, y: 0};
break;
case 'ArrowRight':
this.direction = {x: 1, y: 0};
break;
}
}
// Method to update the game state
update() {
this.model.move(this.direction);
this.view.render();
}
}
// Create the PIXI application
let app = new Application({width: 800, height: 600});
// Create the MVC components
let model = new Model();
let view = new View(model, app);
let controller = new Controller(model, view);
// Start the game loop
setInterval(() => controller.update(), 100);
"""
RUBY = """
require 'io/console'
# Model
class Game
attr_accessor :score, :snake, :food
def initialize
@score = 0
@snake = [[2, 2]]
@food = [6, 4]
end
def move(direction)
head = @snake.first.dup
case direction
when 'up'
head[0] -= 1
when 'down'
head[0] += 1
when 'left'
head[1] -= 1
when 'right'
head[1] += 1
end
@snake.unshift(head)
if @snake.first == @food
@score += 1
@food = [rand(1..8), rand(1..8)]
else
@snake.pop
end
end
def game_over?
head = @snake.first
@snake[1..-1].include?(head) || head[0] == 0 || head[1] == 0 || head[0] == 9 || head[1] == 9
end
end
# View
class View
def render(game)
system('clear')
puts "Score: #{game.score}"
(0..9).each do |i|
(0..9).each do |j|
if game.snake.include?([i, j])
print 'S'
elsif game.food == [i, j]
print 'F'
else
print '.'
end
end
puts
end
end
end
# Controller
class Controller
def initialize
@game = Game.new
@view = View.new
@direction = 'right'
end
def play
loop do
@view.render(@game)
break if @game.game_over?
input = IO.console.getch
case input
when 'w'
@direction = 'up'
when 's'
@direction = 'down'
when 'a'
@direction = 'left'
when 'd'
@direction = 'right'
end
@game.move(@direction)
end
puts "Game Over! Your score was #{@game.score}."
end
end
Controller.new.play
"""
PHP = """
<?php
// Model
class Snake {
public $body;
public $direction;
public function __construct() {
$this->body = array(array(2, 0), array(1, 0), array(0, 0));
$this->direction = 'right';
}
public function move() {
$head = current($this->body);
switch($this->direction) {
case 'right':
$this->body[] = array($head[0] + 1, $head[1]);
break;
case 'left':
$this->body[] = array($head[0] - 1, $head[1]);
break;
case 'up':
$this->body[] = array($head[0], $head[1] - 1);
break;
case 'down':
$this->body[] = array($head[0], $head[1] + 1);
break;
}
array_shift($this->body);
}
public function changeDirection($new_direction) {
$this->direction = $new_direction;
}
}
// View
class GameView {
public function render($snake) {
$output = '';
for ($y=0; $y<20; $y++) {
for ($x=0; $x<20; $x++) {
if (in_array(array($x, $y), $snake->body)) {
$output .= 'X';
} else {
$output .= ' ';
}
}
$output .= "\n";
}
echo $output;
}
}
// Controller
class GameController {
public $snake;
public $view;
public function __construct() {
$this->snake = new Snake();
$this->view = new GameView();
}
public function start() {
while (true) {
$this->view->render($this->snake);
$this->snake->move();
sleep(1);
}
}
public function changeDirection($new_direction) {
$this->snake->changeDirection($new_direction);
}
}
// Game loop
$game = new GameController();
$game->start();
?>
"""
SWIFT = """
import Foundation
import Cocoa
// MARK: - Model
struct Point {
var x: Int
var y: Int
}
class Snake {
var body: [Point]
var direction: Direction
init(startPoint: Point) {
body = [startPoint]
direction = .right
}
func move() {
let head = body.first!
var newHead = head
switch direction {
case .up:
newHead.y += 1
case .down:
newHead.y -= 1
case .left:
newHead.x -= 1
case .right:
newHead.x += 1
}
body.insert(newHead, at: 0)
body.removeLast()
}
func grow() {
let tail = body.last!
body.append(tail)
}
}
enum Direction {
case up
case down
case left
case right
}
// MARK: - View
class GameView {
func draw(snake: Snake) {
for point in snake.body {
print("O", terminator: "")
}
print("\n")
}
}
// MARK: - Controller
class GameController {
var snake: Snake
var view: GameView
init() {
snake = Snake(startPoint: Point(x: 0, y: 0))
view = GameView()
}
func start() {
while true {
snake.move()
view.draw(snake: snake)
sleep(1)
}
}
func handleKey(key: String) {
switch key {
case "w":
snake.direction = .up
case "s":
snake.direction = .down
case "a":
snake.direction = .left
case "d":
snake.direction = .right
default:
break
}
}
}
// MARK: - Main
let gameController = GameController()
gameController.start()
"""
GO = """
package main
import (
"fmt"
"os"
"os/exec"
"time"
"math/rand"
"bufio"
"syscall"
"unsafe"
)
// Model
type Point struct {
X int
Y int
}
type Snake struct {
Body []Point
Dir string
}
type Game struct {
Snake Snake
Food Point
Score int
Width int
Height int
}
// View
func (game *Game) Render() {
clearScreen()
for y := 0; y < game.Height; y++ {
for x := 0; x < game.Width; x++ {
point := Point{X: x, Y: y}
switch {
case point == game.Food:
fmt.Print("F")
case game.Snake.Contains(point):
fmt.Print("S")
default:
fmt.Print(" ")
}
}
fmt.Println()
}
fmt.Println("Score:", game.Score)
}
// Controller
func (game *Game) Update() {
head := game.Snake.Body[0]
switch game.Snake.Dir {
case "up":
head.Y--
case "down":
head.Y++
case "left":
head.X--
case "right":
head.X++
}
if head.X < 0 || head.Y < 0 || head.X >= game.Width || head.Y >= game.Height {
game.Score = -1
return
}
if game.Snake.Contains(head) {
game.Score = -1
return
}
if head == game.Food {
game.Score++
game.Food = Point{rand.Intn(game.Width), rand.Intn(game.Height)}
} else {
game.Snake.Body = game.Snake.Body[:len(game.Snake.Body)-1]
}
game.Snake.Body = append([]Point{head}, game.Snake.Body...)
}
func (snake *Snake) Contains(point Point) bool {
for _, bodyPoint := range snake.Body {
if bodyPoint == point {
return true
}
}
return false
}
func clearScreen() {
cmd := exec.Command("clear")
cmd.Stdout = os.Stdout
cmd.Run()
}
func main() {
game := &Game{
Snake: Snake{
Body: []Point{{10, 10}},
Dir: "right",
},
Food: Point{15, 15},
Score: 0,
Width: 20,
Height: 20,
}
go func() {
reader := bufio.NewReader(os.Stdin)
for {
char, _, err := reader.ReadRune()
if err != nil {
panic(err)
}
switch char {
case 'w':
game.Snake.Dir = "up"
case 's':
game.Snake.Dir = "down"
case 'a':
game.Snake.Dir = "left"
case 'd':
game.Snake.Dir = "right"
}
}
}()
for game.Score >= 0 {
game.Render()
time.Sleep(time.Second / 5)
game.Update()
}
}
"""
KOTLIN = """
import java.awt.Color
import java.awt.Dimension
import java.awt.Font
import java.awt.FontMetrics
import java.awt.Graphics
import java.awt.Image
import java.awt.Toolkit
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.ImageIcon
import javax.swing.JPanel
import javax.swing.Timer
class Board : JPanel(), ActionListener {
private val B_WIDTH = 300
private val B_HEIGHT = 300
private val DOT_SIZE = 10
private val ALL_DOTS = 900
private val RAND_POS = 29
private val DELAY = 140
private val x = IntArray(ALL_DOTS)
private val y = IntArray(ALL_DOTS)
private var dots: Int = 0
private var apple_x: Int = 0
private var apple_y: Int = 0
private var leftDirection = false
private var rightDirection = true
private var upDirection = false
private var downDirection = false
private var inGame = true
private lateinit var timer: Timer
private lateinit var apple: Image
private lateinit var dot: Image
private lateinit var head: Image
init {
initBoard()
}
private fun initBoard() {
addKeyListener(TAdapter())
background = Color.black
isFocusable = true
preferredSize = Dimension(B_WIDTH, B_HEIGHT)
loadImages()
initGame()
}
private fun loadImages() {
val iid = ImageIcon("src/resources/apple.png")
apple = iid.image
val iid2 = ImageIcon("src/resources/dot.png")
dot = iid2.image
val iid3 = ImageIcon("src/resources/head.png")
head = iid3.image
}
private fun initGame() {
dots = 3
for (z in 0 until dots) {
x[z] = 50 - z * 10
y[z] = 50
}
locateApple()
timer = Timer(DELAY, this)
timer.start()
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
doDrawing(g)
}
private fun doDrawing(g: Graphics) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this)
for (z in 0 until dots) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this)
} else {
g.drawImage(dot, x[z], y[z], this)
}
}
Toolkit.getDefaultToolkit().sync()
} else {
gameOver(g)
}
}
private fun gameOver(g: Graphics) {
val msg = "Game Over"
val font = Font("Helvetica", Font.BOLD, 14)
val metrics: FontMetrics = this.getFontMetrics(font)
g.color = Color.white
g.font = font
g.drawString(msg, (B_WIDTH - metrics.stringWidth(msg)) / 2, B_HEIGHT / 2)
}
private fun checkApple() {
if (x[0] == apple_x && y[0] == apple_y) {
dots++
locateApple()
}
}
private fun move() {
for (z in dots downTo 1) {
x[z] = x[z - 1]
y[z] = y[z - 1]
}
if (leftDirection) {
x[0] -= DOT_SIZE
}
if (rightDirection) {
x[0] += DOT_SIZE
}
if (upDirection) {
y[0] -= DOT_SIZE
}
if (downDirection) {
y[0] += DOT_SIZE
}
}
private fun checkCollision() {
for (z in dots downTo 1) {
if (z > 4 && x[0] == x[z] && y[0] == y[z]) {
inGame = false
}
}
if (y[0] >= B_HEIGHT) {
inGame = false
}
if (y[0] < 0) {
inGame = false
}
if (x[0] >= B_WIDTH) {
inGame = false
}
if (x[0] < 0) {
inGame = false
}
if (!inGame) {
timer.stop()
}
}
private fun locateApple() {
val r = (Math.random() * RAND_POS).toInt()
apple_x = r * DOT_SIZE
r = (Math.random() * RAND_POS).toInt()
apple_y = r * DOT_SIZE
}
override fun actionPerformed(e: ActionEvent) {
if (inGame) {
checkApple()
checkCollision()
move()
}
repaint()
}
private inner class TAdapter : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
val key = e.keyCode
if (key == KeyEvent.VK_LEFT && !rightDirection) {
leftDirection = true
upDirection = false
downDirection = false
}
if (key == KeyEvent.VK_RIGHT && !leftDirection) {
rightDirection = true
upDirection = false
downDirection = false
}
if (key == KeyEvent.VK_UP && !downDirection) {
upDirection = true
rightDirection = false
leftDirection = false
}
if (key == KeyEvent.VK_DOWN && !upDirection) {
downDirection = true
rightDirection = false
leftDirection = false
}
}
}
}
"""
RUST = """
extern crate termion;
use std::io;
use std::io::stdout;
use std::io::Write;
use std::thread;
use std::time::Duration;
use termion::raw::IntoRawMode;
use termion::input::TermRead;
use termion::event::Key;
// Define the size of the game board
const BOARD_SIZE: usize = 10;
// Define the game state
struct GameState {
snake: Snake,
food: Food,
}
// Define the snake
struct Snake {
body: Vec<(usize, usize)>,
direction: Direction,
}
// Define the food
struct Food {
position: (usize, usize),
}
// Define the possible directions the snake can move
enum Direction {
Up,
Down,
Left,
Right,
}
// Implement the game state
impl GameState {
fn new() -> GameState {
GameState {
snake: Snake::new(),
food: Food::new(),
}
}
// Update the game state
fn update(&mut self) {
self.snake.move();
if self.snake.eats(&self.food) {
self.food = Food::new();
}
}
}
// Implement the snake
impl Snake {
fn new() -> Snake {
Snake {
body: vec![(BOARD_SIZE / 2, BOARD_SIZE / 2)],
direction: Direction::Right,
}
}
// Move the snake in the current direction
fn move(&mut self) {
let (head_x, head_y) = self.body[0];
match self.direction {
Direction::Up => self.body.insert(0, (head_x, head_y - 1)),
Direction::Down => self.body.insert(0, (head_x, head_y + 1)),
Direction::Left => self.body.insert(0, (head_x - 1, head_y)),
Direction::Right => self.body.insert(0, (head_x + 1, head_y)),
}
self.body.pop();
}
// Check if the snake eats the food
fn eats(&self, food: &Food) -> bool {
self.body[0] == food.position
}
}
// Implement the food
impl Food {
fn new() -> Food {
Food {
position: (rand::random::<usize>() % BOARD_SIZE, rand::random::<usize>() % BOARD_SIZE),
}
}
}
// Implement the view
fn render(game_state: &GameState) {
for y in 0..BOARD_SIZE {
for x in 0..BOARD_SIZE {
if game_state.snake.body.contains(&(x, y)) {
print!("S");
} else if game_state.food.position == (x, y) {
print!("F");
} else {
print!(" ");
}
}
println!();
}
}
// Implement the controller
fn controller(game_state: &mut GameState) {
let stdin = io::stdin();
for c in stdin.keys() {
match c.unwrap() {
Key::Char('q') => break,
Key::Up => game_state.snake.direction = Direction::Up,
Key::Down => game_state.snake.direction = Direction::Down,
Key::Left => game_state.snake.direction = Direction::Left,
Key::Right => game_state.snake.direction = Direction::Right,
_ => {}
}
}
}
fn main() {
let mut game_state = GameState::new();
let mut stdout = stdout().into_raw_mode().unwrap();
loop {
write!(stdout, "{}", termion::clear::All).unwrap();
render(&game_state);
stdout.flush().unwrap();
game_state.update();
thread::sleep(Duration::from_millis(1000));
}
}
"""
C_PLUS_PLUS = """
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool gameOver;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirecton { STOP = 0, LEFT, RIGHT, UP, DOWN};
eDirecton dir;
void Setup()
{
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw()
{
system("cls");
for (int i = 0; i < width+2; i++)
cout << "#";
cout << endl;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | true |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/benchmark/test_BenchConfig.py | tests/benchmark/test_BenchConfig.py | # Generated by CodiumAI
import pytest
from gpt_engineer.benchmark.bench_config import (
AppsConfig,
BenchConfig,
GptmeConfig,
MbppConfig,
)
class TestBenchConfig:
# Creating a BenchConfig object with default values should return an instance of BenchConfig with all attributes set to their default values.
def test_default_values(self):
config = BenchConfig()
assert isinstance(config.apps, AppsConfig)
assert isinstance(config.mbpp, MbppConfig)
assert isinstance(config.gptme, GptmeConfig)
assert config.apps.active is True
assert config.apps.test_start_index == 0
assert config.apps.test_end_index == 1
assert config.apps.train_start_index == 0
assert config.apps.train_end_index == 0
assert config.mbpp.active is True
assert config.mbpp.test_len == 1
assert config.mbpp.train_len == 0
assert config.gptme.active is True
# Creating a BenchConfig object with specific values should return an instance of BenchConfig with the specified attributes set to the specified values.
def test_specific_values(self):
config = BenchConfig(
apps=AppsConfig(
active=False,
test_start_index=1,
test_end_index=2,
train_start_index=3,
train_end_index=4,
),
mbpp=MbppConfig(active=False, test_len=5, train_len=6),
gptme=GptmeConfig(active=False),
)
assert isinstance(config.apps, AppsConfig)
assert isinstance(config.mbpp, MbppConfig)
assert isinstance(config.gptme, GptmeConfig)
assert config.apps.active is False
assert config.apps.test_start_index == 1
assert config.apps.test_end_index == 2
assert config.apps.train_start_index == 3
assert config.apps.train_end_index == 4
assert config.mbpp.active is False
assert config.mbpp.test_len == 5
assert config.mbpp.train_len == 6
assert config.gptme.active is False
# Calling the from_dict method with a valid dictionary should return an instance of BenchConfig with attributes set according to the values in the dictionary.
def test_from_dict_valid_dict(self):
config_dict = {
"apps": {
"active": False,
"test_start_index": 1,
"test_end_index": 2,
"train_start_index": 3,
"train_end_index": 4,
},
"mbpp": {"active": False, "test_len": 5, "train_len": 6},
"gptme": {"active": False},
}
config = BenchConfig.from_dict(config_dict)
assert isinstance(config.apps, AppsConfig)
assert isinstance(config.mbpp, MbppConfig)
assert isinstance(config.gptme, GptmeConfig)
assert config.apps.active is False
assert config.apps.test_start_index == 1
assert config.apps.test_end_index == 2
assert config.apps.train_start_index == 3
assert config.apps.train_end_index == 4
assert config.mbpp.active is False
assert config.mbpp.test_len == 5
assert config.mbpp.train_len == 6
assert config.gptme.active is False
# Calling the from_toml method with an invalid path to a TOML file should raise an appropriate exception.
def test_from_toml_invalid_path(self):
config_file = "invalid_config.toml"
with pytest.raises(Exception):
BenchConfig.from_toml(config_file)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/__init__.py | tests/applications/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/cli/test_main.py | tests/applications/cli/test_main.py | import dataclasses
import functools
import inspect
import os
import shutil
import tempfile
from argparse import Namespace
from unittest.mock import patch
import pytest
import typer
import gpt_engineer.applications.cli.main as main
from gpt_engineer.applications.cli.main import load_prompt
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.prompt import Prompt
@functools.wraps(dataclasses.make_dataclass)
def dcommand(typer_f, **kwargs):
required = True
def field_desc(name, param):
nonlocal required
t = param.annotation or "typing.Any"
if param.default.default is not ...:
required = False
return name, t, dataclasses.field(default=param.default.default)
if not required:
raise ValueError("Required value after optional")
return name, t
kwargs.setdefault("cls_name", typer_f.__name__)
params = inspect.signature(typer_f).parameters
kwargs["fields"] = [field_desc(k, v) for k, v in params.items()]
@functools.wraps(typer_f)
def dcommand_decorator(function_or_class):
assert callable(function_or_class)
ka = dict(kwargs)
ns = Namespace(**(ka.pop("namespace", None) or {}))
if isinstance(function_or_class, type):
ka["bases"] = *ka.get("bases", ()), function_or_class
else:
ns.__call__ = function_or_class
ka["namespace"] = vars(ns)
return dataclasses.make_dataclass(**ka)
return dcommand_decorator
@dcommand(main.main)
class DefaultArgumentsMain:
def __call__(self):
attribute_dict = vars(self)
main.main(**attribute_dict)
def input_generator():
yield "y" # First response
while True:
yield "n" # Subsequent responses
prompt_text = "Make a python program that writes 'hello' to a file called 'output.txt'"
class TestMain:
# Runs gpt-engineer cli interface for many parameter configurations, BUT DOES NOT CODEGEN! Only testing cli.
def test_default_settings_generate_project(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(str(p), llm_via_clipboard=True, no_execution=True)
args()
# Runs gpt-engineer with improve mode and improves an existing project in the specified path.
def test_improve_existing_project(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p), improve_mode=True, llm_via_clipboard=True, no_execution=True
)
args()
# Runs gpt-engineer with improve mode and improves an existing project in the specified path, with skip_file_selection
def test_improve_existing_project_skip_file_selection(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p),
improve_mode=True,
llm_via_clipboard=True,
no_execution=True,
skip_file_selection=True,
)
args()
assert args.skip_file_selection, "Skip_file_selection not set"
# Runs gpt-engineer with improve mode and improves an existing project in the specified path, with skip_file_selection
def test_improve_existing_project_diff_timeout(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p),
improve_mode=True,
llm_via_clipboard=True,
no_execution=True,
diff_timeout=99,
)
args()
assert args.diff_timeout == 99, "Diff timeout not set"
# def improve_generator():
# yield "y"
# while True:
# yield "n" # Subsequent responses
#
# gen = improve_generator()
# monkeypatch.setattr("builtins.input", lambda _: next(gen))
# p = tmp_path / "projects/example"
# p.mkdir(parents=True)
# (p / "prompt").write_text(prompt_text)
# (p / "main.py").write_text("The program will be written in this file")
# meta_p = p / META_DATA_REL_PATH
# meta_p.mkdir(parents=True)
# (meta_p / "file_selection.toml").write_text(
# """
# [files]
# "main.py" = "selected"
# """
# )
# os.environ["GPTE_TEST_MODE"] = "True"
# simplified_main(str(p), "improve")
# DiskExecutionEnv(path=p)
# del os.environ["GPTE_TEST_MODE"]
# Runs gpt-engineer with lite mode and generates a project with only the main prompt.
def test_lite_mode_generate_project(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p), lite_mode=True, llm_via_clipboard=True, no_execution=True
)
args()
# Runs gpt-engineer with clarify mode and generates a project after discussing the specification with the AI.
def test_clarify_mode_generate_project(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p), clarify_mode=True, llm_via_clipboard=True, no_execution=True
)
args()
# Runs gpt-engineer with self-heal mode and generates a project after discussing the specification with the AI and self-healing the code.
def test_self_heal_mode_generate_project(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p), self_heal_mode=True, llm_via_clipboard=True, no_execution=True
)
args()
def test_clarify_lite_improve_mode_generate_project(self, tmp_path, monkeypatch):
p = tmp_path / "projects/example"
p.mkdir(parents=True)
(p / "prompt").write_text(prompt_text)
args = DefaultArgumentsMain(
str(p),
improve_mode=True,
lite_mode=True,
clarify_mode=True,
llm_via_clipboard=True,
no_execution=True,
)
pytest.raises(typer.Exit, args)
# Tests the creation of a log file in improve mode.
class TestLoadPrompt:
# Load prompt from existing file in input_repo
def test_load_prompt_existing_file(self):
with tempfile.TemporaryDirectory() as tmp_dir:
input_repo = DiskMemory(tmp_dir)
prompt_file = "prompt.txt"
prompt_content = "This is the prompt"
input_repo[prompt_file] = prompt_content
improve_mode = False
image_directory = ""
result = load_prompt(input_repo, improve_mode, prompt_file, image_directory)
assert isinstance(result, Prompt)
assert result.text == prompt_content
assert result.image_urls is None
# Prompt file does not exist in input_repo, and improve_mode is False
def test_load_prompt_no_file_improve_mode_false(self):
with tempfile.TemporaryDirectory() as tmp_dir:
input_repo = DiskMemory(tmp_dir)
prompt_file = "prompt.txt"
improve_mode = False
image_directory = ""
with patch(
"builtins.input",
return_value="What application do you want gpt-engineer to generate?",
):
result = load_prompt(
input_repo, improve_mode, prompt_file, image_directory
)
assert isinstance(result, Prompt)
assert (
result.text == "What application do you want gpt-engineer to generate?"
)
assert result.image_urls is None
# Prompt file is a directory
def test_load_prompt_directory_file(self):
with tempfile.TemporaryDirectory() as tmp_dir:
input_repo = DiskMemory(tmp_dir)
prompt_file = os.path.join(tmp_dir, "prompt")
os.makedirs(os.path.join(tmp_dir, prompt_file))
improve_mode = False
image_directory = ""
with pytest.raises(ValueError):
load_prompt(input_repo, improve_mode, prompt_file, image_directory)
# Prompt file is empty
def test_load_prompt_empty_file(self):
with tempfile.TemporaryDirectory() as tmp_dir:
input_repo = DiskMemory(tmp_dir)
prompt_file = "prompt.txt"
input_repo[prompt_file] = ""
improve_mode = False
image_directory = ""
with patch(
"builtins.input",
return_value="What application do you want gpt-engineer to generate?",
):
result = load_prompt(
input_repo, improve_mode, prompt_file, image_directory
)
assert isinstance(result, Prompt)
assert (
result.text == "What application do you want gpt-engineer to generate?"
)
assert result.image_urls is None
# image_directory does not exist in input_repo
def test_load_prompt_no_image_directory(self):
with tempfile.TemporaryDirectory() as tmp_dir:
input_repo = DiskMemory(tmp_dir)
prompt_file = "prompt.txt"
prompt_content = "This is the prompt"
input_repo[prompt_file] = prompt_content
improve_mode = False
image_directory = "tests/test_data"
shutil.copytree(image_directory, os.path.join(tmp_dir, image_directory))
result = load_prompt(input_repo, improve_mode, prompt_file, image_directory)
assert isinstance(result, Prompt)
assert result.text == prompt_content
assert "mona_lisa.jpg" in result.image_urls
# def test_log_creation_in_improve_mode(self, tmp_path, monkeypatch):
# def improve_generator():
# yield "y"
# while True:
# yield "n" # Subsequent responses
#
# gen = improve_generator()
# monkeypatch.setattr("builtins.input", lambda _: next(gen))
# p = tmp_path / "projects/example"
# p.mkdir(parents=True)
# (p / "prompt").write_text(prompt_text)
# (p / "main.py").write_text("The program will be written in this file")
# meta_p = p / META_DATA_REL_PATH
# meta_p.mkdir(parents=True)
# (meta_p / "file_selection.toml").write_text(
# """
# [files]
# "main.py" = "selected"
# """
# )
# os.environ["GPTE_TEST_MODE"] = "True"
# simplified_main(str(p), "improve")
# DiskExecutionEnv(path=p)
# assert (
# (p / f".gpteng/memory/{DEBUG_LOG_FILE}").read_text().strip()
# == """UPLOADED FILES:
# ```
# File: main.py
# 1 The program will be written in this file
#
# ```
# PROMPT:
# Make a python program that writes 'hello' to a file called 'output.txt'
# CONSOLE OUTPUT:"""
# )
# del os.environ["GPTE_TEST_MODE"]
#
# def test_log_creation_in_improve_mode_with_failing_diff(
# self, tmp_path, monkeypatch
# ):
# def improve_generator():
# yield "y"
# while True:
# yield "n" # Subsequent responses
#
# def mock_salvage_correct_hunks(
# messages: List, files_dict: FilesDict, error_message: List
# ) -> FilesDict:
# # create a falling diff
# messages[
# -1
# ].content = """To create a Python program that writes 'hello' to a file called 'output.txt', we will need to perform the following steps:
#
# 1. Open the file 'output.txt' in write mode.
# 2. Write the string 'hello' to the file.
# 3. Close the file to ensure the data is written and the file is not left open.
#
# Here is the implementation of the program in the `main.py` file:
#
# ```diff
# --- main.py
# +++ main.py
# @@ -0,0 +1,9 @@
# -create falling diff
# ```
#
# This concludes a fully working implementation."""
# # Call the original function with modified messages or define your own logic
# return salvage_correct_hunks(messages, files_dict, error_message)
#
# gen = improve_generator()
# monkeypatch.setattr("builtins.input", lambda _: next(gen))
# monkeypatch.setattr(
# "gpt_engineer.core.default.steps.salvage_correct_hunks",
# mock_salvage_correct_hunks,
# )
# p = tmp_path / "projects/example"
# p.mkdir(parents=True)
# (p / "prompt").write_text(prompt_text)
# (p / "main.py").write_text("The program will be written in this file")
# meta_p = p / META_DATA_REL_PATH
# meta_p.mkdir(parents=True)
# (meta_p / "file_selection.toml").write_text(
# """
# [files]
# "main.py" = "selected"
# """
# )
# os.environ["GPTE_TEST_MODE"] = "True"
# simplified_main(str(p), "improve")
# DiskExecutionEnv(path=p)
# assert (
# (p / f".gpteng/memory/{DEBUG_LOG_FILE}").read_text().strip()
# == """UPLOADED FILES:
# ```
# File: main.py
# 1 The program will be written in this file
#
# ```
# PROMPT:
# Make a python program that writes 'hello' to a file called 'output.txt'
# CONSOLE OUTPUT:
# Invalid hunk: @@ -0,0 +1,9 @@
# -create falling diff
#
# Invalid hunk: @@ -0,0 +1,9 @@
# -create falling diff"""
# )
# del os.environ["GPTE_TEST_MODE"]
#
# def test_log_creation_in_improve_mode_with_unexpected_exceptions(
# self, tmp_path, monkeypatch
# ):
# def improve_generator():
# yield "y"
# while True:
# yield "n" # Subsequent responses
#
# def mock_salvage_correct_hunks(
# messages: List, files_dict: FilesDict, error_message: List
# ) -> FilesDict:
# raise Exception("Mock exception in salvage_correct_hunks")
#
# gen = improve_generator()
# monkeypatch.setattr("builtins.input", lambda _: next(gen))
# monkeypatch.setattr(
# "gpt_engineer.core.default.steps.salvage_correct_hunks",
# mock_salvage_correct_hunks,
# )
# p = tmp_path / "projects/example"
# p.mkdir(parents=True)
# (p / "prompt").write_text(prompt_text)
# (p / "main.py").write_text("The program will be written in this file")
# meta_p = p / META_DATA_REL_PATH
# meta_p.mkdir(parents=True)
# (meta_p / "file_selection.toml").write_text(
# """
# [files]
# "main.py" = "selected"
# """
# )
# os.environ["GPTE_TEST_MODE"] = "True"
# simplified_main(str(p), "improve")
# DiskExecutionEnv(path=p)
# assert (
# (p / f".gpteng/memory/{DEBUG_LOG_FILE}").read_text().strip()
# == """UPLOADED FILES:
# ```
# File: main.py
# 1 The program will be written in this file
#
# ```
# PROMPT:
# Make a python program that writes 'hello' to a file called 'output.txt'
# CONSOLE OUTPUT:
# Error while improving the project: Mock exception in salvage_correct_hunks"""
# )
# del os.environ["GPTE_TEST_MODE"]
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/cli/test_learning.py | tests/applications/cli/test_learning.py | from unittest import mock
from gpt_engineer.applications.cli import learning
from gpt_engineer.applications.cli.learning import Learning
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.prompt import Prompt
def test_human_review_input_no_concent_returns_none():
with mock.patch.object(learning, "check_collection_consent", return_value=False):
result = learning.human_review_input()
assert result is None
def test_human_review_input_consent_code_ran_no_comments():
with (
mock.patch.object(learning, "check_collection_consent", return_value=True),
mock.patch("builtins.input", return_value="y"),
):
result = learning.human_review_input()
assert result.raw == "y, y, "
assert result.ran is True
assert result.works is None
assert result.comments == ""
def test_human_review_input_consent_code_ran_not_perfect_but_useful_no_comments():
with (
mock.patch.object(learning, "check_collection_consent", return_value=True),
mock.patch("builtins.input", side_effect=["y", "n", "y", ""]),
):
result = learning.human_review_input()
assert result.raw == "y, n, y"
assert result.ran is True
assert result.works is True
assert result.comments == ""
def test_check_collection_consent_yes():
gpte_consent_mock = mock.Mock()
gpte_consent_mock.exists.return_value = True
gpte_consent_mock.read_text.return_value = "true"
with mock.patch.object(learning, "Path", return_value=gpte_consent_mock):
result = learning.check_collection_consent()
assert result is True
def test_check_collection_consent_no_ask_collection_consent():
with mock.patch.object(learning, "Path") as gpte_consent_mock:
gpte_consent_mock.exists.return_value = True
gpte_consent_mock.read_text.return_value = "false"
with mock.patch.object(learning, "ask_collection_consent", return_value=True):
result = learning.check_collection_consent()
assert result is True
def test_ask_collection_consent_yes():
with mock.patch("builtins.input", return_value="y"):
result = learning.ask_collection_consent()
assert result is True
def test_ask_collection_consent_no():
with mock.patch("builtins.input", return_value="n"):
result = learning.ask_collection_consent()
assert result is False
def test_extract_learning():
review = learning.Review(
raw="y, n, y",
ran=True,
works=True,
perfect=False,
comments="The code is not perfect",
)
memory = mock.Mock(spec=DiskMemory)
memory.to_json.return_value = {"prompt": "prompt"}
result = learning.extract_learning(
Prompt("prompt"),
"model_name",
0.01,
("prompt_tokens", "completion_tokens"),
memory,
review,
)
assert isinstance(result, Learning)
def test_get_session():
with mock.patch.object(learning, "Path") as path_mock:
# can be better tested with pyfakefs.
path_mock.return_value.__truediv__.return_value.exists.return_value = False
with mock.patch.object(learning, "random") as random_mock:
random_mock.randint.return_value = 42
result = learning.get_session()
assert result == "42"
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/cli/test_collect.py | tests/applications/cli/test_collect.py | """
Tests the collect_learnings function in the cli/collect module.
"""
import pytest
# def test_collect_learnings(monkeypatch):
# monkeypatch.setattr(rudder_analytics, "track", MagicMock())
#
# model = "test_model"
# temperature = 0.5
# steps = [simple_gen]
# dbs = FileRepositories(
# OnDiskRepository("/tmp"),
# OnDiskRepository("/tmp"),
# OnDiskRepository("/tmp"),
# OnDiskRepository("/tmp"),
# OnDiskRepository("/tmp"),
# OnDiskRepository("/tmp"),
# OnDiskRepository("/tmp"),
# )
# dbs.input = {
# "prompt": "test prompt\n with newlines",
# "feedback": "test feedback",
# }
# code = "this is output\n\nit contains code"
# dbs.logs = {steps[0].__name__: json.dumps([{"role": "system", "content": code}])}
# dbs.memory = {"all_output.txt": "test workspace\n" + code}
#
# collect_learnings(model, temperature, steps, dbs)
#
# learnings = extract_learning(
# model, temperature, steps, dbs, steps_file_hash=steps_file_hash()
# )
# assert rudder_analytics.track.call_count == 1
# assert rudder_analytics.track.call_args[1]["event"] == "learning"
# a = {
# k: v
# for k, v in rudder_analytics.track.call_args[1]["properties"].items()
# if k != "timestamp"
# }
# b = {k: v for k, v in learnings.to_dict().items() if k != "timestamp"}
# assert a == b
#
# assert json.dumps(code) in learnings.logs
# assert code in learnings.workspace
if __name__ == "__main__":
pytest.main(["-v"])
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/cli/__init__.py | tests/applications/cli/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/cli/test_cli_agent.py | tests/applications/cli/test_cli_agent.py | import os
import tempfile
import pytest
from langchain.schema import AIMessage
from gpt_engineer.applications.cli.cli_agent import CliAgent
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.default.disk_memory import DiskMemory
# from gpt_engineer.core.default.git_version_manager import GitVersionManager
from gpt_engineer.core.default.paths import ENTRYPOINT_FILE, memory_path
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
from gpt_engineer.tools.custom_steps import clarified_gen, lite_gen
from tests.mock_ai import MockAI
def test_init_standard_config(monkeypatch):
monkeypatch.setattr("builtins.input", lambda _: "y")
temp_dir = tempfile.mkdtemp()
memory = DiskMemory(memory_path(temp_dir))
execution_env = DiskExecutionEnv()
mock_ai = MockAI(
[
AIMessage(
"hello_world.py\n```\nwith open('output.txt', 'w') as file:\n file.write('Hello World!')\n```"
),
AIMessage("```run.sh\npython3 hello_world.py\n```"),
],
)
cli_agent = CliAgent.with_default_config(memory, execution_env, ai=mock_ai)
outfile = "output.txt"
os.path.join(temp_dir, outfile)
code = cli_agent.init(
Prompt(
f"Make a program that prints 'Hello World!' to a file called '{outfile}'"
)
)
env = DiskExecutionEnv()
env.upload(code).run(f"bash {ENTRYPOINT_FILE}")
code = env.download()
assert outfile in code
assert code[outfile] == "Hello World!"
def test_init_lite_config(monkeypatch):
monkeypatch.setattr("builtins.input", lambda _: "y")
temp_dir = tempfile.mkdtemp()
memory = DiskMemory(memory_path(temp_dir))
# version_manager = GitVersionManager(temp_dir)
execution_env = DiskExecutionEnv()
mock_ai = MockAI(
[
AIMessage(
"hello_world.py\n```\nwith open('output.txt', 'w') as file:\n file.write('Hello World!')\n```"
),
AIMessage("```run.sh\npython3 hello_world.py\n```"),
],
)
cli_agent = CliAgent.with_default_config(
memory, execution_env, ai=mock_ai, code_gen_fn=lite_gen
)
outfile = "output.txt"
os.path.join(temp_dir, outfile)
code = cli_agent.init(
Prompt(
f"Make a program that prints 'Hello World!' to a file called '{outfile}'"
)
)
env = DiskExecutionEnv()
env.upload(code).run(f"bash {ENTRYPOINT_FILE}")
code = env.download()
assert outfile in code
assert code[outfile].strip() == "Hello World!"
def test_init_clarified_gen_config(monkeypatch):
monkeypatch.setattr("builtins.input", lambda _: "y")
temp_dir = tempfile.mkdtemp()
memory = DiskMemory(memory_path(temp_dir))
execution_env = DiskExecutionEnv()
mock_ai = MockAI(
[
AIMessage("nothing to clarify"),
AIMessage(
"hello_world.py\n```\nwith open('output.txt', 'w') as file:\n file.write('Hello World!')\n```"
),
AIMessage("```run.sh\npython3 hello_world.py\n```"),
],
)
cli_agent = CliAgent.with_default_config(
memory, execution_env, ai=mock_ai, code_gen_fn=clarified_gen
)
outfile = "output.txt"
code = cli_agent.init(
Prompt(
f"Make a program that prints 'Hello World!' to a file called '{outfile} either using python or javascript'"
)
)
env = DiskExecutionEnv()
env.upload(code).run(f"bash {ENTRYPOINT_FILE}")
code = env.download()
assert outfile in code
assert code[outfile].strip() == "Hello World!"
def test_improve_standard_config(monkeypatch):
monkeypatch.setattr("builtins.input", lambda _: "y")
temp_dir = tempfile.mkdtemp()
code = FilesDict(
{
"main.py": "def write_hello_world_to_file(filename):\n \"\"\"\n Writes 'Hello World!' to the specified file.\n \n :param filename: The name of the file to write to.\n \"\"\"\n with open(filename, 'w') as file:\n file.write('Hello World!')\n\nif __name__ == \"__main__\":\n output_filename = 'output.txt'\n write_hello_world_to_file(output_filename)",
"requirements.txt": "# No dependencies required",
"run.sh": "python3 main.py\n",
}
)
memory = DiskMemory(memory_path(temp_dir))
# version_manager = GitVersionManager(temp_dir)
execution_env = DiskExecutionEnv()
mock_ai = MockAI(
[
AIMessage(
"```diff\n--- main.py\n+++ main.py\n@@ -7,3 +7,3 @@\n with open(filename, 'w') as file:\n- file.write('Hello World!')\n+ file.write('!dlroW olleH')\n```"
)
]
)
cli_agent = CliAgent.with_default_config(memory, execution_env, ai=mock_ai)
code = cli_agent.improve(
code,
Prompt(
"Change the program so that it prints '!dlroW olleH' instead of 'Hello World!'"
),
)
env = DiskExecutionEnv()
env.upload(code).run(f"bash {ENTRYPOINT_FILE}")
code = env.download()
outfile = "output.txt"
assert outfile in code
assert code[outfile] == "!dlroW olleH"
if __name__ == "__main__":
pytest.main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/applications/cli/test_collection_consent.py | tests/applications/cli/test_collection_consent.py | """
Tests for the revised data collection consent mechanism in the cli/learning module.
"""
from pathlib import Path
from unittest.mock import patch
import pytest
from gpt_engineer.applications.cli.learning import (
ask_collection_consent,
check_collection_consent,
)
# Use a fixture to clean up created files after each test
@pytest.fixture
def cleanup():
yield
if Path(".gpte_consent").exists():
Path(".gpte_consent").unlink()
"""
Test the following 4 scenarios for check_collection_consent():
* The .gpte_consent file exists and its content is "true".
* The .gpte_consent file exists but its content is not "true".
* The .gpte_consent file does not exist and the user gives consent when asked.
* The .gpte_consent file does not exist and the user does not give consent when asked.
"""
def test_check_consent_file_exists_and_true(cleanup):
Path(".gpte_consent").write_text("true")
assert check_collection_consent() is True
def test_check_consent_file_exists_and_false(cleanup):
Path(".gpte_consent").write_text("false")
with patch("builtins.input", side_effect=["n"]):
assert check_collection_consent() is False
def test_check_consent_file_not_exists_and_user_says_yes(cleanup):
with patch("builtins.input", side_effect=["y"]):
assert check_collection_consent() is True
assert Path(".gpte_consent").exists()
assert Path(".gpte_consent").read_text() == "true"
def test_check_consent_file_not_exists_and_user_says_no(cleanup):
with patch("builtins.input", side_effect=["n"]):
assert check_collection_consent() is False
assert not Path(".gpte_consent").exists()
"""
Test the following 4 scenarios for ask_collection_consent():
1. The user immediately gives consent with "y":
* The .gpte_consent file is created with content "true".
* The function returns True.
2. The user immediately denies consent with "n":
* The .gpte_consent file is not created.
* The function returns False.
3. The user first provides an invalid response, then gives consent with "y":
* The user is re-prompted after the invalid input.
* The .gpte_consent file is created with content "true".
* The function returns True.
4. The user first provides an invalid response, then denies consent with "n":
* The user is re-prompted after the invalid input.
* The .gpte_consent file is not created.
* The function returns False.
"""
def test_ask_collection_consent_yes(cleanup):
with patch("builtins.input", side_effect=["y"]):
result = ask_collection_consent()
assert Path(".gpte_consent").exists()
assert Path(".gpte_consent").read_text() == "true"
assert result is True
def test_ask_collection_consent_no(cleanup):
with patch("builtins.input", side_effect=["n"]):
result = ask_collection_consent()
assert not Path(".gpte_consent").exists()
assert result is False
def test_ask_collection_consent_invalid_then_yes(cleanup):
with patch("builtins.input", side_effect=["invalid", "y"]):
result = ask_collection_consent()
assert Path(".gpte_consent").exists()
assert Path(".gpte_consent").read_text() == "true"
assert result is True
def test_ask_collection_consent_invalid_then_no(cleanup):
with patch("builtins.input", side_effect=["invalid", "n"]):
result = ask_collection_consent()
assert not Path(".gpte_consent").exists()
assert result is False
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/test_file_selector_enhancements.py | tests/core/test_file_selector_enhancements.py | import os
from pathlib import Path
from typing import List, Union
from gpt_engineer.applications.cli.file_selector import FileSelector
editorcalled = False
def set_editor_called(
self, input_path: Union[str, Path], init: bool = True
) -> List[str]:
global editorcalled
editorcalled = True
return []
def set_file_selector_tmpproject(tmp_path):
project_path = tmp_path / "project/"
os.mkdir(project_path)
os.mkdir(project_path / "x")
os.mkdir(project_path / "a")
gpteng_path = project_path / ".gpteng"
os.mkdir(gpteng_path)
with open(gpteng_path / "file_selection.toml", "w") as file:
file.write("[files]\n")
file.write(' "x/xxtest.py" = "selected"\n')
file.write(' "a/aatest.py" = "selected"\n')
with open(project_path / "x/xxtest.py", "w") as file:
file.write('print("Hello")')
with open(project_path / "a/aatest.py", "w") as file:
file.write('print("Hello")')
return project_path
def test_file_selector_enhancement_skip_file_selector(tmp_path):
project_path = set_file_selector_tmpproject(tmp_path)
fileSelector = FileSelector(project_path=project_path)
fileSelector.editor_file_selector = set_editor_called
fileSelector.ask_for_files(skip_file_selection=True)
assert editorcalled is False, "FileSelector.skip_file_selector is not working"
def test_file_selector_enhancement_sort(tmp_path):
project_path = set_file_selector_tmpproject(tmp_path)
fileSelector = FileSelector(project_path=project_path)
sortedFiles = fileSelector.get_current_files(project_path)
assert sortedFiles == [
"a/aatest.py",
"x/xxtest.py",
], "FileSelector.get_current_files is unsorted!"
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/test_chat_to_files.py | tests/core/test_chat_to_files.py | import os
from typing import Dict, Tuple
import pytest
from gpt_engineer.core.chat_to_files import parse_diffs
from gpt_engineer.core.diff import is_similar
from gpt_engineer.core.files_dict import file_to_lines_dict
THIS_FILE_DIR = os.path.dirname(os.path.abspath(__file__))
example_diff = """
Irrelevant line to be ignored
another irrelevant line to be ignored
```diff
--- example.txt
+++ example.txt
@@ -12,3 +12,4 @@
sample text 1
sample text 2
+ added extra line here
- original text A
+ updated original text A with changes
@@ -35,4 +36,5 @@
checking status:
- perform operation X
+ perform operation X only if specific condition holds
+ new operation related to condition
evaluating next step:
- execute step Y
+ revised execution of step Y
```
"""
example_multiple_diffs = """
I apologize for the oversight. Let's correct the `calculator.py` file with the proper git diff format, ensuring that the context lines match the original code exactly.
```diff
--- calculator.py
+++ calculator.py
@@ -1,3 +1,3 @@
class Calculator:
- def add(self, a, b):
- return a - b # Logical
+ def add(self, a, b): # Adds two numbers
+ return a + b
```
Now, let's create the `main.py` file with the correct git diff format:
```diff
--- /dev/null
+++ main.py
@@ -0,0 +1,7 @@
+from calculator import Calculator
+
+# Function to demonstrate the usage of the Calculator class
+def main():
+ calc = Calculator()
+if __name__ == "__main__":
+ main()
```
These changes should now correctly apply to the provided code and create a simple calculator program with a command-line interface.
"""
example_line_dist_diff = """
Irrelevant line to be ignored
another irrelevant line to be ignored
```diff
--- example.txt
+++ example.txt
@@ -10,4 +13,5 @@
sample text 1
sample text 2
+ added extra line here
- original text A
+ updated original text A with changes
@@ -33,14 +363,5 @@
checking status:
- perform operation X
+ perform operation X only if specific condition holds
+ new operation related to condition
evaluating next step:
- execute step Y
+ revised execution of step Y
```
"""
add_example = """
Uninteresting stuff
```diff
--- /dev/null
+++ new_file.txt
@@ -0,0 +1,3 @@
+First example line
+
+Last example line
```
"""
file_example = """# Introduction
@Analysis
Overview: outcomes
%
Background: *context*
Method: []
!
Theories: ?
> Leading up...
sample text 1
sample text 2
original text A
a
Challenges: ~
Perspectives: <>
Strategy: {#}
+
Outcomes: ^^^
Future: |||
x
Y
Z
code
checking status:
perform operation X
evaluating next step:
execute step Y
End.
Conclusion: ***
"""
single_diff = """
```
--- a/file1.txt
+++ a/file1.txt
@@ -1,3 +1,3 @@
-old line
+new line
```
"""
multi_diff = """
```
--- a/file1.txt
+++ a/file1.txt
@@ -1,3 +1,3 @@
-old line
+new line
```
```
--- a/file1.txt
+++ a/file1.txt
@@ -2,3 +2,3 @@
-another old line
+another new line
```
"""
# Single function tests
def test_basic_similarity():
assert is_similar("abc", "cab")
assert not is_similar("abc", "def")
def test_case_insensitivity_and_whitespace():
assert is_similar("A b C", "c a b")
assert not is_similar("Abc", "D e F")
def test_length_and_character_frequency():
assert is_similar("aabbc", "bacba")
assert not is_similar("aabbcc", "abbcc")
def test_edge_cases():
assert not is_similar("", "a")
assert is_similar("a", "a")
def insert_string_in_lined_string(string, to_insert, line_number):
split_string = string.split("\n")
split_string.insert(line_number - 1, to_insert)
return "\n".join(split_string)
def test_diff_changing_one_file():
diffs = parse_diffs(example_diff)
for filename, diff in diffs.items():
string_diff = diff.diff_to_string()
correct_diff = "\n".join(example_diff.strip().split("\n")[4:-1])
assert string_diff == correct_diff
def test_diff_adding_one_file():
add_diff = parse_diffs(add_example)
for filename, diff in add_diff.items():
string_add_diff = diff.diff_to_string()
correct_add_diff = "\n".join(add_example.strip().split("\n")[2:-1])
assert string_add_diff == correct_add_diff
def test_diff_changing_two_files():
merged_diff = parse_diffs(example_diff + add_example)
correct_diff = "\n".join(example_diff.strip().split("\n")[4:-1])
correct_add_diff = "\n".join(add_example.strip().split("\n")[2:-1])
assert merged_diff["example.txt"].diff_to_string() == correct_diff
assert merged_diff["new_file.txt"].diff_to_string() == correct_add_diff
def test_validate_diff_correct():
lines_dict = file_to_lines_dict(file_example)
diffs = parse_diffs(example_diff)
# This is a test in its own right since it full of exceptions, would something go wrong
list(diffs.values())[0].validate_and_correct(lines_dict)
def test_correct_distorted_numbers():
lines_dict = file_to_lines_dict(file_example)
diffs = parse_diffs(example_line_dist_diff)
# This is a test in its own right since it full of exceptions, would something go wrong
list(diffs.values())[0].validate_and_correct(lines_dict)
correct_diff = "\n".join(example_diff.strip().split("\n")[4:-1])
assert diffs["example.txt"].diff_to_string() == correct_diff
def test_correct_skipped_lines():
distorted_example = insert_string_in_lined_string(
file_example, "#\n#comment\n#\n#", 14
)
diffs = parse_diffs(example_diff)
list(diffs.values())[0].validate_and_correct(file_to_lines_dict(distorted_example))
with open(
os.path.join(
THIS_FILE_DIR,
"improve_function_test_cases",
"corrected_diff_from_missing_lines",
),
"r",
) as f:
corrected_diff_from_missing_lines = f.read()
assert (
diffs["example.txt"].diff_to_string().strip()
== corrected_diff_from_missing_lines.strip()
)
def test_correct_skipped_lines_and_number_correction():
distorted_example = insert_string_in_lined_string(
file_example, "#\n#comment\n#\n#", 14
)
diffs = parse_diffs(example_line_dist_diff)
# list(diffs.values())[0].validate_and_correct(file_to_lines_dict(distorted_example))
for diff in diffs.values():
problems = diff.validate_and_correct(file_to_lines_dict(distorted_example))
print(problems)
with open(
os.path.join(
THIS_FILE_DIR,
"improve_function_test_cases",
"corrected_diff_from_missing_lines",
),
"r",
) as f:
corrected_diff_from_missing_lines = f.read()
assert (
diffs["example.txt"].diff_to_string().strip()
== corrected_diff_from_missing_lines.strip()
)
def test_diff_regex():
diff = parse_diffs(example_diff)
assert len(diff) == 1
diffs = parse_diffs(example_multiple_diffs)
assert len(diffs) == 2
def parse_chats_with_regex(
diff_file_name: str, code_file_name: str
) -> Tuple[str, str, Dict]:
# Load the diff
with open(
os.path.join(THIS_FILE_DIR, "improve_function_test_cases", diff_file_name), "r"
) as f:
diff_content = f.read()
# Load the corresponding code
with open(
os.path.join(THIS_FILE_DIR, "improve_function_test_cases", code_file_name), "r"
) as f:
code_content = f.read()
# Parse the diffs
diffs = parse_diffs(diff_content)
return diff_content, code_content, diffs
def capture_print_output(func):
import io
import sys
captured_output = io.StringIO()
sys.stdout = captured_output
func()
sys.stdout = sys.__stdout__
return captured_output
def test_single_diff():
diffs = parse_diffs(single_diff)
correct_diff = "\n".join(single_diff.strip().split("\n")[1:-1])
assert diffs["a/file1.txt"].diff_to_string() == correct_diff
def test_multi_diff_discard():
captured_output = capture_print_output(lambda: parse_diffs(multi_diff))
diffs = parse_diffs(multi_diff)
correct_diff = "\n".join(multi_diff.strip().split("\n")[1:8]).replace(
"```\n```", ""
)
assert (
"Multiple diffs found for a/file1.txt. Only the first one is kept."
in captured_output.getvalue()
)
assert diffs["a/file1.txt"].diff_to_string().strip() == correct_diff.strip()
# test parse diff
def test_controller_diff():
parse_chats_with_regex("controller_chat", "controller_code")
def test_simple_calculator_diff():
parse_chats_with_regex("simple_calculator_chat", "simple_calculator_code")
def test_complex_temperature_converter_diff():
parse_chats_with_regex("temperature_converter_chat", "temperature_converter_code")
def test_complex_task_master_diff():
parse_chats_with_regex("task_master_chat", "task_master_code")
def test_long_file_diff():
parse_chats_with_regex("wheaties_example_chat", "wheaties_example_code")
if __name__ == "__main__":
pytest.main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/test_git.py | tests/core/test_git.py | import subprocess
import tempfile
from pathlib import Path
from gpt_engineer.core.git import (
filter_by_gitignore,
filter_files_with_uncommitted_changes,
init_git_repo,
is_git_installed,
is_git_repo,
stage_files,
)
def test_verify_git_installed():
# If git isn't installed we can't run any git tests either way
assert is_git_installed()
def test_init_git_repo():
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir)
init_git_repo(path)
assert is_git_repo(path)
def test_stage_files():
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir)
init_git_repo(path)
# Create a file and stage it
file = path / "test.txt"
file.write_text("test")
stage_files(path, ["test.txt"])
# Check if the file is staged
assert (
subprocess.run(
["git", "diff", "--cached", "--name-only"],
cwd=path,
stdout=subprocess.PIPE,
)
.stdout.decode()
.strip()
== "test.txt"
)
def test_filter_by_gitignore():
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir)
init_git_repo(path)
# Create a .gitignore file
gitignore = path / ".gitignore"
gitignore.write_text("*.txt")
assert filter_by_gitignore(path, ["test.txt"]) == []
def test_filter_by_uncommitted_changes():
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir)
init_git_repo(path)
# Create a file and commit it
file = path / "test.txt"
file.write_text("test")
subprocess.run(["git", "add", "test.txt"], cwd=path)
subprocess.run(["git", "commit", "-m", "test"], cwd=path)
# Update the file
file.write_text("test2")
# Check if the file is staged
assert filter_files_with_uncommitted_changes(path, {"test.txt": "test"}) == [
"test.txt"
]
def test_filter_by_uncommitted_changes_ignore_staged_files():
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir)
init_git_repo(path)
# Create a file but and stage it
file = path / "test.txt"
file.write_text("test")
subprocess.run(["git", "add", "test.txt"], cwd=path)
# Check if the file is staged
assert filter_files_with_uncommitted_changes(path, {"test.txt": "test"}) == []
def test_filter_by_uncommitted_changes_ignore_untracked():
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir)
init_git_repo(path)
# Create a file but don't track it
file = path / "test.txt"
file.write_text("test")
# Check if the file is staged
assert filter_files_with_uncommitted_changes(path, {"test.txt": "test"}) == []
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/test_token_usage.py | tests/core/test_token_usage.py | import base64
import csv
import io
import os
from io import StringIO
from pathlib import Path
from langchain.schema import HumanMessage, SystemMessage
from PIL import Image
from gpt_engineer.core.token_usage import Tokenizer, TokenUsageLog
def test_format_log():
# arrange
token_usage_log = TokenUsageLog("gpt-4")
request_messages = [
SystemMessage(content="my system message"),
HumanMessage(content="my user prompt"),
]
response = "response from model"
# act
token_usage_log.update_log(request_messages, response, "step 1")
token_usage_log.update_log(request_messages, response, "step 2")
csv_log = token_usage_log.format_log()
# assert
csv_rows = list(csv.reader(StringIO(csv_log)))
assert len(csv_rows) == 3
assert all(len(row) == 7 for row in csv_rows)
def test_usage_cost():
# arrange
token_usage_log = TokenUsageLog("gpt-4")
request_messages = [
SystemMessage(content="my system message"),
HumanMessage(content="my user prompt"),
]
response = "response from model"
# act
token_usage_log.update_log(request_messages, response, "step 1")
token_usage_log.update_log(request_messages, response, "step 2")
usage_cost = token_usage_log.usage_cost()
# assert
assert usage_cost > 0
def test_image_tokenizer():
# Arrange
token_usage_log = Tokenizer("gpt-4")
image_path = Path(__file__).parent.parent / "test_data" / "mona_lisa.jpg"
# Check if the image file exists
if not os.path.isfile(image_path):
raise FileNotFoundError(f"Image file not found: {image_path}")
# Act
with Image.open(image_path) as img:
# Convert RGBA to RGB
if img.mode == "RGBA":
img = img.convert("RGB")
buffered = io.BytesIO()
img.save(buffered, format="JPEG")
image_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
# Calculate the token cost of the base64 encoded image
image_token_cost = token_usage_log.num_tokens_for_base64_image(image_base64)
# Assert
assert image_token_cost == 1105
def test_list_type_message_with_image():
# Arrange
token_usage_log = TokenUsageLog("gpt-4")
request_messages = [
SystemMessage(content="My system message"),
HumanMessage(
content=[
{"type": "text", "text": "My user message"},
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII",
"detail": "low",
},
},
]
),
]
response = "response from model"
# Act
token_usage_log.update_log(request_messages, response, "list message with image")
# Since this is the first (and only) log entry, the in-step total tokens should match our expected total
expected_total_tokens = 106
# Assert
assert (
token_usage_log.log()[-1].in_step_total_tokens == expected_total_tokens
), f"Expected {expected_total_tokens} tokens, got {token_usage_log.log()[-1].in_step_total_tokens}"
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/__init__.py | tests/core/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/test_salvage_correct_hunks.py | tests/core/test_salvage_correct_hunks.py | import os
import shutil
from typing import List
import pytest
from langchain_core.messages import AIMessage
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.paths import memory_path
from gpt_engineer.core.default.steps import salvage_correct_hunks
from gpt_engineer.core.files_dict import FilesDict
TEST_FILES_DIR = os.path.dirname(os.path.abspath(__file__))
memory = DiskMemory(memory_path("."))
def get_file_content(file_path: str) -> str:
with open(
os.path.join(TEST_FILES_DIR, "improve_function_test_cases", file_path), "r"
) as f:
return f.read()
def message_builder(chat_path: str) -> List[AIMessage]:
chat_content = get_file_content(chat_path)
json = {
"lc": 1,
"type": "constructor",
"id": ["langchain", "schema", "messages", "AIMessage"],
"kwargs": {
"content": chat_content,
"additional_kwargs": {},
"response_metadata": {"finish_reason": "stop"},
"name": None,
"id": None,
"example": False,
},
}
return [AIMessage(**json["kwargs"])]
def test_validation_and_apply_complex_diff():
files = FilesDict({"taskmaster.py": get_file_content("task_master_code")})
salvage_correct_hunks(message_builder("task_master_chat"), files, memory)
def test_validation_and_apply_long_diff():
files = FilesDict({"VMClonetest.ps1": get_file_content("wheaties_example_code")})
salvage_correct_hunks(message_builder("wheaties_example_chat"), files, memory)
def test_validation_and_apply_wrong_diff():
files = FilesDict(
{"src/components/SocialLinks.tsx": get_file_content("vgvishesh_example_code")}
)
salvage_correct_hunks(message_builder("vgvishesh_example_chat"), files, memory)
def test_validation_and_apply_non_change_diff():
files = FilesDict({"src/App.tsx": get_file_content("vgvishesh_example_2_code")})
salvage_correct_hunks(message_builder("vgvishesh_example_2_chat"), files, memory)
def test_validation_and_apply_diff_on_apps_benchmark_6():
files = FilesDict({"main.py": get_file_content("apps_benchmark_6_code")})
salvage_correct_hunks(message_builder("apps_benchmark_6_chat"), files, memory)
def test_validation_and_apply_diff_on_apps_benchmark_6_v2():
files = FilesDict({"main.py": get_file_content("apps_benchmark_6_v2_code")})
salvage_correct_hunks(message_builder("apps_benchmark_6_v2_chat"), files, memory)
def test_create_two_new_files():
files = FilesDict({"main.py": get_file_content("create_two_new_files_code")})
salvage_correct_hunks(message_builder("create_two_new_files_chat"), files, memory)
def test_theo_case():
files = FilesDict({"dockerfile": get_file_content("theo_case_code")})
updated_files, _ = salvage_correct_hunks(
message_builder("theo_case_chat"), files, memory
)
print(updated_files["dockerfile"])
print(updated_files["run.py"])
def test_zbf_yml_missing():
files = FilesDict(
{"src/main/resources/application.yml": get_file_content("zbf_yml_missing_code")}
)
updated_files, _ = salvage_correct_hunks(
message_builder("zbf_yml_missing_chat"), files, memory
)
print(updated_files["src/main/resources/application.yml"])
print(updated_files["src/main/resources/application-local.yml"])
def test_clean_up_folder(clean_up_folder):
# The folder should be deleted after the test is run
assert True
@pytest.fixture
def clean_up_folder():
yield
# Teardown code: delete a folder and all its contents
print("cleaning up")
folder_path = os.path.join(os.path.dirname(__file__), ".gpteng")
shutil.rmtree(folder_path, ignore_errors=True)
if __name__ == "__main__":
pytest.main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/test_ai.py | tests/core/test_ai.py | from langchain.chat_models.base import BaseChatModel
from langchain_community.chat_models.fake import FakeListChatModel
from gpt_engineer.core.ai import AI
def mock_create_chat_model(self) -> BaseChatModel:
return FakeListChatModel(responses=["response1", "response2", "response3"])
def test_start(monkeypatch):
monkeypatch.setattr(AI, "_create_chat_model", mock_create_chat_model)
ai = AI("gpt-4")
# act
response_messages = ai.start("system prompt", "user prompt", step_name="step name")
# assert
assert response_messages[-1].content == "response1"
def test_next(monkeypatch):
# arrange
monkeypatch.setattr(AI, "_create_chat_model", mock_create_chat_model)
ai = AI("gpt-4")
response_messages = ai.start("system prompt", "user prompt", step_name="step name")
# act
response_messages = ai.next(
response_messages, "next user prompt", step_name="step name"
)
# assert
assert response_messages[-1].content == "response2"
def test_token_logging(monkeypatch):
# arrange
monkeypatch.setattr(AI, "_create_chat_model", mock_create_chat_model)
ai = AI("gpt-4")
# act
response_messages = ai.start("system prompt", "user prompt", step_name="step name")
usageCostAfterStart = ai.token_usage_log.usage_cost()
ai.next(response_messages, "next user prompt", step_name="step name")
usageCostAfterNext = ai.token_usage_log.usage_cost()
# assert
assert usageCostAfterStart > 0
assert usageCostAfterNext > usageCostAfterStart
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/default/__init__.py | tests/core/default/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/default/test_steps.py | tests/core/default/test_steps.py | # Generated by CodiumAI
import tempfile
from unittest.mock import MagicMock
import pytest
from langchain.schema import SystemMessage
from gpt_engineer.core.ai import AI
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.paths import ENTRYPOINT_FILE, PREPROMPTS_PATH
from gpt_engineer.core.default.steps import (
curr_fn,
gen_code,
gen_entrypoint,
improve_fn,
setup_sys_prompt,
setup_sys_prompt_existing_code,
)
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.linting import Linting
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
factorial_program = """
To implement a function that calculates the factorial of a number in Python, we will create a simple Python module with a single function `factorial`. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. It is denoted by `n!`. The factorial of 0 is defined to be 1.
Let's start by creating the `factorial.py` file which will contain our `factorial` function.
factorial.py
```python
def factorial(n: int) -> int:
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
elif n == 0:
return 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: python factorial.py <number>")
sys.exit(1)
try:
number = int(sys.argv[1])
print(f"The factorial of {number} is {factorial(number)}")
except ValueError as e:
print(e)
sys.exit(1)
```
Now, let's create a `requirements.txt` file to specify the dependencies for this module. Since we are not using any external libraries, the `requirements.txt` file will be empty, but it's a good practice to include it in Python projects.
requirements.txt
```
# No dependencies required
```
This concludes a fully working implementation.```
"""
factorial_entrypoint = """
Irrelevant explanations
```sh
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pytest test_factorial.py
```
"""
class TestGenCode:
# Generates code based on a given prompt using an AI model.
def test_generates_code_using_ai_model(self):
# Mock AI class
class MockAI:
def start(self, sys_prompt, user_prompt, step_name):
return [SystemMessage(content=factorial_program)]
ai = MockAI()
prompt = Prompt("Write a function that calculates the factorial of a number.")
memory = DiskMemory(tempfile.mkdtemp())
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
code = gen_code(ai, prompt, memory, preprompts_holder)
assert isinstance(code, FilesDict)
assert len(code) == 2
# assert CODE_GEN_LOG_FILE in memory
# assert memory[CODE_GEN_LOG_FILE] == factorial_program.strip()
# The generated code is saved to disk.
def test_generated_code_saved_to_disk(self):
# Mock AI class
class MockAI:
def start(self, sys_prompt, user_prompt, step_name):
return [SystemMessage(content=factorial_program)]
ai = MockAI()
prompt = Prompt("Write a function that calculates the factorial of a number.")
memory = DiskMemory(tempfile.mkdtemp())
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
code = gen_code(ai, prompt, memory, preprompts_holder)
assert isinstance(code, FilesDict)
assert len(code) == 2
# assert CODE_GEN_LOG_FILE in memory
# assert memory[CODE_GEN_LOG_FILE] == factorial_program.strip()
# Raises TypeError if keys are not strings or Path objects.
def test_raises_type_error_if_keys_not_strings_or_path_objects(self):
# Mock AI class
class MockAI:
def start(self, sys_prompt, user_prompt, step_name):
return [SystemMessage(content=factorial_program)]
ai = MockAI()
prompt = Prompt("Write a function that calculates the factorial of a number.")
memory = DiskMemory(tempfile.mkdtemp())
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
with pytest.raises(TypeError):
code = gen_code(ai, prompt, memory, preprompts_holder)
code[123] = "code"
# Raises TypeError if values are not strings.
def test_raises_type_error_if_values_not_strings(self):
# Mock AI class
class MockAI:
def start(self, sys_prompt, user_prompt, step_name):
return [SystemMessage(content=factorial_program)]
ai = MockAI()
prompt = Prompt("Write a function that calculates the factorial of a number.")
memory = DiskMemory(tempfile.mkdtemp())
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
with pytest.raises(TypeError):
code = gen_code(ai, prompt, memory, preprompts_holder)
code["file.py"] = 123
# Raises KeyError if the file does not exist in the database.
def test_raises_key_error_if_file_not_exist_in_database(self):
# Mock AI class
class MockAI:
def start(self, sys_prompt, user_prompt, step_name):
return [SystemMessage(content=factorial_program)]
ai = MockAI()
prompt = Prompt("Write a function that calculates the factorial of a number.")
memory = DiskMemory(tempfile.mkdtemp())
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
with pytest.raises(KeyError):
code = gen_code(ai, prompt, memory, preprompts_holder)
code["nonexistent_file.py"]
class TestStepUtilities:
def test_called_from_function(self):
# Arrange
def test_function():
return curr_fn()
expected_name = "test_function"
# Act
actual_name = test_function()
# Assert
assert actual_name == expected_name
def test_constructs_system_prompt_with_predefined_instructions_and_philosophies(
self,
):
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
preprompts = preprompts_holder.get_preprompts()
sys_prompt = setup_sys_prompt(preprompts)
expected_prompt = (
preprompts["roadmap"]
+ preprompts["generate"].replace("FILE_FORMAT", preprompts["file_format"])
+ "\nUseful to know:\n"
+ preprompts["philosophy"]
)
assert sys_prompt == expected_prompt
def test_constructs_system_prompt(self):
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
preprompts = preprompts_holder.get_preprompts()
expected_prompt = (
preprompts["roadmap"]
+ preprompts["improve"].replace(
"FILE_FORMAT", preprompts["file_format_diff"]
)
+ "\nUseful to know:\n"
+ preprompts["philosophy"]
)
actual_prompt = setup_sys_prompt_existing_code(preprompts)
assert actual_prompt == expected_prompt
class TestGenEntrypoint:
class MockAI:
def __init__(self, content):
self.content = content
def start(self, system, user, step_name):
return [SystemMessage(content=self.content)]
# The function receives valid input and generates a valid entry point script.
def test_valid_input_generates_valid_entrypoint(self):
# Mock AI class
ai_mock = TestGenEntrypoint.MockAI(factorial_entrypoint)
code = FilesDict()
tempdir = tempfile.mkdtemp()
memory = DiskMemory(tempdir)
prompt = Prompt("")
# Act
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
entrypoint_code = gen_entrypoint(
ai_mock, prompt, code, memory, preprompts_holder
)
# Assert
assert ENTRYPOINT_FILE in entrypoint_code
assert isinstance(entrypoint_code[ENTRYPOINT_FILE], str)
assert (
entrypoint_code[ENTRYPOINT_FILE]
== """python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pytest test_factorial.py
"""
)
# assert ENTRYPOINT_LOG_FILE in memory
# assert isinstance(memory[ENTRYPOINT_LOG_FILE], str)
# assert memory[ENTRYPOINT_LOG_FILE] == factorial_entrypoint.strip()
# The function receives an empty codebase and returns an empty entry point script.
def test_empty_codebase_returns_empty_entrypoint(self):
# Arrange
ai_mock = TestGenEntrypoint.MockAI("Irrelevant explanation")
code = FilesDict()
tempdir = tempfile.mkdtemp()
memory = DiskMemory(tempdir)
prompt = Prompt("")
# Act
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
entrypoint_code = gen_entrypoint(
ai_mock, prompt, code, memory, preprompts_holder
)
# Assert
assert ENTRYPOINT_FILE in entrypoint_code
assert isinstance(entrypoint_code[ENTRYPOINT_FILE], str)
assert entrypoint_code[ENTRYPOINT_FILE] == ""
# assert ENTRYPOINT_LOG_FILE in memory
# assert isinstance(memory[ENTRYPOINT_LOG_FILE], str)
# assert memory[ENTRYPOINT_LOG_FILE] == "Irrelevant explanation"
class TestImprove:
def test_improve_existing_code(self, tmp_path):
# Mock the AI class
ai_patch = """
Some introductory text.
```diff
--- main.py
+++ main.py
@@ -1,1 +1,1 @@
-print('Hello, World!')
+print('Goodbye, World!')
```
"""
ai_mock = MagicMock(spec=AI)
ai_mock.next.return_value = [SystemMessage(content=ai_patch)]
# Create a Code object with existing code
code = FilesDict(
{
"main.py": "print('Hello, World!')",
"requirements.txt": "numpy==1.18.1",
"README.md": "This is a sample code repository.",
}
)
# Create a BaseRepository object for memory
memory = DiskMemory(tmp_path)
# Define the user prompt
prompt = Prompt(
"Change the program to print 'Goodbye, World!' instead of 'Hello, World!'"
)
# Call the improve function
preprompts_holder = PrepromptsHolder(PREPROMPTS_PATH)
improved_code = improve_fn(ai_mock, prompt, code, memory, preprompts_holder)
# Assert that the code was improved correctly
expected_code = FilesDict(
{
"main.py": "print('Goodbye, World!')",
"requirements.txt": "numpy==1.18.1",
"README.md": "This is a sample code repository.",
}
)
assert improved_code == expected_code
def test_lint_python(self):
linting = Linting()
content = "print('Hello, world! ')"
config = {"line_length": 50}
linted_content = linting.lint_python(content, config)
assert linted_content is not None, "Linted content should not be None"
def test_lint_files(self):
linting = Linting()
files_dict = FilesDict({"test.py": "print('Hello, world! ')"})
config = {"line_length": 50}
linted_files_dict = linting.lint_files(files_dict, config)
assert linted_files_dict is not None, "Linted files dict should not be None"
assert isinstance(
linted_files_dict, FilesDict
), "Output should be an instance of FilesDict"
assert (
"test.py" in linted_files_dict
), "test.py should be in the linted files dict"
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/default/test_simple_agent.py | tests/core/default/test_simple_agent.py | import tempfile
import pytest
from langchain.schema import AIMessage
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.default.paths import ENTRYPOINT_FILE
from gpt_engineer.core.default.simple_agent import SimpleAgent
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
from tests.mock_ai import MockAI
def test_init():
temp_dir = tempfile.mkdtemp()
mock_ai = MockAI(
[
AIMessage(
"hello_world.py\n```\nwith open('output.txt', 'w') as file:\n file.write('Hello World!')\n```"
),
AIMessage("```run.sh\npython3 hello_world.py\n```"),
],
)
lean_agent = SimpleAgent.with_default_config(temp_dir, mock_ai)
outfile = "output.txt"
code = lean_agent.init(
Prompt(
f"Make a program that prints 'Hello World!' to a file called '{outfile}'"
)
)
env = DiskExecutionEnv()
env.upload(code).run(f"bash {ENTRYPOINT_FILE}")
code = env.download()
assert outfile in code
assert code[outfile] == "Hello World!"
def test_improve():
temp_dir = tempfile.mkdtemp()
code = FilesDict(
{
"main.py": "def write_hello_world_to_file(filename):\n \"\"\"\n Writes 'Hello World!' to the specified file.\n \n :param filename: The name of the file to write to.\n \"\"\"\n with open(filename, 'w') as file:\n file.write('Hello World!')\n\nif __name__ == \"__main__\":\n output_filename = 'output.txt'\n write_hello_world_to_file(output_filename)",
"requirements.txt": "# No dependencies required",
"run.sh": "python3 main.py\n",
}
)
mock_ai = MockAI(
[
AIMessage(
"```diff\n--- main.py\n+++ main.py\n@@ -7,3 +7,3 @@\n with open(filename, 'w') as file:\n- file.write('Hello World!')\n+ file.write('!dlroW olleH')\n```"
)
]
)
lean_agent = SimpleAgent.with_default_config(temp_dir, mock_ai)
code = lean_agent.improve(
code,
Prompt(
"Change the program so that it prints '!dlroW olleH' instead of 'Hello World!' "
),
f"bash {ENTRYPOINT_FILE}",
)
env = DiskExecutionEnv()
env.upload(code).run(f"bash {ENTRYPOINT_FILE}")
code = env.download()
outfile = "output.txt"
assert outfile in code
assert code[outfile] == "!dlroW olleH"
if __name__ == "__main__":
pytest.main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/default/test_disk_file_repository.py | tests/core/default/test_disk_file_repository.py | import pytest
from gpt_engineer.core.default.disk_memory import DiskMemory
def test_DB_operations(tmp_path):
# Test initialization
db = DiskMemory(tmp_path)
# Test __setitem__
db["test_key"] = "test_value"
assert (tmp_path / "test_key").is_file()
# Test __getitem__
val = db["test_key"]
assert val == "test_value"
def test_large_files(tmp_path):
db = DiskMemory(tmp_path)
large_content = "a" * (10**6) # 1MB of tools
# Test write large files
db["large_file"] = large_content
# Test read large files
assert db["large_file"] == large_content
def test_concurrent_access(tmp_path):
import threading
db = DiskMemory(tmp_path)
num_threads = 10
num_writes = 1000
def write_to_db(thread_id):
for i in range(num_writes):
key = f"thread{thread_id}_write{i}"
db[key] = str(i)
threads = []
for thread_id in range(num_threads):
t = threading.Thread(target=write_to_db, args=(thread_id,))
t.start()
threads.append(t)
for t in threads:
t.join()
# Verify that all expected tools was written
for thread_id in range(num_threads):
for i in range(num_writes):
key = f"thread{thread_id}_write{i}"
assert key in db # using __contains__ now
assert db[key] == str(i)
def test_error_messages(tmp_path):
db = DiskMemory(tmp_path)
# Test error on getting non-existent key
with pytest.raises(KeyError):
db["non_existent"]
with pytest.raises(TypeError) as e:
db["key"] = ["Invalid", "value"]
assert str(e.value) == "val must be str"
# Generated by CodiumAI
class TestOnDiskRepository:
# can set and get a value for a key
def test_set_and_get_value(self, tmp_path):
db = DiskMemory(tmp_path)
db["test_key"] = "test_value"
assert (tmp_path / "test_key").is_file()
val = db["test_key"]
assert val == "test_value"
# can check if a key exists in the database
def test_key_exists(self, tmp_path):
db = DiskMemory(tmp_path)
db["test_key"] = "test_value"
assert "test_key" in db
assert "nonexistent_key" not in db
# can fetch a default value if a key does not exist
def test_fetch_default_value(self, tmp_path):
db = DiskMemory(tmp_path)
default_val = "default_value"
assert db.get("nonexistent_key", default_val) == default_val
# can delete a file or directory in the database
def test_delete_file_or_directory(self, tmp_path):
db = DiskMemory(tmp_path)
db["test_file"] = "test_content"
db["test_directory/test_file"] = "test_content"
del db["test_file"]
del db["test_directory"]
assert not (tmp_path / "test_file").exists()
assert not (tmp_path / "test_directory").exists()
# can iterate over all files in the database
def test_iterate_files(self, tmp_path):
db = DiskMemory(tmp_path)
db["file1.txt"] = "content1"
db["file2.txt"] = "content2"
db["directory/file3.txt"] = "content3"
files = list(db)
assert len(files) == 3
assert "file1.txt" in files
assert "file2.txt" in files
assert "directory/file3.txt" in files
# raises a KeyError if a non-existent key is accessed
def test_key_error(self, tmp_path):
db = DiskMemory(tmp_path)
with pytest.raises(KeyError):
_ = db["nonexistent_key"]
# raises a ValueError if a file name attempts to access parent path
def test_value_error(self, tmp_path):
db = DiskMemory(tmp_path)
with pytest.raises(ValueError):
db["../file.txt"] = "content"
# raises a TypeError if a non-string value is set for a key
def test_type_error(self, tmp_path):
db = DiskMemory(tmp_path)
with pytest.raises(TypeError):
db["test_key"] = 123
# can handle large file contents
def test_large_file_contents(self, tmp_path):
db = DiskMemory(tmp_path)
large_content = "a" * (10**6) # 1MB of tools
db["large_file"] = large_content
assert db["large_file"] == large_content
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/tests/core/default/test_disk_execution_env.py | tests/core/default/test_disk_execution_env.py | import tempfile
import unittest
from unittest.mock import MagicMock, patch
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
# from gpt_engineer.core.default.git_version_manager import GitVersionManager
from gpt_engineer.core.default.paths import ENTRYPOINT_FILE
from gpt_engineer.core.files_dict import FilesDict
class TestOnDiskExecutionEnv(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.env = DiskExecutionEnv()
def tearDown(self):
self.temp_dir.cleanup()
def test_successful_execution(self):
entrypoint_content = """
python -m venv venv
source venv/bin/activate
python script.py
"""
code = {
ENTRYPOINT_FILE: entrypoint_content,
"script.py": "print('This is a test script')",
}
with patch("subprocess.Popen") as mock_popen:
mock_popen.return_value.wait.return_value = 0
process = self.env.upload(FilesDict(code)).popen(f"bash {ENTRYPOINT_FILE}")
self.assertIsNotNone(process)
mock_popen.assert_called_once()
def test_missing_entrypoint(self):
code = {"script.py": "print('This is a test script')"}
p = self.env.upload(FilesDict(code)).popen(f"bash {ENTRYPOINT_FILE}")
p.communicate()
assert p.returncode != 0
def test_keyboard_interrupt_handling(self):
entrypoint_content = """
python script.py
"""
code = {
ENTRYPOINT_FILE: entrypoint_content,
"script.py": "print('This is a test script')",
}
with patch("subprocess.Popen") as mock_popen:
mock_process = MagicMock()
mock_process.poll.side_effect = KeyboardInterrupt
mock_popen.return_value = mock_process
stdout_full, stderr_full, returncode = self.env.upload(FilesDict(code)).run(
f"bash {ENTRYPOINT_FILE}"
)
mock_process.kill.assert_called_once()
def test_execution_with_output(self):
entrypoint_content = """
python script.py
"""
code = {
ENTRYPOINT_FILE: entrypoint_content,
"script.py": "import sys; print('Out'); sys.stderr.write('Error')",
}
with patch("subprocess.Popen") as mock_popen:
process = MagicMock()
process.wait.return_value = 0
process.communicate.return_value = (b"Out\n", b"Error\n")
mock_popen.return_value = process
process = self.env.upload(FilesDict(code)).popen(f"bash {ENTRYPOINT_FILE}")
stdout, stderr = process.communicate()
self.assertEqual(stdout, b"Out\n")
self.assertEqual(stderr, b"Error\n")
if __name__ == "__main__":
unittest.main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/docs/create_api_rst.py | docs/create_api_rst.py | """Script for auto-generating api_reference.rst"""
import glob
import re
from pathlib import Path
ROOT_DIR = Path(__file__).parents[1].absolute()
print(ROOT_DIR)
PKG_DIR = ROOT_DIR / "gpt_engineer"
WRITE_FILE = Path(__file__).parent / "api_reference.rst"
def load_members() -> dict:
members: dict = {}
for py in glob.glob(str(PKG_DIR) + "/**/*.py", recursive=True):
module = py[len(str(PKG_DIR)) + 1 :].replace(".py", "").replace("/", ".")
top_level = module.split(".")[0]
if top_level not in members:
members[top_level] = {"classes": [], "functions": []}
with open(py, "r") as f:
for line in f.readlines():
cls = re.findall(r"^class ([^_].*)\(", line)
members[top_level]["classes"].extend([module + "." + c for c in cls])
func = re.findall(r"^def ([^_].*)\(", line)
afunc = re.findall(r"^async def ([^_].*)\(", line)
func_strings = [module + "." + f for f in func + afunc]
members[top_level]["functions"].extend(func_strings)
return members
def construct_doc(members: dict) -> str:
full_doc = """\
.. _api_reference:
=============
API Reference
=============
"""
for module, _members in sorted(members.items(), key=lambda kv: kv[0]):
classes = _members["classes"]
functions = _members["functions"]
if not (classes or functions):
continue
module_title = module.replace("_", " ").title()
if module_title == "Llms":
module_title = "LLMs"
section = f":mod:`gpt_engineer.{module}`: {module_title}"
full_doc += f"""\
{section}
{'=' * (len(section) + 1)}
.. automodule:: gpt_engineer.{module}
:no-members:
:no-inherited-members:
"""
if classes:
cstring = "\n ".join(sorted(classes))
full_doc += f"""\
Classes
--------------
.. currentmodule:: gpt_engineer
.. autosummary::
:toctree: {module}
:template: class.rst
{cstring}
"""
if functions:
fstring = "\n ".join(sorted(functions))
full_doc += f"""\
Functions
--------------
.. currentmodule:: gpt_engineer
.. autosummary::
:toctree: {module}
{fstring}
"""
return full_doc
def main() -> None:
members = load_members()
full_doc = construct_doc(members)
with open(WRITE_FILE, "w") as f:
f.write(full_doc)
if __name__ == "__main__":
main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/docs/conf.py | docs/conf.py | #!/usr/bin/env python
#
# file_processor documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
from pathlib import Path
import toml
sys.path.insert(0, os.path.abspath(".."))
ROOT_DIR = Path(__file__).parents[1].absolute()
with open("../pyproject.toml") as f:
data = toml.load(f)
# The master toctree document.
master_doc = "index"
# General information about the project.
project = data["tool"]["poetry"]["name"]
copyright = "2023 Anton Osika"
author = " Anton Osika & Contributors"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = data["tool"]["poetry"]["version"]
# The full version, including alpha/beta/rc tags.
release = data["tool"]["poetry"]["version"]
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autodoc.typehints",
"sphinx.ext.autosummary",
"sphinx.ext.napoleon",
"sphinx.ext.viewcode",
"sphinx_copybutton",
"myst_parser",
"IPython.sphinxext.ipython_console_highlighting",
]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = [".rst", ".md"]
autodoc_pydantic_model_show_json = False
autodoc_pydantic_field_list_validators = False
autodoc_pydantic_config_members = False
autodoc_pydantic_model_show_config_summary = False
autodoc_pydantic_model_show_validator_members = False
autodoc_pydantic_model_show_validator_summary = False
autodoc_pydantic_model_signature_prefix = "class"
autodoc_pydantic_field_signature_prefix = "param"
autodoc_member_order = "groupwise"
autoclass_content = "both"
autodoc_typehints_format = "short"
autodoc_default_options = {
"members": True,
"show-inheritance": True,
"inherited-members": "BaseModel",
"undoc-members": False,
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# source_suffix = '.rst'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ["_static"]
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "gpt_engineerdoc"
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, "gpt_engineer.tex", "GPT-ENgineer Documentation", "manual"),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "gpt_engineer", "GPT-Engineer Documentation", [author], 1)]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"gpt_engineer",
"GPT-Engineer Documentation",
author,
"gpt_engineer",
"One line description of project.",
"Miscellaneous",
),
]
# generate autosummary even if no references
autosummary_generate = True
myst_enable_extensions = [
"colon_fence",
]
myst_all_links_external = True
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/docs/examples/open_llms/langchain_interface.py | docs/examples/open_llms/langchain_interface.py | import os
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
model=os.getenv("MODEL_NAME"),
temperature=0.1,
callbacks=[StreamingStdOutCallbackHandler()],
streaming=True,
)
prompt = (
"Provide me with only the code for a simple python function that sums two numbers."
)
model.invoke(prompt)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/docs/examples/open_llms/openai_api_interface.py | docs/examples/open_llms/openai_api_interface.py | import os
from openai import OpenAI
client = OpenAI(
base_url=os.getenv("OPENAI_API_BASE"), api_key=os.getenv("OPENAI_API_KEY")
)
response = client.chat.completions.create(
model=os.getenv("MODEL_NAME"),
messages=[
{
"role": "user",
"content": "Provide me with only the code for a simple python function that sums two numbers.",
},
],
temperature=0.7,
max_tokens=200,
)
print(response.choices[0].message.content)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/projects/example-improve/controller.py | projects/example-improve/controller.py | import keyboard
class Controller:
def __init__(self, game, view):
self.game = game
self.view = view
def handle_input(self):
if keyboard.is_pressed("up") and not hasattr(self, "last_key_pressed"):
self.game.move("down")
self.last_key_pressed = "up"
elif hasattr(self, "last_key_pressed") and self.last_key_pressed == "up":
self.game.move("right")
del self.last_key_pressed
elif keyboard.is_pressed("down"):
self.game.move("up")
elif keyboard.is_pressed("left"):
self.game.move("right")
elif keyboard.is_pressed("right"):
self.game.move("left")
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/projects/example-improve/view.py | projects/example-improve/view.py | from model import Point
class View:
def __init__(self, game):
self.game = game
def render(self):
# Print the game state
for y in range(10):
for x in range(10):
if Point(x, y) in self.game.snake:
print("S", end="")
elif Point(x, y) == self.game.food:
print("F", end="")
else:
print(".", end="")
print()
print()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/projects/example-improve/model.py | projects/example-improve/model.py | import random
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
class Game:
def __init__(self):
self.snake = [Point(5, 5)]
self.food = self.generate_food()
self.is_running = True
def generate_food(self):
return Point(random.randint(0, 10), random.randint(0, 10))
def update(self):
# Move the snake
self.snake.move()
# Check for collision with food
if self.snake.head == self.food:
self.snake.grow()
self.food = self.generate_food()
# Check for collision with boundaries
if not (0 <= self.snake.head.x < 10 and 0 <= self.snake.head.y < 10):
self.is_running = False
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/projects/example-improve/main.py | projects/example-improve/main.py | from controller import Controller
from model import Game
from view import View
def main():
game = Game()
view = View(game)
controller = Controller(game, view)
while game.is_running:
controller.handle_input()
game.update()
view.render()
if __name__ == "__main__":
main()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/__init__.py | gpt_engineer/__init__.py | # Adding convenience imports to the package
# from gpt_engineer.tools import code_vector_repository
# from gpt_engineer.core.default import on_disk_repository
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/tools/supported_languages.py | gpt_engineer/tools/supported_languages.py | """
This module defines the supported programming languages for document chunking.
Variables:
SUPPORTED_LANGUAGES (list): A list of dictionaries defining supported languages.
"""
SUPPORTED_LANGUAGES = [
{"name": "Python", "extensions": [".py"], "tree_sitter_name": "python"},
{
"name": "JavaScript",
"extensions": [".js", ".mjs"],
"tree_sitter_name": "javascript",
},
{"name": "HTML", "extensions": [".html", ".htm"], "tree_sitter_name": "html"},
{"name": "CSS", "extensions": [".css"], "tree_sitter_name": "css"},
{"name": "Java", "extensions": [".java"], "tree_sitter_name": "java"},
{"name": "C#", "extensions": [".cs"], "tree_sitter_name": "c_sharp"},
{
"name": "TypeScript",
"extensions": [".ts", ".tsx"],
"tree_sitter_name": "typescript",
},
{"name": "Ruby", "extensions": [".rb", ".erb"], "tree_sitter_name": "ruby"},
{
"name": "PHP",
"extensions": [
".php",
".phtml",
".php3",
".php4",
".php5",
".php7",
".phps",
".php-s",
".pht",
".phar",
],
"tree_sitter_name": "php",
},
{"name": "Go", "extensions": [".go"], "tree_sitter_name": "go"},
{"name": "Kotlin", "extensions": [".kt", ".kts"], "tree_sitter_name": "kotlin"},
{"name": "Rust", "extensions": [".rs"], "tree_sitter_name": "rust"},
{
"name": "C++",
"extensions": [".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"],
"tree_sitter_name": "cpp",
},
{"name": "C", "extensions": [".c", ".h"], "tree_sitter_name": "c"},
{"name": "Markdown", "extensions": [".md"], "tree_sitter_name": "md"},
{"name": "Arduino C", "extensions": [".ino"], "tree_sitter_name": "ino"}
# ---- the following are not supported by the current code chunker implementation ----
# {
# "name": "Swift",
# "extensions": [".swift"],
# "tree_sitter_name": "swift"
# },
]
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/tools/custom_steps.py | gpt_engineer/tools/custom_steps.py | from platform import platform
from sys import version_info
from typing import List, Union
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from gpt_engineer.core.ai import AI
from gpt_engineer.core.base_execution_env import BaseExecutionEnv
from gpt_engineer.core.base_memory import BaseMemory
from gpt_engineer.core.chat_to_files import chat_to_files_dict
from gpt_engineer.core.default.paths import CODE_GEN_LOG_FILE, ENTRYPOINT_FILE
from gpt_engineer.core.default.steps import curr_fn, improve_fn, setup_sys_prompt
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
# Type hint for chat messages
Message = Union[AIMessage, HumanMessage, SystemMessage]
MAX_SELF_HEAL_ATTEMPTS = 10
def get_platform_info() -> str:
"""
Returns a string containing the OS and Python version information.
This function is used for self-healing by providing information about the current
operating system and Python version. It assumes that the Python version in the
virtual environment is the one being used.
Returns:
str: A string containing the OS and Python version information.
"""
v = version_info
a = f"Python Version: {v.major}.{v.minor}.{v.micro}"
b = f"\nOS: {platform()}\n"
return a + b
def self_heal(
ai: AI,
execution_env: BaseExecutionEnv,
files_dict: FilesDict,
prompt: Prompt = None,
preprompts_holder: PrepromptsHolder = None,
memory: BaseMemory = None,
diff_timeout=3,
) -> FilesDict:
"""
Attempts to execute the code from the entrypoint and if it fails, sends the error output back to the AI with instructions to fix.
Parameters
----------
ai : AI
An instance of the AI model.
execution_env : BaseExecutionEnv
The execution environment where the code is run.
files_dict : FilesDict
A dictionary of file names to their contents.
preprompts_holder : PrepromptsHolder, optional
A holder for preprompt messages.
Returns
-------
FilesDict
The updated files dictionary after self-healing attempts.
Raises
------
FileNotFoundError
If the required entrypoint file does not exist in the code.
AssertionError
If the preprompts_holder is None.
Notes
-----
This code will make `MAX_SELF_HEAL_ATTEMPTS` to try and fix the code
before giving up.
This makes the assuption that the previous step was `gen_entrypoint`,
this code could work with `simple_gen`, or `gen_clarified_code` as well.
"""
# step 1. execute the entrypoint
# log_path = dbs.workspace.path / "log.txt"
if ENTRYPOINT_FILE not in files_dict:
raise FileNotFoundError(
"The required entrypoint "
+ ENTRYPOINT_FILE
+ " does not exist in the code."
)
attempts = 0
if preprompts_holder is None:
raise AssertionError("Prepromptsholder required for self-heal")
while attempts < MAX_SELF_HEAL_ATTEMPTS:
attempts += 1
timed_out = False
# Start the process
execution_env.upload(files_dict)
p = execution_env.popen(files_dict[ENTRYPOINT_FILE])
# Wait for the process to complete and get output
stdout_full, stderr_full = p.communicate()
if (p.returncode != 0 and p.returncode != 2) and not timed_out:
print("run.sh failed. The log is:")
print(stdout_full.decode("utf-8"))
print(stderr_full.decode("utf-8"))
new_prompt = Prompt(
f"A program with this specification was requested:\n{prompt}\n, but running it produced the following output:\n{stdout_full}\n and the following errors:\n{stderr_full}. Please change it so that it fulfills the requirements."
)
files_dict = improve_fn(
ai, new_prompt, files_dict, memory, preprompts_holder, diff_timeout
)
else:
break
return files_dict
def clarified_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
"""
Generates code based on clarifications obtained from the user and saves it to a specified workspace.
Parameters
----------
ai : AI
An instance of the AI model, responsible for processing and generating the code.
prompt : str
The user's clarification prompt.
memory : BaseMemory
The memory instance where the generated code log is saved.
preprompts_holder : PrepromptsHolder
A holder for preprompt messages.
Returns
-------
FilesDict
A dictionary of file names to their contents generated by the AI.
"""
preprompts = preprompts_holder.get_preprompts()
messages: List[Message] = [SystemMessage(content=preprompts["clarify"])]
user_input = prompt.text # clarify does not work with vision right now
while True:
messages = ai.next(messages, user_input, step_name=curr_fn())
msg = messages[-1].content.strip()
if "nothing to clarify" in msg.lower():
break
if msg.lower().startswith("no"):
print("Nothing to clarify.")
break
print('(answer in text, or "c" to move on)\n')
user_input = input("")
print()
if not user_input or user_input == "c":
print("(letting gpt-engineer make its own assumptions)")
print()
messages = ai.next(
messages,
"Make your own assumptions and state them explicitly before starting",
step_name=curr_fn(),
)
print()
user_input += """
\n\n
Is anything else unclear? If yes, ask another question.\n
Otherwise state: "Nothing to clarify"
"""
print()
messages = [
SystemMessage(content=setup_sys_prompt(preprompts)),
] + messages[
1:
] # skip the first clarify message, which was the original clarify priming prompt
messages = ai.next(
messages,
preprompts["generate"].replace("FILE_FORMAT", preprompts["file_format"]),
step_name=curr_fn(),
)
print()
chat = messages[-1].content.strip()
memory.log(CODE_GEN_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
files_dict = chat_to_files_dict(chat)
return files_dict
def lite_gen(
ai: AI, prompt: Prompt, memory: BaseMemory, preprompts_holder: PrepromptsHolder
) -> FilesDict:
"""
Executes the AI model using the main prompt and saves the generated results to the specified workspace.
Parameters
----------
ai : AI
An instance of the AI model.
prompt : str
The main prompt to feed to the AI model.
memory : BaseMemory
The memory instance where the generated code log is saved.
preprompts_holder : PrepromptsHolder
A holder for preprompt messages.
Returns
-------
FilesDict
A dictionary of file names to their contents generated by the AI.
Notes
-----
The function assumes the `ai.start` method and the `to_files` utility to be correctly
set up and functional. Ensure these prerequisites before invoking `lite_gen`.
"""
preprompts = preprompts_holder.get_preprompts()
messages = ai.start(
prompt.to_langchain_content(), preprompts["file_format"], step_name=curr_fn()
)
chat = messages[-1].content.strip()
memory.log(CODE_GEN_LOG_FILE, "\n\n".join(x.pretty_repr() for x in messages))
files_dict = chat_to_files_dict(chat)
return files_dict
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/tools/__init__.py | gpt_engineer/tools/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/run.py | gpt_engineer/benchmark/run.py | """
Module for running benchmarks.
This module defines functions to run benchmarks using a given agent and to print
the results of the benchmark tasks.
Functions
---------
run : function
Runs the benchmark tasks using the provided agent and returns a list of TaskResult objects.
print_results : function
Prints the results of the benchmark tasks to the console.
"""
import time
from typing import List
import yaml
from gpt_engineer.benchmark.types import Assertable, Benchmark, TaskResult
from gpt_engineer.core.base_agent import BaseAgent
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
def run(
agent: BaseAgent,
benchmark: Benchmark,
verbose=False,
) -> List[TaskResult]:
"""
Runs the benchmark tasks using the provided agent and returns a list of TaskResult objects.
Parameters
----------
agent : BaseAgent
The agent to use for running the benchmark tasks.
benchmark : Benchmark
The benchmark containing the tasks to run.
verbose : bool, default=False
A flag to indicate whether to print verbose output during the benchmark.
Returns
-------
List[TaskResult]
A list of TaskResult objects representing the results of the benchmark tasks.
"""
task_results = []
for task in benchmark.tasks:
print(f"--> Running task: {task.name}\n")
t0 = time.time()
files_dict = agent.improve(task.initial_code, task.prompt)
t1 = time.time()
env = DiskExecutionEnv()
env.upload(files_dict)
if task.command:
p = env.popen(task.command)
stdout, stderr = p.communicate(benchmark.timeout)
stdout, stderr = stdout.decode("utf-8"), stderr.decode("utf-8")
else:
p, stdout, stderr = None, None, None
exec_result = Assertable(
files=files_dict,
env=env,
process=p,
stdout=stdout,
stderr=stderr,
)
task_results.append(
TaskResult(
task_name=task.name,
assertion_results={
assertion_name: assertion(exec_result)
for assertion_name, assertion in task.assertions.items()
},
duration=t1 - t0,
)
)
if verbose:
print_results(task_results)
return task_results
def print_results(results: list[TaskResult]):
"""
Prints the results of the benchmark tasks to the console.
Parameters
----------
results : list[TaskResult]
A list of TaskResult objects representing the results of the benchmark tasks.
Returns
-------
None
"""
for task_result in results:
print(f"\n--- Results for {task_result.task_name} ---")
print(f"{task_result.task_name} ({task_result.duration:.2f}s)")
for assertion_name, assertion_result in task_result.assertion_results.items():
checkmark = "✅" if assertion_result else "❌"
print(f" {checkmark} {assertion_name}")
print()
success_rates = [task_result.success_rate for task_result in results]
avg_success_rate = sum(success_rates) / len(results)
total_time = sum(task_result.duration for task_result in results)
correct_assertions = sum(
sum(
assertion_result
for assertion_result in task_result.assertion_results.values()
)
for task_result in results
)
total_assertions = sum(
len(task_result.assertion_results) for task_result in results
)
correct_tasks = [
task_result for task_result in results if task_result.success_rate == 1
]
print("--- Results ---")
print(f"Total time: {total_time:.2f}s")
print(f"Completely correct tasks: {len(correct_tasks)}/{len(results)}")
print(f"Total correct assertions: {correct_assertions}/{total_assertions}")
print(f"Average success rate: {avg_success_rate * 100}% on {len(results)} tasks")
print("--- Results ---")
print()
def export_yaml_results(yaml_path, complete_results, config):
for results in complete_results.values():
correct_tasks = [
task_result
for task_result in results["detailed"]
if task_result["solved"] == 1.0
]
fraction_correct = len(correct_tasks) / len(results["detailed"])
results["fully_solved"] = fraction_correct
complete_results["config"] = config
with open(yaml_path, "w") as f:
yaml.dump(complete_results, f, indent=4)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/bench_config.py | gpt_engineer/benchmark/bench_config.py | from dataclasses import dataclass, field
from pathlib import Path
from tomlkit.items import Integer
from gpt_engineer.core.project_config import read_config
@dataclass
class AppsConfig:
active: bool | None = True
test_start_index: int | None = 0
test_end_index: int | None = 1
train_start_index: int | None = 0
train_end_index: int | None = 0
examples_per_problem: int | None = 10
@dataclass
class MbppConfig:
active: bool | None = True
test_len: int | None = 1
train_len: int | None = 0
@dataclass
class GptmeConfig:
active: bool | None = True
@dataclass
class BenchConfig:
"""Configuration for the GPT Engineer CLI and gptengineer.app via `gpt-engineer.toml`."""
apps: AppsConfig = field(default_factory=AppsConfig)
mbpp: MbppConfig = field(default_factory=MbppConfig)
gptme: GptmeConfig = field(default_factory=GptmeConfig)
@classmethod
def from_toml(cls, config_file: Path | str):
if isinstance(config_file, str):
config_file = Path(config_file)
config_dict = read_config(config_file)
return cls.from_dict(config_dict)
@classmethod
def from_dict(cls, config_dict: dict):
return cls(
apps=AppsConfig(**config_dict.get("apps", {})),
mbpp=MbppConfig(**config_dict.get("mbpp", {})),
gptme=GptmeConfig(**config_dict.get("gptme", {})),
)
@staticmethod
def recursive_resolve(data_dict):
for key, value in data_dict.items():
if isinstance(value, Integer):
data_dict[key] = int(value)
elif isinstance(value, dict):
BenchConfig.recursive_resolve(value)
def to_dict(self):
dict_config = {
benchmark_name: {key: val for key, val in spec_config.__dict__.items()}
for benchmark_name, spec_config in self.__dict__.items()
}
BenchConfig.recursive_resolve(dict_config)
return dict_config
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/__main__.py | gpt_engineer/benchmark/__main__.py | """
Main entry point for the benchmarking tool.
This module provides a command-line interface for running benchmarks using Typer.
It allows users to specify the path to an agent, the benchmark(s) to run, and other
options such as verbosity.
Functions
---------
get_agent : function
Dynamically imports and returns the default configuration agent from the given path.
main : function
The main function that runs the specified benchmarks with the given agent.
Outputs the results to the console.
Attributes
----------
__name__ : str
The standard boilerplate for invoking the main function when the script is executed.
"""
import importlib
import os.path
import sys
from typing import Annotated, Optional
import typer
from langchain.globals import set_llm_cache
from langchain_community.cache import SQLiteCache
from gpt_engineer.applications.cli.main import load_env_if_needed
from gpt_engineer.benchmark.bench_config import BenchConfig
from gpt_engineer.benchmark.benchmarks.load import get_benchmark
from gpt_engineer.benchmark.run import export_yaml_results, print_results, run
app = typer.Typer(
context_settings={"help_option_names": ["-h", "--help"]}
) # creates a CLI app
def get_agent(path):
"""
Dynamically imports and returns the default configuration agent from the given path.
Parameters
----------
path : str
The file path to the module containing the default configuration agent.
Returns
-------
BaseAgent
An instance of the imported default configuration agent.
"""
# Dynamically import the python module at path
sys.path.append(os.path.dirname(path))
agent_module = importlib.import_module(path.replace("/", ".").replace(".py", ""))
return agent_module.default_config_agent()
@app.command(
help="""
Run any benchmark(s) against the specified agent.
\b
Currently available benchmarks are: apps and mbpp
"""
)
def main(
path_to_agent: Annotated[
str,
typer.Argument(
help="python file that contains a function called 'default_config_agent'"
),
],
bench_config: Annotated[
str, typer.Argument(help="optional task name in benchmark")
] = os.path.join(os.path.dirname(__file__), "default_bench_config.toml"),
yaml_output: Annotated[
Optional[str],
typer.Option(help="print results for each task", show_default=False),
] = None,
verbose: Annotated[
Optional[bool],
typer.Option(help="print results for each task", show_default=False),
] = False,
use_cache: Annotated[
Optional[bool],
typer.Option(
help="Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.",
show_default=False,
),
] = True,
):
"""
The main function that runs the specified benchmarks with the given agent and outputs the results to the console.
Parameters
----------
path_to_agent : str
The file path to the Python module that contains a function called 'default_config_agent'.
bench_config : str, default=default_bench_config.toml
Configuration file for choosing which benchmark problems to run. See default config for more details.
yaml_output: Optional[str], default=None
Pass a path to a yaml file to have results written to file.
verbose : Optional[bool], default=False
A flag to indicate whether to print results for each task.
use_cache : Optional[bool], default=True
Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.
Returns
-------
None
"""
if use_cache:
set_llm_cache(SQLiteCache(database_path=".langchain.db"))
load_env_if_needed()
config = BenchConfig.from_toml(bench_config)
print("using config file: " + bench_config)
benchmarks = list()
benchmark_results = dict()
for specific_config_name in vars(config):
specific_config = getattr(config, specific_config_name)
if hasattr(specific_config, "active"):
if specific_config.active:
benchmarks.append(specific_config_name)
for benchmark_name in benchmarks:
benchmark = get_benchmark(benchmark_name, config)
if len(benchmark.tasks) == 0:
print(
benchmark_name
+ " was skipped, since no tasks are specified. Increase the number of tasks in the config file at: "
+ bench_config
)
continue
agent = get_agent(path_to_agent)
results = run(agent, benchmark, verbose=verbose)
print(
f"\n--- Results for agent {path_to_agent}, benchmark: {benchmark_name} ---"
)
print_results(results)
print()
benchmark_results[benchmark_name] = {
"detailed": [result.to_dict() for result in results]
}
if yaml_output is not None:
export_yaml_results(yaml_output, benchmark_results, config.to_dict())
if __name__ == "__main__":
typer.run(main)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/__init__.py | gpt_engineer/benchmark/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/types.py | gpt_engineer/benchmark/types.py | """
Module defining types used in benchmarking.
This module contains dataclass definitions for various types used throughout the
benchmarking process, such as Assertable, Task, Benchmark, and TaskResult.
Classes:
Assertable:
Represents an object that can be asserted against in a benchmark task.
Assertion:
Type alias for a callable that takes an Assertable and returns a boolean.
Task:
Represents a single task within a benchmark, including its assertions.
Benchmark:
Represents a collection of tasks used to evaluate a model's performance.
TaskResult:
Represents the result of running a single task within a benchmark.
"""
from dataclasses import dataclass
from subprocess import Popen
from typing import Callable, Dict, Optional
from gpt_engineer.core.base_execution_env import BaseExecutionEnv
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
@dataclass
class Assertable:
"""
A class representing an object which can be asserted against.
Attributes:
files (FilesDict): The code files involved in the assertion.
env (BaseExecutionEnv): The execution environment in which the code is run.
process (Popen): The subprocess in which the code is run.
stdout (str): The standard output from the code execution.
stderr (str): The standard error from the code execution.
"""
files: FilesDict
env: BaseExecutionEnv
process: Optional[Popen]
stdout: Optional[str]
stderr: Optional[str]
Assertion = Callable[[Assertable], bool]
@dataclass
class Task:
name: str
initial_code: Optional[FilesDict]
command: Optional[str]
prompt: Prompt
assertions: Optional[Dict[str, Assertion]]
@dataclass
class Benchmark:
"""A benchmark is a collection of tasks that evaluate a model's performance."""
name: str
tasks: list[Task]
timeout: Optional[int] = None
@dataclass
class TaskResult:
task_name: str
assertion_results: dict[str, bool]
duration: float
# Returns success rate from 0.00 up to 1.00
@property
def success_rate(self) -> float:
if not self.assertion_results:
return 0.0
succeeded = len(
[result for result in self.assertion_results.values() if result is True]
)
return succeeded / len(self.assertion_results)
def to_dict(self) -> dict:
out_dict = {key: value for key, value in self.__dict__.items()}
out_dict["solved"] = self.success_rate
return out_dict
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/load.py | gpt_engineer/benchmark/benchmarks/load.py | """
Module for loading benchmarks.
This module provides a central point to access different benchmarks by name.
It maps benchmark names to their respective loading functions.
Functions
---------
get_benchmark : function
Retrieves a Benchmark object by name. Raises ValueError if the benchmark is unknown.
"""
from gpt_engineer.benchmark.bench_config import BenchConfig
from gpt_engineer.benchmark.benchmarks.apps.load import load_apps
from gpt_engineer.benchmark.benchmarks.gptme.load import load_gptme
from gpt_engineer.benchmark.benchmarks.mbpp.load import load_mbpp
from gpt_engineer.benchmark.types import Benchmark
BENCHMARKS = {
"gptme": load_gptme,
"apps": load_apps,
"mbpp": load_mbpp,
}
def get_benchmark(name: str, config: BenchConfig) -> Benchmark:
"""
Retrieves a Benchmark object by name. Raises ValueError if the benchmark is unknown.
Parameters
----------
name : str
The name of the benchmark to retrieve.
config : BenchConfig
Configuration object for the benchmarks.
Returns
-------
Benchmark
The Benchmark object corresponding to the given name.
Raises
------
ValueError
If the benchmark name is not found in the BENCHMARKS mapping.
"""
if name not in BENCHMARKS:
raise ValueError(f"Unknown benchmark {name}.")
return BENCHMARKS[name](config.__getattribute__(name))
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/apps/load.py | gpt_engineer/benchmark/benchmarks/apps/load.py | """
Module for loading APPS evaluation tasks.
This module provides functionality to load tasks for evaluating GPT-based models
on smaller, more focused tasks. It defines a set of tasks with predefined prompts
and assertions to benchmark the performance of AI models.
Functions
---------
load_apps : function
Loads the APPS benchmark, which consists of a series coding problems.
"""
from pathlib import Path
from subprocess import TimeoutExpired
from typing import Union
from datasets import Dataset, DatasetDict, load_dataset, load_from_disk
from gpt_engineer.benchmark.bench_config import AppsConfig
from gpt_engineer.benchmark.benchmarks.apps.problem import Problem
from gpt_engineer.benchmark.types import Assertable, Benchmark, Task
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
DATASET_PATH = Path(__file__).parent / "dataset"
class AppsAssertion:
def __init__(self, expected: str, command: str):
self.expected_output = self._format(expected)
self.command = command
def evaluate(self, assertable: Assertable) -> bool:
# Create new execution environment for every run to avoid side effects
env = DiskExecutionEnv()
env.upload(assertable.files)
pro = env.popen(self.command)
try:
stdout, stderr = pro.communicate(timeout=2)
stdout, stderr = stdout.decode("utf-8"), stderr.decode("utf-8")
except TimeoutExpired:
print("Execution Timeout")
return False
return self.expected_output in self._format(stdout)
def _format(self, string: str) -> str:
return string.replace(" ", "").replace("\n", "")
def _get_dataset() -> Union[Dataset, DatasetDict]:
try:
return load_from_disk(str(DATASET_PATH))
except FileNotFoundError:
print("Dataset not found locally, downloading...")
dataset = load_dataset("codeparrot/apps", trust_remote_code=True)
dataset.save_to_disk(str(DATASET_PATH))
return dataset
def load_apps(config: AppsConfig) -> Benchmark:
"""
Loads the APPS benchmark, which consists of a series coding problems.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the APPS evaluation.
"""
dataset = _get_dataset()
tasks = []
problems = list()
for dataset_type in ["test", "train"]:
problems += [
Problem(
id=problem["problem_id"],
question=problem["question"],
input_output=problem["input_output"],
starter_code=problem["starter_code"],
)
for index, problem in enumerate(dataset[dataset_type])
if (index < config.__getattribute__(dataset_type + "_end_index"))
and (index >= config.__getattribute__(dataset_type + "_start_index"))
]
for problem in problems:
prompt = Prompt(
problem.question
+ "\nThe program, including its inputs, should be run from the command "
"line like 'python main \"input1 input2 etc \"', with all inputs inside "
"the quotation marks. The program should not read inputs from stdin."
)
tasks.append(
Task(
name=str(problem.id),
initial_code=FilesDict({"main.py": problem.starter_code}),
command=None, # Explicitly setting `None` because each assertion specifies its command
prompt=prompt,
assertions={
f"correct output {i}": AppsAssertion(
expected=problem.outputs[i],
command="python main.py" + ' "' + problem.inputs[i] + '"',
).evaluate
for i in range(
min(len(problem.outputs), config.examples_per_problem)
)
},
)
)
return Benchmark(
name="apps",
tasks=tasks,
)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/apps/problems.py | gpt_engineer/benchmark/benchmarks/apps/problems.py | # TODO: Pick problems
# Temporary testing against these problems
PROBLEM_IDS = list(range(0, 50))
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/apps/problem.py | gpt_engineer/benchmark/benchmarks/apps/problem.py | import json
from dataclasses import dataclass
from functools import cached_property
from typing import List
@dataclass(frozen=True)
class Problem:
id: int
question: str
input_output: str
starter_code: str
@property
def inputs(self) -> List[str]:
return self._parsed_inputs_outputs["inputs"]
@property
def outputs(self) -> List[str]:
return self._parsed_inputs_outputs["outputs"]
@cached_property
def _parsed_inputs_outputs(self):
return json.loads(self.input_output.replace("\n", ""))
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/gptme/load.py | gpt_engineer/benchmark/benchmarks/gptme/load.py | """
Module for loading GPT-Me evaluation tasks.
This module provides functionality to load tasks for evaluating GPT-based models
on smaller, more focused tasks. It defines a set of tasks with predefined prompts
and assertions to benchmark the performance of AI models.
Functions
---------
load_gptme : function
Loads the GPT-Me benchmark, which consists of a series of tasks for evaluation.
"""
from gpt_engineer.benchmark.bench_config import GptmeConfig
from gpt_engineer.benchmark.types import Benchmark, Task
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
def load_gptme(config: GptmeConfig) -> Benchmark:
"""
Loads the GPT-Me benchmark, which consists of a series of tasks for evaluation.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the GPT-Me evaluation.
"""
return Benchmark(
name="gptme",
tasks=[
Task(
name="hello",
initial_code=FilesDict({"hello.py": "print('Hello, world!')"}),
command="python hello.py",
prompt=Prompt("Change the code in hello.py to print 'Hello, human!'"),
assertions={
"correct output": lambda assertable: assertable.stdout
== "Hello, human!\n",
"correct file": lambda assertable: assertable.files[
"hello.py"
].strip()
== "print('Hello, human!')",
},
),
Task(
name="hello-patch",
initial_code=FilesDict({"hello.py": "print('Hello, world!')"}),
command="python hello.py",
prompt=Prompt("Patch the code in hello.py to print 'Hello, human!'"),
assertions={
"correct output": lambda assertable: assertable.stdout
== "Hello, human!\n",
"correct file": lambda assertable: assertable.files[
"hello.py"
].strip()
== "print('Hello, human!')",
},
),
Task(
name="hello-ask",
initial_code=FilesDict({"hello.py": "print('Hello, world!')"}),
command="echo 'Erik' | python hello.py",
prompt=Prompt(
"modify hello.py to ask the user for their name and print 'Hello, <name>!'. don't try to execute it"
),
assertions={
"correct output": lambda assertable: "Hello, Erik!"
in assertable.stdout,
},
),
Task(
name="prime100",
initial_code=FilesDict(
{}
), # Empty dictionary since no initial code is provided
command="python prime.py",
prompt=Prompt(
"write a script prime.py that computes and prints the 100th prime number"
),
assertions={
"correct output": lambda assertable: "541"
in assertable.stdout.split(),
},
),
Task(
name="init-git",
initial_code=FilesDict(
{}
), # Empty dictionary since no initial code is provided
command="git status",
prompt=Prompt(
"initialize a git repository, write a main.py file, and commit it"
),
assertions={
"clean exit": lambda assertable: assertable.process.returncode == 0,
"clean working tree": lambda assertable: "nothing to commit, working tree clean"
in assertable.stdout,
"main.py exists": lambda assertable: "main.py" in assertable.files,
"we have a commit": lambda assertable: "No commits yet"
not in assertable.stdout,
},
),
],
)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/mbpp/load.py | gpt_engineer/benchmark/benchmarks/mbpp/load.py | """
Module for loading MBPP evaluation tasks.
This module provides functionality to load tasks for evaluating GPT-based models
on smaller, more focused tasks. It defines a set of tasks with predefined prompts
and assertions to benchmark the performance of AI models.
Functions
---------
load_mbpp : function
Loads the MBPP benchmark, which consists of a series coding problems.
"""
from pathlib import Path
from subprocess import TimeoutExpired
from typing import Union
from datasets import Dataset, DatasetDict, load_dataset, load_from_disk
from gpt_engineer.benchmark.bench_config import MbppConfig
from gpt_engineer.benchmark.benchmarks.mbpp.problem import Problem
from gpt_engineer.benchmark.types import Assertable, Benchmark, Task
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
DATASET_PATH = Path(__file__).parent / "dataset"
class MbppAssertion:
def __init__(self, assertion: str):
self.assertion = assertion
def evaluate(self, assertable: Assertable) -> bool:
generated_code = assertable.files["main.py"]
code_with_assertion = f"{generated_code}\n{self.assertion}"
# Create new execution environment for every run to avoid side effects
env = DiskExecutionEnv()
env.upload(FilesDict({"main.py": code_with_assertion}))
pro = env.popen("python main.py")
try:
stdout, stderr = pro.communicate(timeout=2)
stdout, stderr = stdout.decode("utf-8"), stderr.decode("utf-8")
except TimeoutExpired:
print("Execution Timeout")
return False
return not stderr
def _get_dataset() -> Union[Dataset, DatasetDict]:
try:
return load_from_disk(str(DATASET_PATH))
except FileNotFoundError:
print("Dataset not found locally, downloading...")
dataset = load_dataset("mbpp", "sanitized", trust_remote_code=True)
dataset.save_to_disk(str(DATASET_PATH))
return dataset
def load_mbpp(config: MbppConfig) -> Benchmark:
"""
Loads the MBPP benchmark, which consists of a series coding problems.
Returns
-------
Benchmark
A Benchmark object containing a list of Task objects for the MBPP evaluation.
"""
dataset = _get_dataset()
tasks = []
problems = []
for dataset_type in ["test", "train"]:
problems += [
Problem(
source_file=problem["source_file"],
task_id=problem["task_id"],
prompt=problem["prompt"],
code=problem["code"],
test_imports=problem["test_imports"],
test_list=problem["test_list"],
)
for index, problem in enumerate(dataset[dataset_type])
if index < config.__getattribute__(dataset_type + "_len")
]
for problem in problems:
prompt = Prompt(
problem.prompt
+ "Please extend given function without changing it's declaration including arguments."
)
tasks.append(
Task(
name=str(problem.task_id),
initial_code=FilesDict({"main.py": problem.starting_code}),
command=None, # Explicitly setting `None` because each assertion runs code
prompt=prompt,
assertions={
f"correct assertion {i}": MbppAssertion(
assertion=assertion
).evaluate
for i, assertion in enumerate(problem.test_list)
},
)
)
return Benchmark(
name="mbpp",
tasks=tasks,
)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/mbpp/problems.py | gpt_engineer/benchmark/benchmarks/mbpp/problems.py | # TODO: Pick problems
# Temporary testing against these problems
PROBLEM_IDS = range(0, 100)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/benchmark/benchmarks/mbpp/problem.py | gpt_engineer/benchmark/benchmarks/mbpp/problem.py | from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class Problem:
source_file: int
task_id: str
prompt: str
code: str
test_imports: str
test_list: List[str]
@property
def starting_code(self) -> str:
lines: List[str] = []
for line in self.code.split("\n"):
lines.append(line)
if line.startswith("def "):
lines.append("pass # TODO: Implement method\n")
break
return "\n".join(lines)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/__init__.py | gpt_engineer/applications/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/cli/learning.py | gpt_engineer/applications/cli/learning.py | """
The `learning` module is designed to facilitate the collection and storage of user feedback on the outputs generated by the GPT Engineer tool. It provides mechanisms for obtaining user consent, capturing user reviews, and storing this information for future analysis and enhancement of the tool's performance.
Classes
-------
Review : dataclass
Represents a user's review of the generated code, including whether it ran, was perfect, was useful, and any additional comments.
Learning : dataclass
Encapsulates the metadata and feedback collected during a session of using the GPT Engineer tool, including the prompt, model, temperature, configuration, logs, session identifier, user review, and timestamp.
Functions
---------
human_review_input() -> Optional[Review]
Interactively gathers feedback from the user regarding the performance of generated code and returns a Review instance.
check_collection_consent() -> bool
Checks if the user has previously given consent to store their data and, if not, asks for it.
ask_collection_consent() -> bool
Prompts the user for consent to store their data for the purpose of improving GPT Engineer.
extract_learning(prompt: Prompt, model: str, temperature: float, config: Tuple[str, ...], memory: DiskMemory, review: Review) -> Learning
Extracts feedback and session details to create a Learning instance based on the provided parameters.
get_session() -> str
Retrieves a unique identifier for the current user session, creating one if it does not exist.
Constants
---------
TERM_CHOICES : tuple
Terminal color choices for user interactive prompts, formatted with termcolor for readability.
"""
import json
import random
import tempfile
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Optional, Tuple
from dataclasses_json import dataclass_json
from termcolor import colored
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.prompt import Prompt
@dataclass_json
@dataclass
class Review:
"""
A dataclass that represents a user's review of the generated code.
Attributes
----------
ran : Optional[bool]
Indicates whether the generated code ran without errors.
perfect : Optional[bool]
Indicates whether the generated code met all the user's requirements.
works : Optional[bool]
Indicates whether the generated code was useful, even if not perfect.
comments : str
Any additional comments provided by the user.
raw : str
A raw string representation of the user's responses.
"""
ran: Optional[bool]
perfect: Optional[bool]
works: Optional[bool]
comments: str
raw: str
@dataclass_json
@dataclass
class Learning:
"""
A dataclass that encapsulates the learning data collected during a GPT Engineer session.
Attributes
----------
prompt : str
A JSON string representing the prompt provided to GPT Engineer.
model : str
The name of the model used during the session.
temperature : float
The temperature setting used for the model's responses.
config : str
A JSON string representing the configuration settings for the session.
logs : str
A JSON string representing the logs of the session.
session : str
A unique identifier for the user session.
review : Optional[Review]
The user's review of the generated code.
timestamp : str
The UTC timestamp when the learning data was created.
version : str
The version of the learning data schema.
"""
prompt: str
model: str
temperature: float
config: str
logs: str
session: str
review: Optional[Review]
timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
version: str = "0.3"
TERM_CHOICES = (
colored("y", "green")
+ "/"
+ colored("n", "red")
+ "/"
+ colored("u", "yellow")
+ "(ncertain): "
)
def human_review_input() -> Optional[Review]:
"""
Interactively prompts the user to review the generated code and returns their feedback encapsulated in a Review object.
This function will first check if the user has given consent to collect their feedback. If consent is given, it will ask the user a series of questions about the generated code's performance and capture their responses.
Returns
-------
Optional[Review]
A Review object containing the user's feedback, or None if consent is not given.
"""
print()
if not check_collection_consent():
return None
print()
print(
colored("To help gpt-engineer learn, please answer 3 questions:", "light_green")
)
print()
ran = input("Did the generated code run at all? " + TERM_CHOICES)
ran = ask_for_valid_input(ran)
if ran == "y":
perfect = input(
"Did the generated code do everything you wanted? " + TERM_CHOICES
)
perfect = ask_for_valid_input(perfect)
if perfect != "y":
useful = input("Did the generated code do anything useful? " + TERM_CHOICES)
useful = ask_for_valid_input(useful)
else:
useful = ""
else:
perfect = ""
useful = ""
if perfect != "y":
comments = input(
"If you have time, please explain what was not working "
+ colored("(ok to leave blank)\n", "light_green")
)
else:
comments = ""
return Review(
raw=", ".join([ran, perfect, useful]),
ran={"y": True, "n": False, "u": None, "": None}[ran],
works={"y": True, "n": False, "u": None, "": None}[useful],
perfect={"y": True, "n": False, "u": None, "": None}[perfect],
comments=comments,
)
def ask_for_valid_input(ran):
while ran not in ("y", "n", "u"):
ran = input("Invalid input. Please enter y, n, or u: ")
return ran
def check_collection_consent() -> bool:
"""
Checks if the user has previously given consent to store their data for feedback collection.
This function looks for a file that stores the user's consent status. If the file exists and contains 'true', consent is assumed. If the file does not exist or does not contain 'true', the function will prompt the user for consent.
Returns
-------
bool
True if the user has given consent, False otherwise.
"""
path = Path(".gpte_consent")
if path.exists() and path.read_text() == "true":
return True
else:
return ask_collection_consent()
def ask_collection_consent() -> bool:
"""
Asks the user for their consent to store their data for the purpose of improving the GPT Engineer tool.
The user's response is recorded in a file for future reference. If the user consents, the function will write 'true' to the file. If the user does not consent, no data will be collected, and the function will not modify the file.
Returns
-------
bool
True if the user consents, False otherwise.
"""
answer = input(
"Is it ok if we store your prompts to help improve GPT Engineer? (y/n)"
)
while answer.lower() not in ("y", "n"):
answer = input("Invalid input. Please enter y or n: ")
if answer.lower() == "y":
path = Path(".gpte_consent")
path.write_text("true")
print(colored("Thank you️", "light_green"))
print()
print(
"(If you no longer wish to participate in data collection, delete the file .gpte_consent)"
)
return True
else:
print(
colored(
"No worries! GPT Engineer will not collect your prompts. ❤️",
"light_green",
)
)
return False
def extract_learning(
prompt: Prompt,
model: str,
temperature: float,
config: Tuple[str, ...],
memory: DiskMemory,
review: Review,
) -> Learning:
"""
Constructs a Learning object containing the session's metadata and user feedback.
Parameters
----------
prompt : str
The initial prompt provided to the GPT Engineer.
model : str
The name of the model used during the session.
temperature : float
The temperature setting used for the model's responses.
config : Tuple[str, ...]
A tuple representing the configuration settings for the session.
memory : DiskMemory
An object representing the disk memory used during the session.
review : Review
The user's review of the generated code.
Returns
-------
Learning
An instance of Learning containing all the session details and user feedback.
"""
return Learning(
prompt=prompt.to_json(),
model=model,
temperature=temperature,
config=json.dumps(config),
session=get_session(),
logs=memory.to_json(),
review=review,
)
def get_session() -> str:
"""
Retrieves or generates a unique identifier for the current user session.
This function attempts to read a unique user ID from a temporary file. If the file does not exist, it generates a new random ID, writes it to the file, and returns it. This ID is used to uniquely identify the user's session.
Returns
-------
str
A unique identifier for the user session.
"""
path = Path(tempfile.gettempdir()) / "gpt_engineer_user_id.txt"
try:
if path.exists():
user_id = path.read_text()
else:
# random uuid:
user_id = str(random.randint(0, 2**32))
path.write_text(user_id)
return user_id
except IOError:
return "ephemeral_" + str(random.randint(0, 2**32))
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/cli/main.py | gpt_engineer/applications/cli/main.py | """
Entrypoint for the CLI tool.
This module serves as the entry point for a command-line interface (CLI) tool.
It is designed to interact with OpenAI's language models.
The module provides functionality to:
- Load necessary environment variables,
- Configure various parameters for the AI interaction,
- Manage the generation or improvement of code projects.
Main Functionality
------------------
- Load environment variables required for OpenAI API interaction.
- Parse user-specified parameters for project configuration and AI behavior.
- Facilitate interaction with AI models, databases, and archival processes.
Parameters
----------
None
Notes
-----
- The `OPENAI_API_KEY` must be set in the environment or provided in a `.env` file within the working directory.
- The default project path is `projects/example`.
- When using the `azure_endpoint` parameter, provide the Azure OpenAI service endpoint URL.
"""
import difflib
import json
import logging
import os
import platform
import subprocess
import sys
from pathlib import Path
import openai
import typer
from dotenv import load_dotenv
from langchain.globals import set_llm_cache
from langchain_community.cache import SQLiteCache
from termcolor import colored
from gpt_engineer.applications.cli.cli_agent import CliAgent
from gpt_engineer.applications.cli.collect import collect_and_send_human_review
from gpt_engineer.applications.cli.file_selector import FileSelector
from gpt_engineer.core.ai import AI, ClipboardAI
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.file_store import FileStore
from gpt_engineer.core.default.paths import PREPROMPTS_PATH, memory_path
from gpt_engineer.core.default.steps import (
execute_entrypoint,
gen_code,
handle_improve_mode,
improve_fn as improve_fn,
)
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.git import stage_uncommitted_to_git
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
from gpt_engineer.tools.custom_steps import clarified_gen, lite_gen, self_heal
app = typer.Typer(
context_settings={"help_option_names": ["-h", "--help"]}
) # creates a CLI app
def load_env_if_needed():
"""
Load environment variables if the OPENAI_API_KEY is not already set.
This function checks if the OPENAI_API_KEY environment variable is set,
and if not, it attempts to load it from a .env file in the current working
directory. It then sets the openai.api_key for use in the application.
"""
# We have all these checks for legacy reasons...
if os.getenv("OPENAI_API_KEY") is None:
load_dotenv()
if os.getenv("OPENAI_API_KEY") is None:
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"))
openai.api_key = os.getenv("OPENAI_API_KEY")
if os.getenv("ANTHROPIC_API_KEY") is None:
load_dotenv()
if os.getenv("ANTHROPIC_API_KEY") is None:
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"))
def concatenate_paths(base_path, sub_path):
# Compute the relative path from base_path to sub_path
relative_path = os.path.relpath(sub_path, base_path)
# If the relative path is not in the parent directory, use the original sub_path
if not relative_path.startswith(".."):
return sub_path
# Otherwise, concatenate base_path and sub_path
return os.path.normpath(os.path.join(base_path, sub_path))
def load_prompt(
input_repo: DiskMemory,
improve_mode: bool,
prompt_file: str,
image_directory: str,
entrypoint_prompt_file: str = "",
) -> Prompt:
"""
Load or request a prompt from the user based on the mode.
Parameters
----------
input_repo : DiskMemory
The disk memory object where prompts and other data are stored.
improve_mode : bool
Flag indicating whether the application is in improve mode.
Returns
-------
str
The loaded or inputted prompt.
"""
if os.path.isdir(prompt_file):
raise ValueError(
f"The path to the prompt, {prompt_file}, already exists as a directory. No prompt can be read from it. Please specify a prompt file using --prompt_file"
)
prompt_str = input_repo.get(prompt_file)
if prompt_str:
print(colored("Using prompt from file:", "green"), prompt_file)
print(prompt_str)
else:
if not improve_mode:
prompt_str = input(
"\nWhat application do you want gpt-engineer to generate?\n"
)
else:
prompt_str = input("\nHow do you want to improve the application?\n")
if entrypoint_prompt_file == "":
entrypoint_prompt = ""
else:
full_entrypoint_prompt_file = concatenate_paths(
input_repo.path, entrypoint_prompt_file
)
if os.path.isfile(full_entrypoint_prompt_file):
entrypoint_prompt = input_repo.get(full_entrypoint_prompt_file)
else:
raise ValueError("The provided file at --entrypoint-prompt does not exist")
if image_directory == "":
return Prompt(prompt_str, entrypoint_prompt=entrypoint_prompt)
full_image_directory = concatenate_paths(input_repo.path, image_directory)
if os.path.isdir(full_image_directory):
if len(os.listdir(full_image_directory)) == 0:
raise ValueError("The provided --image_directory is empty.")
image_repo = DiskMemory(full_image_directory)
return Prompt(
prompt_str,
image_repo.get(".").to_dict(),
entrypoint_prompt=entrypoint_prompt,
)
else:
raise ValueError("The provided --image_directory is not a directory.")
def get_preprompts_path(use_custom_preprompts: bool, input_path: Path) -> Path:
"""
Get the path to the preprompts, using custom ones if specified.
Parameters
----------
use_custom_preprompts : bool
Flag indicating whether to use custom preprompts.
input_path : Path
The path to the project directory.
Returns
-------
Path
The path to the directory containing the preprompts.
"""
original_preprompts_path = PREPROMPTS_PATH
if not use_custom_preprompts:
return original_preprompts_path
custom_preprompts_path = input_path / "preprompts"
if not custom_preprompts_path.exists():
custom_preprompts_path.mkdir()
for file in original_preprompts_path.glob("*"):
if not (custom_preprompts_path / file.name).exists():
(custom_preprompts_path / file.name).write_text(file.read_text())
return custom_preprompts_path
def compare(f1: FilesDict, f2: FilesDict):
def colored_diff(s1, s2):
lines1 = s1.splitlines()
lines2 = s2.splitlines()
diff = difflib.unified_diff(lines1, lines2, lineterm="")
RED = "\033[38;5;202m"
GREEN = "\033[92m"
RESET = "\033[0m"
colored_lines = []
for line in diff:
if line.startswith("+"):
colored_lines.append(GREEN + line + RESET)
elif line.startswith("-"):
colored_lines.append(RED + line + RESET)
else:
colored_lines.append(line)
return "\n".join(colored_lines)
for file in sorted(set(f1) | set(f2)):
diff = colored_diff(f1.get(file, ""), f2.get(file, ""))
if diff:
print(f"Changes to {file}:")
print(diff)
def prompt_yesno() -> bool:
TERM_CHOICES = colored("y", "green") + "/" + colored("n", "red") + " "
while True:
response = input(TERM_CHOICES).strip().lower()
if response in ["y", "yes"]:
return True
if response in ["n", "no"]:
break
print("Please respond with 'y' or 'n'")
def get_system_info():
system_info = {
"os": platform.system(),
"os_version": platform.version(),
"architecture": platform.machine(),
"python_version": sys.version,
"packages": format_installed_packages(get_installed_packages()),
}
return system_info
def get_installed_packages():
try:
result = subprocess.run(
[sys.executable, "-m", "pip", "list", "--format=json"],
capture_output=True,
text=True,
)
packages = json.loads(result.stdout)
return {pkg["name"]: pkg["version"] for pkg in packages}
except Exception as e:
return str(e)
def format_installed_packages(packages):
return "\n".join([f"{name}: {version}" for name, version in packages.items()])
@app.command(
help="""
GPT-engineer lets you:
\b
- Specify a software in natural language
- Sit back and watch as an AI writes and executes the code
- Ask the AI to implement improvements
"""
)
def main(
project_path: str = typer.Argument(".", help="path"),
model: str = typer.Option(
os.environ.get("MODEL_NAME", "gpt-4o"), "--model", "-m", help="model id string"
),
temperature: float = typer.Option(
0.1,
"--temperature",
"-t",
help="Controls randomness: lower values for more focused, deterministic outputs",
),
improve_mode: bool = typer.Option(
False,
"--improve",
"-i",
help="Improve an existing project by modifying the files.",
),
lite_mode: bool = typer.Option(
False,
"--lite",
"-l",
help="Lite mode: run a generation using only the main prompt.",
),
clarify_mode: bool = typer.Option(
False,
"--clarify",
"-c",
help="Clarify mode - discuss specification with AI before implementation.",
),
self_heal_mode: bool = typer.Option(
False,
"--self-heal",
"-sh",
help="Self-heal mode - fix the code by itself when it fails.",
),
azure_endpoint: str = typer.Option(
"",
"--azure",
"-a",
help="""Endpoint for your Azure OpenAI Service (https://xx.openai.azure.com).
In that case, the given model is the deployment name chosen in the Azure AI Studio.""",
),
use_custom_preprompts: bool = typer.Option(
False,
"--use-custom-preprompts",
help="""Use your project's custom preprompts instead of the default ones.
Copies all original preprompts to the project's workspace if they don't exist there.""",
),
llm_via_clipboard: bool = typer.Option(
False,
"--llm-via-clipboard",
help="Use the clipboard to communicate with the AI.",
),
verbose: bool = typer.Option(
False, "--verbose", "-v", help="Enable verbose logging for debugging."
),
debug: bool = typer.Option(
False, "--debug", "-d", help="Enable debug mode for debugging."
),
prompt_file: str = typer.Option(
"prompt",
"--prompt_file",
help="Relative path to a text file containing a prompt.",
),
entrypoint_prompt_file: str = typer.Option(
"",
"--entrypoint_prompt",
help="Relative path to a text file containing a file that specifies requirements for you entrypoint.",
),
image_directory: str = typer.Option(
"",
"--image_directory",
help="Relative path to a folder containing images.",
),
use_cache: bool = typer.Option(
False,
"--use_cache",
help="Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.",
),
skip_file_selection: bool = typer.Option(
False,
"--skip-file-selection",
"-s",
help="Skip interactive file selection in improve mode and use the generated TOML file directly.",
),
no_execution: bool = typer.Option(
False,
"--no_execution",
help="Run setup but to not call LLM or write any code. For testing purposes.",
),
sysinfo: bool = typer.Option(
False,
"--sysinfo",
help="Output system information for debugging",
),
diff_timeout: int = typer.Option(
3,
"--diff_timeout",
help="Diff regexp timeout. Default: 3. Increase if regexp search timeouts.",
),
):
"""
The main entry point for the CLI tool that generates or improves a project.
This function sets up the CLI tool, loads environment variables, initializes
the AI, and processes the user's request to generate or improve a project
based on the provided arguments.
Parameters
----------
project_path : str
The file path to the project directory.
model : str
The model ID string for the AI.
temperature : float
The temperature setting for the AI's responses.
improve_mode : bool
Flag indicating whether to improve an existing project.
lite_mode : bool
Flag indicating whether to run in lite mode.
clarify_mode : bool
Flag indicating whether to discuss specifications with AI before implementation.
self_heal_mode : bool
Flag indicating whether to enable self-healing mode.
azure_endpoint : str
The endpoint for Azure OpenAI services.
use_custom_preprompts : bool
Flag indicating whether to use custom preprompts.
prompt_file : str
Relative path to a text file containing a prompt.
entrypoint_prompt_file: str
Relative path to a text file containing a file that specifies requirements for you entrypoint.
image_directory: str
Relative path to a folder containing images.
use_cache: bool
Speeds up computations and saves tokens when running the same prompt multiple times by caching the LLM response.
verbose : bool
Flag indicating whether to enable verbose logging.
skip_file_selection: bool
Skip interactive file selection in improve mode and use the generated TOML file directly
no_execution: bool
Run setup but to not call LLM or write any code. For testing purposes.
sysinfo: bool
Flag indicating whether to output system information for debugging.
Returns
-------
None
"""
if debug:
import pdb
sys.excepthook = lambda *_: pdb.pm()
if sysinfo:
sys_info = get_system_info()
for key, value in sys_info.items():
print(f"{key}: {value}")
raise typer.Exit()
# Validate arguments
if improve_mode and (clarify_mode or lite_mode):
typer.echo("Error: Clarify and lite mode are not compatible with improve mode.")
raise typer.Exit(code=1)
# Set up logging
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO)
if use_cache:
set_llm_cache(SQLiteCache(database_path=".langchain.db"))
if improve_mode:
assert not (
clarify_mode or lite_mode
), "Clarify and lite mode are not active for improve mode"
load_env_if_needed()
if llm_via_clipboard:
ai = ClipboardAI()
else:
ai = AI(
model_name=model,
temperature=temperature,
azure_endpoint=azure_endpoint,
)
path = Path(project_path)
print("Running gpt-engineer in", path.absolute(), "\n")
prompt = load_prompt(
DiskMemory(path),
improve_mode,
prompt_file,
image_directory,
entrypoint_prompt_file,
)
# todo: if ai.vision is false and not llm_via_clipboard - ask if they would like to use gpt-4-vision-preview instead? If so recreate AI
if not ai.vision:
prompt.image_urls = None
# configure generation function
if clarify_mode:
code_gen_fn = clarified_gen
elif lite_mode:
code_gen_fn = lite_gen
else:
code_gen_fn = gen_code
# configure execution function
if self_heal_mode:
execution_fn = self_heal
else:
execution_fn = execute_entrypoint
preprompts_holder = PrepromptsHolder(
get_preprompts_path(use_custom_preprompts, Path(project_path))
)
memory = DiskMemory(memory_path(project_path))
memory.archive_logs()
execution_env = DiskExecutionEnv()
agent = CliAgent.with_default_config(
memory,
execution_env,
ai=ai,
code_gen_fn=code_gen_fn,
improve_fn=improve_fn,
process_code_fn=execution_fn,
preprompts_holder=preprompts_holder,
)
files = FileStore(project_path)
if not no_execution:
if improve_mode:
files_dict_before, is_linting = FileSelector(project_path).ask_for_files(
skip_file_selection=skip_file_selection
)
# lint the code
if is_linting:
files_dict_before = files.linting(files_dict_before)
files_dict = handle_improve_mode(
prompt, agent, memory, files_dict_before, diff_timeout=diff_timeout
)
if not files_dict or files_dict_before == files_dict:
print(
f"No changes applied. Could you please upload the debug_log_file.txt in {memory.path}/logs folder in a github issue?"
)
else:
print("\nChanges to be made:")
compare(files_dict_before, files_dict)
print()
print(colored("Do you want to apply these changes?", "light_green"))
if not prompt_yesno():
files_dict = files_dict_before
else:
files_dict = agent.init(prompt)
# collect user feedback if user consents
config = (code_gen_fn.__name__, execution_fn.__name__)
collect_and_send_human_review(prompt, model, temperature, config, memory)
stage_uncommitted_to_git(path, files_dict, improve_mode)
files.push(files_dict)
if ai.token_usage_log.is_openai_model():
print("Total api cost: $ ", ai.token_usage_log.usage_cost())
elif os.getenv("LOCAL_MODEL"):
print("Total api cost: $ 0.0 since we are using local LLM.")
else:
print("Total tokens used: ", ai.token_usage_log.total_tokens())
if __name__ == "__main__":
app()
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/cli/file_selector.py | gpt_engineer/applications/cli/file_selector.py | """
file_selector.py
This module offers interactive file selection for projects. Leveraging a terminal-based,
tree-structured display, users can navigate and select files for editing or processing.
It integrates with system editors for direct file modification and supports saving
selections for later use. Designed for efficient workflow enhancement in file-intensive
environments, it offers customizable file filtering and seamless editor integration.
Key Components:
- FileSelector: Manages file selection and interaction.
- DisplayablePath: Provides a structured view of file paths.
Usage:
Typically used in project setup or management phases for selecting specific files.
It operates within the GPT-Engineer environment, relying on core functionalities for
file handling and persistence.
"""
import fnmatch
import os
import subprocess
from pathlib import Path
from typing import Any, Dict, Generator, List, Union
import toml
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.paths import metadata_path
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.git import filter_by_gitignore, is_git_repo
class FileSelector:
"""
Manages file selection and interaction within a project directory.
This class provides methods to interactively select files from the terminal,
save selections for later use, and integrate with system editors for direct
file modification.
Attributes
----------
IGNORE_FOLDERS : set
A set of directory names to ignore during file selection.
FILE_LIST_NAME : str
The name of the file that stores the selected files list.
COMMENT : str
The comment string to be added to the top of the file selection list.
"""
IGNORE_FOLDERS = {"site-packages", "node_modules", "venv", "__pycache__"}
FILE_LIST_NAME = "file_selection.toml"
COMMENT = (
"# Remove '#' to select a file or turn off linting.\n\n"
"# Linting with BLACK (Python) enhances code suggestions from LLMs. "
"To disable linting, uncomment the relevant option in the linting settings.\n\n"
"# gpt-engineer can only read selected files. "
"Including irrelevant files will degrade performance, "
"cost additional tokens and potentially overflow token limit.\n\n"
)
LINTING_STRING = '[linting]\n# "linting" = "off"\n\n'
is_linting = True
def __init__(self, project_path: Union[str, Path]):
"""
Initializes the FileSelector with a given project path.
Parameters
----------
project_path : Union[str, Path]
The path to the project directory where file selection is to be performed.
"""
self.project_path = project_path
self.metadata_db = DiskMemory(metadata_path(self.project_path))
self.toml_path = self.metadata_db.path / self.FILE_LIST_NAME
def ask_for_files(self, skip_file_selection=False) -> tuple[FilesDict, bool]:
"""
Prompts the user to select files for context improvement.
This method supports selection from the terminal or using a previously saved list.
In test mode, it retrieves files from a predefined TOML configuration.
Returns
-------
FilesDict
A dictionary with file paths as keys and file contents as values.
"""
if os.getenv("GPTE_TEST_MODE") or skip_file_selection:
# In test mode, retrieve files from a predefined TOML configuration
# also get from toml if skip_file_selector is active
assert self.FILE_LIST_NAME in self.metadata_db
selected_files = self.get_files_from_toml(self.project_path, self.toml_path)
else:
# Otherwise, use the editor file selector for interactive selection
if self.FILE_LIST_NAME in self.metadata_db:
print(
f"File list detected at {self.toml_path}. Edit or delete it if you want to select new files."
)
selected_files = self.editor_file_selector(self.project_path, False)
else:
selected_files = self.editor_file_selector(self.project_path, True)
content_dict = {}
for file_path in selected_files:
# selected files contains paths that are relative to the project path
try:
# to open the file we need the path from the cwd
with open(
Path(self.project_path) / file_path, "r", encoding="utf-8"
) as content:
content_dict[str(file_path)] = content.read()
except FileNotFoundError:
print(f"Warning: File not found {file_path}")
except UnicodeDecodeError:
print(f"Warning: File not UTF-8 encoded {file_path}, skipping")
return FilesDict(content_dict), self.is_linting
def editor_file_selector(
self, input_path: Union[str, Path], init: bool = True
) -> List[str]:
"""
Provides an interactive file selection interface using a .toml file.
Parameters
----------
input_path : Union[str, Path]
The path where file selection is to be performed.
init : bool, optional
Indicates whether to initialize the .toml file with the file tree.
Returns
-------
List[str]
A list of strings representing the paths of selected files.
"""
root_path = Path(input_path)
tree_dict = {}
toml_file = DiskMemory(metadata_path(input_path)).path / "file_selection.toml"
# Define the toml file path
# Initialize .toml file with file tree if in initial state
if init:
tree_dict = {x: "selected" for x in self.get_current_files(root_path)}
s = toml.dumps({"files": tree_dict})
# add comments on all lines that match = "selected"
s = "\n".join(
[
"# " + line if line.endswith(' = "selected"') else line
for line in s.split("\n")
]
)
# Write to the toml file
with open(toml_file, "w") as f:
f.write(self.COMMENT)
f.write(self.LINTING_STRING)
f.write(s)
else:
# Load existing files from the .toml configuration
all_files = self.get_current_files(root_path)
s = toml.dumps({"files": {x: "selected" for x in all_files}})
# get linting status from the toml file
with open(toml_file, "r") as file:
linting_status = toml.load(file)
if (
"linting" in linting_status
and linting_status["linting"].get("linting", "").lower() == "off"
):
self.is_linting = False
self.LINTING_STRING = '[linting]\n"linting" = "off"\n\n'
print("\nLinting is disabled")
with open(toml_file, "r") as file:
selected_files = toml.load(file)
lines = s.split("\n")
s = "\n".join(
lines[:1]
+ [
line
if line.split(" = ")[0].strip('"') in selected_files["files"]
else "# " + line
for line in lines[1:]
]
)
# Write the merged list back to the .toml for user review and modification
with open(toml_file, "w") as file:
file.write(self.COMMENT) # Ensure to write the comment
file.write(self.LINTING_STRING)
file.write(s)
print(
"Please select and deselect (add # in front) files, save it, and close it to continue..."
)
self.open_with_default_editor(
toml_file
) # Open the .toml file in the default editor for user modification
return self.get_files_from_toml(
input_path, toml_file
) # Return the list of selected files after user edits
def open_with_default_editor(self, file_path: Union[str, Path]):
"""
Opens a file with the system's default text editor.
Parameters
----------
file_path : Union[str, Path]
The path to the file to be opened in the text editor.
"""
editors = [
"gedit",
"notepad",
"nvim",
"write",
"nano",
"vim",
"emacs",
] # Putting the beginner-friendly text editor forward
chosen_editor = os.environ.get("EDITOR")
# Try the preferred editor first, then fallback to common editors
if chosen_editor:
try:
subprocess.run([chosen_editor, file_path])
return
except Exception:
pass
for editor in editors:
try:
subprocess.run([editor, file_path])
return
except Exception:
continue
print("No suitable text editor found. Please edit the file manually.")
def is_utf8(self, file_path: Union[str, Path]) -> bool:
"""
Checks if the file at the given path is UTF-8 encoded.
Parameters
----------
file_path : Union[str, Path]
The path to the file to be checked.
Returns
-------
bool
True if the file is UTF-8 encoded, False otherwise.
"""
try:
with open(file_path, "rb") as file:
file.read().decode("utf-8")
return True
except UnicodeDecodeError:
return False
def get_files_from_toml(
self, input_path: Union[str, Path], toml_file: Union[str, Path]
) -> List[str]:
"""
Retrieves a list of selected files from a .toml configuration file.
Parameters
----------
input_path : Union[str, Path]
The path where file selection was performed.
toml_file : Union[str, Path]
The path to the .toml file containing the file selection.
Returns
-------
List[str]
A list of strings representing the paths of selected files.
Raises
------
Exception
If no files are selected in the .toml file.
"""
selected_files = []
edited_tree = toml.load(toml_file) # Load the edited .toml file
# check if users have disabled linting or not
if (
"linting" in edited_tree
and edited_tree["linting"].get("linting", "").lower() == "off"
):
self.is_linting = False
print("\nLinting is disabled")
else:
self.is_linting = True
# Iterate through the files in the .toml and append selected files to the list
for file, _ in edited_tree["files"].items():
selected_files.append(file)
# Ensure that at least one file is selected, or raise an exception
if not selected_files:
raise Exception(
"No files were selected. Please select at least one file to proceed."
)
print(f"\nYou have selected the following files:\n{input_path}")
project_path = Path(input_path).resolve()
selected_paths = set(
project_path.joinpath(file).resolve(strict=False) for file in selected_files
)
for displayable_path in DisplayablePath.make_tree(project_path):
if displayable_path.path in selected_paths:
p = displayable_path
while p.parent and p.parent.path not in selected_paths:
selected_paths.add(p.parent.path)
p = p.parent
try:
for displayable_path in DisplayablePath.make_tree(project_path):
if displayable_path.path in selected_paths:
print(displayable_path.displayable())
except FileNotFoundError:
print("Specified path does not exist: ", project_path)
except Exception as e:
print("An error occurred while trying to display the file tree:", e)
print("\n")
return selected_files
def merge_file_lists(
self, existing_files: Dict[str, Any], new_files: Dict[str, Any]
) -> Dict[str, Any]:
"""
Merges two lists of files, preserving the selection status.
Parameters
----------
existing_files : Dict[str, Any]
The dictionary of existing files with their properties.
new_files : Dict[str, Any]
The dictionary of new files with their properties.
Returns
-------
Dict[str, Any]
The updated dictionary of files after merging.
"""
# Update the existing files with any new files or changes
for file, properties in new_files.items():
if file not in existing_files:
existing_files[file] = properties # Add new files as unselected
# If you want to update other properties of existing files, you can do so here
return existing_files
def should_filter_file(self, file_path: Path, filters: List[str]) -> bool:
"""
Determines if a file should be ignored based on .gitignore rules.
"""
for f in filters:
if fnmatch.fnmatchcase(str(file_path), f):
return True
return False
def get_current_files(self, project_path: Union[str, Path]) -> List[str]:
"""
Generates a list of all files in the project directory. Will use .gitignore files if project_path is a git repository.
Parameters
----------
project_path : Union[str, Path]
The path to the project directory.
Returns
-------
List[str]
A list of strings representing the relative paths of all files in the project directory.
"""
all_files = []
project_path = Path(
project_path
).resolve() # Ensure path is absolute and resolved
file_list = project_path.glob("**/*")
for path in file_list: # Recursively list all files
if path.is_file():
relpath = path.relative_to(project_path)
parts = relpath.parts
if any(part.startswith(".") for part in parts):
continue # Skip hidden files
if any(part in self.IGNORE_FOLDERS for part in parts):
continue
if relpath.name == "prompt":
continue # Skip files named 'prompt'
all_files.append(str(relpath))
if is_git_repo(project_path) and "projects" not in project_path.parts:
all_files = filter_by_gitignore(project_path, all_files)
return sorted(all_files, key=lambda x: Path(x).as_posix())
class DisplayablePath(object):
"""
Represents and displays a file system path in a tree-like structure.
This class is used to visually represent the structure of directories and files
in a way that is similar to a file explorer's tree view.
"""
display_filename_prefix_middle = "├── "
display_filename_prefix_last = "└── "
display_parent_prefix_middle = " "
display_parent_prefix_last = "│ "
def __init__(
self, path: Union[str, Path], parent_path: "DisplayablePath", is_last: bool
):
"""
Initializes a DisplayablePath object with a given path and parent.
Parameters
----------
path : Union[str, Path]
The file system path to be displayed.
parent_path : DisplayablePath
The parent path in the tree structure.
is_last : bool
Indicates whether this is the last sibling in the tree structure.
"""
self.depth = 0
self.path = Path(str(path))
self.parent = parent_path
self.is_last = is_last
if self.parent:
self.depth = self.parent.depth + 1 # Increment depth if it has a parent
@property
def display_name(self) -> str:
"""
Get the display name of the file or directory.
"""
if self.path.is_dir():
return self.path.name + "/"
return self.path.name
@classmethod
def make_tree(
cls, root: Union[str, Path], parent=None, is_last=False, criteria=None
) -> Generator["DisplayablePath", None, None]:
"""
Creates a tree of DisplayablePath objects from a root directory.
Parameters
----------
root : Union[str, Path]
The root directory from which to start creating the tree.
parent : DisplayablePath, optional
The parent path in the tree structure.
is_last : bool, optional
Indicates whether this is the last sibling in the tree structure.
criteria : callable, optional
A function to filter the paths included in the tree.
Yields
------
DisplayablePath
The next DisplayablePath object in the tree.
"""
root = Path(str(root)) # Ensure root is a Path object
criteria = criteria or cls._default_criteria
displayable_root = cls(root, parent, is_last)
yield displayable_root
if root.is_dir(): # Check if root is a directory before iterating
children = sorted(
list(path for path in root.iterdir() if criteria(path)),
key=lambda s: str(s).lower(),
)
count = 1
for path in children:
is_last = count == len(children)
yield from cls.make_tree(
path, parent=displayable_root, is_last=is_last, criteria=criteria
)
count += 1
@classmethod
def _default_criteria(cls, path: Path) -> bool:
"""
The default criteria function to filter the paths.
"""
return True
def displayable(self) -> str:
"""
Returns a string representation of the path for display in a tree-like structure.
Returns
-------
str
The displayable string representation of the file or directory.
"""
if self.parent is None:
return self.display_name
_filename_prefix = (
self.display_filename_prefix_last
if self.is_last
else self.display_filename_prefix_middle
)
parts = ["{!s} {!s}".format(_filename_prefix, self.display_name)]
parent = self.parent
while parent and parent.parent is not None:
parts.append(
self.display_parent_prefix_middle
if parent.is_last
else self.display_parent_prefix_last
)
parent = parent.parent
return "".join(reversed(parts)) # Assemble the parts into the final string
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/cli/__init__.py | gpt_engineer/applications/cli/__init__.py | python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false | |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/cli/collect.py | gpt_engineer/applications/cli/collect.py | """
Module `collect` - Data Handling and RudderStack Integration
This module provides functionalities to handle and send learning data to RudderStack
for the purpose of analysis and to improve the gpt-engineer system. The data is sent
only when the user gives consent to share.
Functions:
send_learning(learning): Sends learning data to RudderStack.
collect_learnings(prompt, model, temperature, config, memory, review): Processes and sends learning data.
collect_and_send_human_review(prompt, model, temperature, config, memory): Collects human feedback and sends it.
Dependencies:
hashlib: For generating SHA-256 hash.
typing: For type annotations.
gpt_engineer.core: Core functionalities of gpt-engineer.
gpt_engineer.cli.learning: Handles the extraction of learning data.
Notes:
Data sent to RudderStack is not shared with third parties and is used solely to
improve gpt-engineer and allow it to handle a broader range of use cases.
Consent logic is in gpt_engineer/learning.py.
"""
from typing import Tuple
from gpt_engineer.applications.cli.learning import (
Learning,
Review,
extract_learning,
human_review_input,
)
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.prompt import Prompt
def send_learning(learning: Learning):
"""
Send the learning data to RudderStack for analysis.
Parameters
----------
learning : Learning
An instance of the Learning class containing the data to be sent.
Notes
-----
This function is only called if consent is given to share data.
Data is not shared to a third party. It is used with the sole purpose of
improving gpt-engineer, and letting it handle more use cases.
Consent logic is in gpt_engineer/learning.py.
"""
import rudderstack.analytics as rudder_analytics
rudder_analytics.write_key = "2Re4kqwL61GDp7S8ewe6K5dbogG"
rudder_analytics.dataPlaneUrl = "https://gptengineerezm.dataplane.rudderstack.com"
rudder_analytics.track(
user_id=learning.session,
event="learning",
properties=learning.to_dict(), # type: ignore
)
def collect_learnings(
prompt: Prompt,
model: str,
temperature: float,
config: any,
memory: DiskMemory,
review: Review,
):
"""
Collect the learning data and send it to RudderStack for analysis.
Parameters
----------
prompt : str
The initial prompt or question that was provided to the model.
model : str
The name of the model used for generating the response.
temperature : float
The temperature setting used in the model's response generation.
config : any
Configuration parameters used for the learning session.
memory : DiskMemory
An instance of DiskMemory for storing and retrieving data.
review : Review
An instance of Review containing human feedback on the model's response.
Notes
-----
This function attempts to send the learning data to RudderStack. If the data size exceeds
the maximum allowed size, it trims the data and retries sending it.
"""
learnings = extract_learning(prompt, model, temperature, config, memory, review)
try:
send_learning(learnings)
except RuntimeError:
# try to remove some parts of learning that might be too big
# rudderstack max event size is 32kb
max_size = 32 << 10 # 32KB in bytes
current_size = len(learnings.to_json().encode("utf-8")) # get size in bytes
overflow = current_size - max_size
# Add some extra characters for the "[REMOVED...]" string and for safety margin
remove_length = overflow + len(f"[REMOVED {overflow} CHARACTERS]") + 100
learnings.logs = (
learnings.logs[:-remove_length]
+ f"\n\n[REMOVED {remove_length} CHARACTERS]"
)
print(
"WARNING: learning too big, removing some parts. "
"Please report if this results in a crash."
)
try:
send_learning(learnings)
except RuntimeError:
print(
"Sending learnings crashed despite truncation. Progressing without saving learnings."
)
# def steps_file_hash():
# """
# Compute the SHA-256 hash of the steps file.
#
# Returns
# -------
# str
# The SHA-256 hash of the steps file.
# """
# with open(steps.__file__, "r") as f:
# content = f.read()
# return hashlib.sha256(content.encode("utf-8")).hexdigest()
def collect_and_send_human_review(
prompt: Prompt,
model: str,
temperature: float,
config: Tuple[str, ...],
memory: DiskMemory,
):
"""
Collects human feedback on the code and sends it for analysis.
Parameters
----------
prompt : str
The initial prompt or question that was provided to the model.
model : str
The name of the model used for generating the response.
temperature : float
The temperature setting used in the model's response generation.
config : Tuple[str, ...]
Configuration parameters used for the learning session.
memory : DiskMemory
An instance of DiskMemory for storing and retrieving data.
Returns
-------
None
Notes
-----
This function prompts the user for a review of the generated or improved code using the
`human_review_input` function. If a valid review is provided, it's serialized to JSON format
and stored within the database's memory under the "review" key.
"""
review = human_review_input()
if review:
collect_learnings(prompt, model, temperature, config, memory, review)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/applications/cli/cli_agent.py | gpt_engineer/applications/cli/cli_agent.py | """
This module provides the CliAgent class which manages the lifecycle of code generation and improvement
using an AI model. It includes functionalities to initialize code generation, improve existing code,
and process the code through various steps defined in the step bundle.
"""
from typing import Callable, Optional, TypeVar
# from gpt_engineer.core.default.git_version_manager import GitVersionManager
from gpt_engineer.core.ai import AI
from gpt_engineer.core.base_agent import BaseAgent
from gpt_engineer.core.base_execution_env import BaseExecutionEnv
from gpt_engineer.core.base_memory import BaseMemory
from gpt_engineer.core.default.disk_execution_env import DiskExecutionEnv
from gpt_engineer.core.default.disk_memory import DiskMemory
from gpt_engineer.core.default.paths import PREPROMPTS_PATH
from gpt_engineer.core.default.steps import (
execute_entrypoint,
gen_code,
gen_entrypoint,
improve_fn,
)
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.preprompts_holder import PrepromptsHolder
from gpt_engineer.core.prompt import Prompt
CodeGenType = TypeVar("CodeGenType", bound=Callable[[AI, str, BaseMemory], FilesDict])
CodeProcessor = TypeVar(
"CodeProcessor", bound=Callable[[AI, BaseExecutionEnv, FilesDict], FilesDict]
)
ImproveType = TypeVar(
"ImproveType", bound=Callable[[AI, str, FilesDict, BaseMemory], FilesDict]
)
class CliAgent(BaseAgent):
"""
The `CliAgent` class is responsible for managing the lifecycle of code generation and improvement
using an AI model. It orchestrates the generation of new code and the improvement of existing code
based on given prompts and utilizes a memory system and execution environment for processing.
Parameters
----------
memory : BaseMemory
An instance of a class that adheres to the BaseMemory interface, used for storing and retrieving
information during the code generation process.
execution_env : BaseExecutionEnv
An instance of a class that adheres to the BaseExecutionEnv interface, used for executing code
and managing the execution environment.
ai : AI, optional
An instance of the AI class that manages calls to the language model. If not provided, a default
instance is created.
code_gen_fn : CodeGenType, optional
A callable that takes an AI instance, a prompt, and a memory instance to generate code. Defaults
to the `gen_code` function.
improve_fn : ImproveType, optional
A callable that takes an AI instance, a prompt, a FilesDict instance, and a memory instance to
improve code. Defaults to the `improve` function.
process_code_fn : CodeProcessor, optional
A callable that takes an AI instance, an execution environment, and a FilesDict instance to
process code. Defaults to the `execute_entrypoint` function.
preprompts_holder : PrepromptsHolder, optional
An instance of PrepromptsHolder that manages preprompt templates. If not provided, a default
instance is created using the PREPROMPTS_PATH.
Attributes
----------
memory : BaseMemory
The memory instance where the agent stores and retrieves information.
execution_env : BaseExecutionEnv
The execution environment instance where the agent executes and manages code.
ai : AI
The AI instance used for interacting with the language model.
code_gen_fn : CodeGenType
The function used for generating code.
improve_fn : ImproveType
The function used for improving code.
process_code_fn : CodeProcessor
The function used for processing code.
preprompts_holder : PrepromptsHolder
The holder for preprompt templates.
"""
def __init__(
self,
memory: BaseMemory,
execution_env: BaseExecutionEnv,
ai: AI = None,
code_gen_fn: CodeGenType = gen_code,
improve_fn: ImproveType = improve_fn,
process_code_fn: CodeProcessor = execute_entrypoint,
preprompts_holder: PrepromptsHolder = None,
):
self.memory = memory
self.execution_env = execution_env
self.ai = ai or AI()
self.code_gen_fn = code_gen_fn
self.process_code_fn = process_code_fn
self.improve_fn = improve_fn
self.preprompts_holder = preprompts_holder or PrepromptsHolder(PREPROMPTS_PATH)
@classmethod
def with_default_config(
cls,
memory: DiskMemory,
execution_env: DiskExecutionEnv,
ai: AI = None,
code_gen_fn: CodeGenType = gen_code,
improve_fn: ImproveType = improve_fn,
process_code_fn: CodeProcessor = execute_entrypoint,
preprompts_holder: PrepromptsHolder = None,
diff_timeout=3,
):
"""
Creates a new instance of CliAgent with default configurations for memory, execution environment,
AI, and other functional parameters.
Parameters
----------
memory : DiskMemory
An instance of DiskMemory for storing and retrieving information.
execution_env : DiskExecutionEnv
An instance of DiskExecutionEnv for executing code.
ai : AI, optional
An instance of AI for interacting with the language model. Defaults to None, which will create
a new AI instance.
code_gen_fn : CodeGenType, optional
A function for generating code. Defaults to `gen_code`.
improve_fn : ImproveType, optional
A function for improving code. Defaults to `improve`.
process_code_fn : CodeProcessor, optional
A function for processing code. Defaults to `execute_entrypoint`.
preprompts_holder : PrepromptsHolder, optional
An instance of PrepromptsHolder for managing preprompt templates. Defaults to None, which will
create a new PrepromptsHolder instance using PREPROMPTS_PATH.
Returns
-------
CliAgent
An instance of CliAgent configured with the provided or default parameters.
"""
return cls(
memory=memory,
execution_env=execution_env,
ai=ai,
code_gen_fn=code_gen_fn,
process_code_fn=process_code_fn,
improve_fn=improve_fn,
preprompts_holder=preprompts_holder or PrepromptsHolder(PREPROMPTS_PATH),
)
def init(self, prompt: Prompt) -> FilesDict:
"""
Generates a new piece of code using the AI and step bundle based on the provided prompt.
Parameters
----------
prompt : str
A string prompt that guides the code generation process.
Returns
-------
FilesDict
An instance of the `FilesDict` class containing the generated code.
"""
files_dict = self.code_gen_fn(
self.ai, prompt, self.memory, self.preprompts_holder
)
entrypoint = gen_entrypoint(
self.ai, prompt, files_dict, self.memory, self.preprompts_holder
)
combined_dict = {**files_dict, **entrypoint}
files_dict = FilesDict(combined_dict)
files_dict = self.process_code_fn(
self.ai,
self.execution_env,
files_dict,
preprompts_holder=self.preprompts_holder,
prompt=prompt,
memory=self.memory,
)
return files_dict
def improve(
self,
files_dict: FilesDict,
prompt: Prompt,
execution_command: Optional[str] = None,
diff_timeout=3,
) -> FilesDict:
"""
Improves an existing piece of code using the AI and step bundle based on the provided prompt.
Parameters
----------
files_dict : FilesDict
An instance of `FilesDict` containing the code to be improved.
prompt : str
A string prompt that guides the code improvement process.
execution_command : str, optional
An optional command to execute the code. If not provided, the default execution command is used.
Returns
-------
FilesDict
An instance of the `FilesDict` class containing the improved code.
"""
files_dict = self.improve_fn(
self.ai,
prompt,
files_dict,
self.memory,
self.preprompts_holder,
diff_timeout=diff_timeout,
)
# entrypoint = gen_entrypoint(
# self.ai, prompt, files_dict, self.memory, self.preprompts_holder
# )
# combined_dict = {**files_dict, **entrypoint}
# files_dict = FilesDict(combined_dict)
# files_dict = self.process_code_fn(
# self.ai,
# self.execution_env,
# files_dict,
# preprompts_holder=self.preprompts_holder,
# prompt=prompt,
# memory=self.memory,
# )
return files_dict
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/project_config.py | gpt_engineer/core/project_config.py | """
Functions for reading and writing the `gpt-engineer.toml` configuration file.
The `gpt-engineer.toml` file is a TOML file that contains project-specific configuration used by the GPT Engineer CLI and gptengineer.app.
"""
from dataclasses import asdict, dataclass, field
from pathlib import Path
import tomlkit
default_config_filename = "gpt-engineer.toml"
example_config = """
[run]
build = "npm run build"
test = "npm run test"
lint = "quick-lint-js"
[paths]
base = "./frontend" # base directory to operate in (for monorepos)
src = "./src" # source directory (under the base directory) from which context will be retrieved
[gptengineer-app] # this namespace is used for gptengineer.app, may be used for internal experiments
project_id = "..."
# we support multiple OpenAPI schemas, used as context for the LLM
openapi = [
{ url = "https://api.gptengineer.app/openapi.json" },
{ url = "https://some-color-translating-api/openapi.json" },
]
"""
@dataclass
class _PathsConfig:
base: str | None = None
src: str | None = None
@dataclass
class _RunConfig:
build: str | None = None
test: str | None = None
lint: str | None = None
format: str | None = None
@dataclass
class _OpenApiConfig:
url: str
@dataclass
class _GptEngineerAppConfig:
project_id: str
openapi: list[_OpenApiConfig] | None = None
def filter_none(d: dict) -> dict:
# Drop None values and empty dictionaries from a dictionary
return {
k: v
for k, v in (
(k, filter_none(v) if isinstance(v, dict) else v)
for k, v in d.items()
if v is not None
)
if not (isinstance(v, dict) and not v) # Check for non-empty after filtering
}
@dataclass
class Config:
"""Configuration for the GPT Engineer CLI and gptengineer.app via `gpt-engineer.toml`."""
paths: _PathsConfig = field(default_factory=_PathsConfig)
run: _RunConfig = field(default_factory=_RunConfig)
gptengineer_app: _GptEngineerAppConfig | None = None
@classmethod
def from_toml(cls, config_file: Path | str):
if isinstance(config_file, str):
config_file = Path(config_file)
config_dict = read_config(config_file)
return cls.from_dict(config_dict)
@classmethod
def from_dict(cls, config_dict: dict):
run = _RunConfig(**config_dict.get("run", {}))
paths = _PathsConfig(**config_dict.get("paths", {}))
# load optional gptengineer-app section
gptengineer_app_dict = config_dict.get("gptengineer-app", {})
gptengineer_app = None
if gptengineer_app_dict:
assert (
"project_id" in gptengineer_app_dict
), "project_id is required in gptengineer-app section"
gptengineer_app = _GptEngineerAppConfig(
# required if gptengineer-app section is present
project_id=gptengineer_app_dict["project_id"],
openapi=[
_OpenApiConfig(**openapi)
for openapi in gptengineer_app_dict.get("openapi", [])
]
or None,
)
return cls(paths=paths, run=run, gptengineer_app=gptengineer_app)
def to_dict(self) -> dict:
d = asdict(self)
d["gptengineer-app"] = d.pop("gptengineer_app", None)
# Drop None values and empty dictionaries
# Needed because tomlkit.dumps() doesn't handle None values,
# and we don't want to write empty sections.
d = filter_none(d)
return d
def to_toml(self, config_file: Path | str, save=True) -> str:
"""Write the configuration to a TOML file."""
if isinstance(config_file, str):
config_file = Path(config_file)
# Load the TOMLDocument and overwrite it with the new values
config = read_config(config_file)
default_config = Config().to_dict()
for k, v in self.to_dict().items():
# only write values that are already explicitly set, or that differ from defaults
if k in config or v != default_config[k]:
if isinstance(v, dict):
config[k] = {
k2: v2
for k2, v2 in v.items()
if (
k2 in config[k]
or default_config.get(k) is None
or v2 != default_config[k].get(k2)
)
}
else:
config[k] = v
toml_str = tomlkit.dumps(config)
if save:
with open(config_file, "w") as f:
f.write(toml_str)
return toml_str
def read_config(config_file: Path) -> tomlkit.TOMLDocument:
"""Read the configuration file"""
assert config_file.exists(), f"Config file {config_file} does not exist"
with open(config_file, "r") as f:
return tomlkit.load(f)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/chat_to_files.py | gpt_engineer/core/chat_to_files.py | """
This Python script provides functionalities for parsing chat transcripts that contain file paths and code blocks,
applying diffs to these files, and parsing unified git diff format strings. The script is designed to work within
a larger system that involves processing and manipulating code files based on chat inputs and diff information.
Key Components:
- chat_to_files_dict: Parses a chat transcript, extracting file paths and associated code blocks, and organizes
them into a FilesDict object, which is a custom dictionary format designed to hold file contents keyed by their paths.
- apply_diffs: Takes a dictionary of Diff objects (which represent changes to be made to files) and a FilesDict
object containing the current state of files. It applies the changes described by the Diff objects to the
corresponding files in the FilesDict, updating the file contents as specified by the diffs.
- parse_diffs: Parses a string containing diffs in the unified git diff format, extracting the changes described
in the diffs and organizing them into a dictionary of Diff objects, keyed by the filename to which each diff applies.
- parse_diff_block: Parses a single block of text from a diff string, translating it into a Diff object that
represents the changes described in that block of text.
This script is intended for use in environments where code collaboration or review is conducted through chat interfaces,
allowing for the dynamic application of changes to code bases and the efficient handling of file and diff information in chat transcripts.
"""
import logging
import re
from typing import Dict, Tuple
from regex import regex
from gpt_engineer.core.diff import ADD, REMOVE, RETAIN, Diff, Hunk
from gpt_engineer.core.files_dict import FilesDict, file_to_lines_dict
# Initialize a logger for this module
logger = logging.getLogger(__name__)
def chat_to_files_dict(chat: str) -> FilesDict:
"""
Converts a chat string containing file paths and code blocks into a FilesDict object.
Args:
- chat (str): The chat string containing file paths and code blocks.
Returns:
- FilesDict: A dictionary with file paths as keys and code blocks as values.
"""
# Regex to match file paths and associated code blocks
regex = r"(\S+)\n\s*```[^\n]*\n(.+?)```"
matches = re.finditer(regex, chat, re.DOTALL)
files_dict = FilesDict()
for match in matches:
# Clean and standardize the file path
path = re.sub(r'[\:<>"|?*]', "", match.group(1))
path = re.sub(r"^\[(.*)\]$", r"\1", path)
path = re.sub(r"^`(.*)`$", r"\1", path)
path = re.sub(r"[\]\:]$", "", path)
# Extract and clean the code content
content = match.group(2)
# Add the cleaned path and content to the FilesDict
files_dict[path.strip()] = content.strip()
return files_dict
def apply_diffs(diffs: Dict[str, Diff], files: FilesDict) -> FilesDict:
"""
Applies diffs to the provided files.
Args:
- diffs (Dict[str, Diff]): A dictionary of diffs to apply, keyed by filename.
- files (FilesDict): The original files to which diffs will be applied.
Returns:
- FilesDict: The updated files after applying diffs.
"""
files = FilesDict(files.copy())
REMOVE_FLAG = "<REMOVE_LINE>" # Placeholder to mark lines for removal
for diff in diffs.values():
if diff.is_new_file():
# If it's a new file, create it with the content from the diff
files[diff.filename_post] = "\n".join(
line[1] for hunk in diff.hunks for line in hunk.lines
)
else:
# Convert the file content to a dictionary of lines
line_dict = file_to_lines_dict(files[diff.filename_pre])
for hunk in diff.hunks:
current_line = hunk.start_line_pre_edit
for line in hunk.lines:
if line[0] == RETAIN:
current_line += 1
elif line[0] == ADD:
# Handle added lines
current_line -= 1
if (
current_line in line_dict.keys()
and line_dict[current_line] != REMOVE_FLAG
):
line_dict[current_line] += "\n" + line[1]
else:
line_dict[current_line] = line[1]
current_line += 1
elif line[0] == REMOVE:
# Mark removed lines with REMOVE_FLAG
line_dict[current_line] = REMOVE_FLAG
current_line += 1
# Remove lines marked for removal
line_dict = {
key: line_content
for key, line_content in line_dict.items()
if REMOVE_FLAG not in line_content
}
# Reassemble the file content
files[diff.filename_post] = "\n".join(line_dict.values())
return files
def parse_diffs(diff_string: str, diff_timeout=3) -> dict:
"""
Parses a diff string in the unified git diff format.
Args:
- diff_string (str): The diff string to parse.
Returns:
- dict: A dictionary of Diff objects keyed by filename.
"""
# Regex to match individual diff blocks
diff_block_pattern = regex.compile(
r"```.*?\n\s*?--- .*?\n\s*?\+\+\+ .*?\n(?:@@ .*? @@\n(?:[-+ ].*?\n)*?)*?```",
re.DOTALL,
)
diffs = {}
try:
for block in diff_block_pattern.finditer(diff_string, timeout=diff_timeout):
diff_block = block.group()
# Parse individual diff blocks and update the diffs dictionary
diff = parse_diff_block(diff_block)
for filename, diff_obj in diff.items():
if filename not in diffs:
diffs[filename] = diff_obj
else:
print(
f"\nMultiple diffs found for {filename}. Only the first one is kept."
)
except TimeoutError:
print("gpt-engineer timed out while parsing git diff")
if not diffs:
print(
"GPT did not provide any proposed changes. Please try to reselect the files for uploading and edit your prompt file."
)
return diffs
def parse_diff_block(diff_block: str) -> dict:
"""
Parses a block of diff text into a Diff object.
Args:
- diff_block (str): A single block of diff text.
Returns:
- dict: A dictionary containing a single Diff object keyed by the post-edit filename.
"""
lines = diff_block.strip().split("\n")[1:-1] # Exclude the opening and closing ```
diffs = {}
current_diff = None
hunk_lines = []
filename_pre = None
filename_post = None
hunk_header = None
for line in lines:
if line.startswith("--- "):
# Pre-edit filename
filename_pre = line[4:]
elif line.startswith("+++ "):
# Post-edit filename and initiation of a new Diff object
if (
filename_post is not None
and current_diff is not None
and hunk_header is not None
):
current_diff.hunks.append(Hunk(*hunk_header, hunk_lines))
hunk_lines = []
filename_post = line[4:]
current_diff = Diff(filename_pre, filename_post)
diffs[filename_post] = current_diff
elif line.startswith("@@ "):
# Start of a new hunk in the diff
if hunk_lines and current_diff is not None and hunk_header is not None:
current_diff.hunks.append(Hunk(*hunk_header, hunk_lines))
hunk_lines = []
hunk_header = parse_hunk_header(line)
elif line.startswith("+"):
# Added line
hunk_lines.append((ADD, line[1:]))
elif line.startswith("-"):
# Removed line
hunk_lines.append((REMOVE, line[1:]))
else:
# Retained line
hunk_lines.append((RETAIN, line[1:]))
# Append the last hunk if any
if current_diff is not None and hunk_lines and hunk_header is not None:
current_diff.hunks.append(Hunk(*hunk_header, hunk_lines))
return diffs
def parse_hunk_header(header_line) -> Tuple[int, int, int, int]:
"""
Parses the header of a hunk from a diff.
Args:
- header_line (str): The header line of a hunk.
Returns:
- tuple: A tuple containing start and length information for pre- and post-edit.
"""
pattern = re.compile(r"^@@ -\d{1,},\d{1,} \+\d{1,},\d{1,} @@$")
if not pattern.match(header_line):
# Return a default value if the header does not match the expected format
return 0, 0, 0, 0
pre, post = header_line.split(" ")[1:3]
start_line_pre_edit, hunk_len_pre_edit = map(int, pre[1:].split(","))
start_line_post_edit, hunk_len_post_edit = map(int, post[1:].split(","))
return (
start_line_pre_edit,
hunk_len_pre_edit,
start_line_post_edit,
hunk_len_post_edit,
)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/preprompts_holder.py | gpt_engineer/core/preprompts_holder.py | from pathlib import Path
from typing import Dict
from gpt_engineer.core.default.disk_memory import DiskMemory
class PrepromptsHolder:
"""
A holder for preprompt texts that are stored on disk.
This class provides methods to retrieve preprompt texts from a specified directory.
Attributes
----------
preprompts_path : Path
The file path to the directory containing preprompt texts.
Methods
-------
get_preprompts() -> Dict[str, str]
Retrieve all preprompt texts from the directory and return them as a dictionary.
"""
def __init__(self, preprompts_path: Path):
self.preprompts_path = preprompts_path
def get_preprompts(self) -> Dict[str, str]:
preprompts_repo = DiskMemory(self.preprompts_path)
return {file_name: preprompts_repo[file_name] for file_name in preprompts_repo}
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/token_usage.py | gpt_engineer/core/token_usage.py | import base64
import io
import logging
import math
from dataclasses import dataclass
from typing import List, Union
import tiktoken
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from PIL import Image
# workaround for function moved in:
# https://github.com/langchain-ai/langchain/blob/535db72607c4ae308566ede4af65295967bb33a8/libs/community/langchain_community/callbacks/openai_info.py
try:
from langchain.callbacks.openai_info import (
get_openai_token_cost_for_model, # fmt: skip
)
except ImportError:
from langchain_community.callbacks.openai_info import (
get_openai_token_cost_for_model, # fmt: skip
)
Message = Union[AIMessage, HumanMessage, SystemMessage]
logger = logging.getLogger(__name__)
@dataclass
class TokenUsage:
"""
Dataclass representing token usage statistics for a conversation step.
Attributes
----------
step_name : str
The name of the conversation step.
in_step_prompt_tokens : int
The number of prompt tokens used in the step.
in_step_completion_tokens : int
The number of completion tokens used in the step.
in_step_total_tokens : int
The total number of tokens used in the step.
total_prompt_tokens : int
The cumulative number of prompt tokens used up to this step.
total_completion_tokens : int
The cumulative number of completion tokens used up to this step.
total_tokens : int
The cumulative total number of tokens used up to this step.
"""
"""
Represents token usage statistics for a conversation step.
"""
step_name: str
in_step_prompt_tokens: int
in_step_completion_tokens: int
in_step_total_tokens: int
total_prompt_tokens: int
total_completion_tokens: int
total_tokens: int
class Tokenizer:
"""
Tokenizer for counting tokens in text.
"""
def __init__(self, model_name):
self.model_name = model_name
self._tiktoken_tokenizer = (
tiktoken.encoding_for_model(model_name)
if "gpt-4" in model_name or "gpt-3.5" in model_name
else tiktoken.get_encoding("cl100k_base")
)
def num_tokens(self, txt: str) -> int:
"""
Get the number of tokens in a text.
Parameters
----------
txt : str
The text to count the tokens in.
Returns
-------
int
The number of tokens in the text.
"""
return len(self._tiktoken_tokenizer.encode(txt))
def num_tokens_for_base64_image(
self, image_base64: str, detail: str = "high"
) -> int:
"""
Calculate the token size for a base64 encoded image based on OpenAI's token calculation rules.
Parameters:
- image_base64 (str): The base64 encoded string of the image.
- detail (str): The detail level of the image, 'low' or 'high'.
Returns:
- int: The token size of the image.
"""
if detail == "low":
return 85 # Fixed cost for low detail images
# Decode image from base64
image_data = base64.b64decode(image_base64)
# Convert byte data to image for size extraction
image = Image.open(io.BytesIO(image_data))
# Calculate the initial scale to fit within 2048 square while maintaining aspect ratio
max_dimension = max(image.size)
scale_factor = min(2048 / max_dimension, 1) # Ensure we don't scale up
new_width = int(image.size[0] * scale_factor)
new_height = int(image.size[1] * scale_factor)
# Scale such that the shortest side is 768px
shortest_side = min(new_width, new_height)
if shortest_side > 768:
resize_factor = 768 / shortest_side
new_width = int(new_width * resize_factor)
new_height = int(new_height * resize_factor)
# Calculate the number of 512px tiles needed
width_tiles = math.ceil(new_width / 512)
height_tiles = math.ceil(new_height / 512)
total_tiles = width_tiles * height_tiles
# Each tile costs 170 tokens, plus a base cost of 85 tokens for high detail
token_cost = total_tiles * 170 + 85
return token_cost
def num_tokens_from_messages(self, messages: List[Message]) -> int:
"""
Get the total number of tokens used by a list of messages, accounting for text and base64 encoded images.
Parameters
----------
messages : List[Message]
The list of messages to count the tokens in.
Returns
-------
int
The total number of tokens used by the messages.
"""
n_tokens = 0
for message in messages:
n_tokens += 4 # Account for message framing tokens
if isinstance(message.content, str):
# Content is a simple string
n_tokens += self.num_tokens(message.content)
elif isinstance(message.content, list):
# Content is a list, potentially mixed with text and images
for item in message.content:
if item.get("type") == "text":
n_tokens += self.num_tokens(item["text"])
elif item.get("type") == "image_url":
image_detail = item["image_url"].get("detail", "high")
image_base64 = item["image_url"].get("url")
n_tokens += self.num_tokens_for_base64_image(
image_base64, detail=image_detail
)
n_tokens += 2 # Account for assistant's reply framing tokens
return n_tokens
class TokenUsageLog:
"""
Represents a log of token usage statistics for a conversation.
"""
def __init__(self, model_name):
self.model_name = model_name
self._cumulative_prompt_tokens = 0
self._cumulative_completion_tokens = 0
self._cumulative_total_tokens = 0
self._log = []
self._tokenizer = Tokenizer(model_name)
def update_log(self, messages: List[Message], answer: str, step_name: str) -> None:
"""
Update the token usage log with the number of tokens used in the current step.
Parameters
----------
messages : List[Message]
The list of messages in the conversation.
answer : str
The answer from the AI.
step_name : str
The name of the step.
"""
prompt_tokens = self._tokenizer.num_tokens_from_messages(messages)
completion_tokens = self._tokenizer.num_tokens(answer)
total_tokens = prompt_tokens + completion_tokens
self._cumulative_prompt_tokens += prompt_tokens
self._cumulative_completion_tokens += completion_tokens
self._cumulative_total_tokens += total_tokens
self._log.append(
TokenUsage(
step_name=step_name,
in_step_prompt_tokens=prompt_tokens,
in_step_completion_tokens=completion_tokens,
in_step_total_tokens=total_tokens,
total_prompt_tokens=self._cumulative_prompt_tokens,
total_completion_tokens=self._cumulative_completion_tokens,
total_tokens=self._cumulative_total_tokens,
)
)
def log(self) -> List[TokenUsage]:
"""
Get the token usage log.
Returns
-------
List[TokenUsage]
A log of token usage details per step in the conversation.
"""
return self._log
def format_log(self) -> str:
"""
Format the token usage log as a CSV string.
Returns
-------
str
The token usage log formatted as a CSV string.
"""
result = "step_name,prompt_tokens_in_step,completion_tokens_in_step,total_tokens_in_step,total_prompt_tokens,total_completion_tokens,total_tokens\n"
for log in self._log:
result += f"{log.step_name},{log.in_step_prompt_tokens},{log.in_step_completion_tokens},{log.in_step_total_tokens},{log.total_prompt_tokens},{log.total_completion_tokens},{log.total_tokens}\n"
return result
def is_openai_model(self) -> bool:
"""
Check if the model is an OpenAI model.
Returns
-------
bool
True if the model is an OpenAI model, False otherwise.
"""
return "gpt" in self.model_name.lower()
def total_tokens(self) -> int:
"""
Return the total number of tokens used in the conversation.
Returns
-------
int
The total number of tokens used in the conversation.
"""
return self._cumulative_total_tokens
def usage_cost(self) -> float | None:
"""
Return the total cost in USD of the API usage.
Returns
-------
float
Cost in USD.
"""
if not self.is_openai_model():
return None
try:
result = 0
for log in self.log():
result += get_openai_token_cost_for_model(
self.model_name, log.total_prompt_tokens, is_completion=False
)
result += get_openai_token_cost_for_model(
self.model_name, log.total_completion_tokens, is_completion=True
)
return result
except Exception as e:
print(f"Error calculating usage cost: {e}")
return None
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/git.py | gpt_engineer/core/git.py | import shutil
import subprocess
from pathlib import Path
from typing import List
from gpt_engineer.core.files_dict import FilesDict
def is_git_installed():
return shutil.which("git") is not None
def is_git_repo(path: Path):
return (
subprocess.run(
["git", "rev-parse", "--is-inside-work-tree"],
cwd=path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
).returncode
== 0
)
def init_git_repo(path: Path):
subprocess.run(["git", "init"], cwd=path)
def has_uncommitted_changes(path: Path):
return bool(
subprocess.run(
["git", "diff", "--exit-code"],
cwd=path,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
).returncode
)
def filter_files_with_uncommitted_changes(
basepath: Path, files_dict: FilesDict
) -> List[Path]:
files_with_diff = (
subprocess.run(
["git", "diff", "--name-only"], cwd=basepath, stdout=subprocess.PIPE
)
.stdout.decode()
.splitlines()
)
return [f for f in files_dict.keys() if f in files_with_diff]
def stage_files(path: Path, files: List[str]):
subprocess.run(["git", "add", *files], cwd=path)
def filter_by_gitignore(path: Path, file_list: List[str]) -> List[str]:
out = subprocess.run(
["git", "-C", ".", "check-ignore", "--no-index", "--stdin"],
cwd=path,
input="\n".join(file_list).encode(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
paths = out.stdout.decode().splitlines()
# return file_list but filter out the results from git check-ignore
return [f for f in file_list if f not in paths]
def stage_uncommitted_to_git(path, files_dict, improve_mode):
# Check if there's a git repo and verify that there aren't any uncommitted changes
if is_git_installed() and not improve_mode:
if not is_git_repo(path):
print("\nInitializing an empty git repository")
init_git_repo(path)
if is_git_repo(path):
modified_files = filter_files_with_uncommitted_changes(path, files_dict)
if modified_files:
print(
"Staging the following uncommitted files before overwriting: ",
", ".join(modified_files),
)
stage_files(path, modified_files)
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/diff.py | gpt_engineer/core/diff.py | """
File Overview:
This Python module is designed for processing and analyzing diffs in source code files. Diffs represent the changes between two versions of a file, which are crucial in version control systems for tracking file modifications. The module focuses on the detailed examination of these diffs, enabling users to understand, validate, and correct changes between file versions.
Key Features:
1. The `Hunk` class encapsulates a contiguous block of changes within a file. It includes detailed information such as start lines before and after edits, lengths of change blocks, and specific line changes categorized as additions, deletions, or unchanged.
2. The `Diff` class represents a complete set of changes across a file and may contain multiple `Hunk` objects. It facilitates operations like generating string representations of diffs, and validating and correcting hunks based on the original file content.
3. Functions within the module allow for the validation of hunks against original files, identifying mismatches, and making necessary corrections. This feature ensures that diffs are accurate and reflect true changes.
4. Utility functions `is_similar` and `count_ratio` offer the capability to compare strings for similarity, accounting for variations in spacing and case. This aids in the validation process by allowing a flexible comparison of code lines.
Dependencies:
- `logging`: Utilized for logging warnings and errors encountered during the validation and correction process.
- `collections.Counter`: Used for counting occurrences of characters in strings, supporting the string similarity assessment functions.
Functions and Classes:
1. `Hunk`: Class representing a block of changes within a file, with methods for managing and validating these changes.
2. `Diff`: Class representing the entire set of changes in a file, containing multiple `Hunk` instances and methods for overall diff management.
3. `is_similar(str1, str2, similarity_threshold)`: Function to compare two strings for similarity, useful in validating line changes in hunks.
4. `count_ratio(str1, str2)`: Function that computes the ratio of common characters to the length of the longer string, aiding in the assessment of line similarity.
This module is essential for developers and teams utilizing version control systems, providing tools for a deeper analysis and correction of diffs, ensuring the integrity and accuracy of code changes.
"""
import logging
from collections import Counter
from typing import List
RETAIN = "retain"
ADD = "add"
REMOVE = "remove"
class Hunk:
"""
Represents a section of a file diff, containing changes made to that section.
Attributes:
start_line_pre_edit (int): The starting line number in the original file.
hunk_len_pre_edit (int): The length of the hunk in the original file.
start_line_post_edit (int): The starting line number in the edited file.
hunk_len_post_edit (int): The length of the hunk in the edited file.
lines (list): A list of tuples representing the lines in the hunk and their types (RETAIN, ADD, REMOVE).
category_counts (dict): A count of lines by their type.
is_new_file (bool): Flag indicating if the hunk represents a new file.
"""
def __init__(
self,
start_line_pre_edit,
hunk_len_pre_edit,
start_line_post_edit,
hunk_len_post_edit,
lines,
) -> None:
self.start_line_pre_edit = start_line_pre_edit
self.hunk_len_pre_edit = hunk_len_pre_edit
self.start_line_post_edit = start_line_post_edit
self.hunk_len_post_edit = hunk_len_post_edit
self.category_counts = {RETAIN: 0, ADD: 0, REMOVE: 0}
self.lines = list()
self.add_lines(lines)
self.forward_block_len = 10
# Note that this assumption should not be done on hunk level, however, if the below is true, no validation is possible anyway.
if self.category_counts[RETAIN] == 0 and self.category_counts[REMOVE] == 0:
self.is_new_file = True
else:
self.is_new_file = False
def add_retained_line(self, line, index) -> None:
"""Adds a retained line to the hunk at the specified index."""
self.lines.insert(index, (RETAIN, line))
self.category_counts[RETAIN] += 1
def relabel_line(self, index, new_label) -> None:
"""Changes the label of a line at the specified index."""
old_label = self.lines[index][0]
self.lines[index] = (new_label, self.lines[index][1])
self.category_counts[old_label] -= 1
self.category_counts[new_label] += 1
def pop_line(self, line, index) -> None:
"""Removes a line from the hunk at the specified index."""
self.lines.pop(index)
assert self.category_counts[line[0]] > 0
self.category_counts[line[0]] -= 1
def add_lines(self, new_lines) -> None:
"""Adds multiple lines to the hunk."""
for line in new_lines:
self.lines.append(line)
self.category_counts[line[0]] += 1
def hunk_to_string(self) -> str:
"""Converts the hunk to a string representation."""
string = f"@@ -{self.start_line_pre_edit},{self.hunk_len_pre_edit} +{self.start_line_post_edit},{self.hunk_len_post_edit} @@\n"
for line_type, line_content in self.lines:
line_prefix = (
" " if line_type == RETAIN else "+" if line_type == ADD else "-"
)
string += f"{line_prefix}{line_content}\n"
return string
def make_forward_block(self, hunk_ind: int, forward_block_len) -> str:
"""Creates a block of lines for forward comparison."""
forward_lines = [
line[1] for line in self.lines[hunk_ind:] if not line[0] == ADD
]
forward_block = "\n".join(forward_lines[0:forward_block_len])
return forward_block
def check_start_line(self, lines_dict: dict) -> bool:
"""Check if the starting line of a hunk is present in the original code and returns a boolean value accordingly."""
if self.is_new_file:
# this hunk cannot be falsified and is by definition true
return True
if self.start_line_pre_edit in lines_dict:
# check the location of the actual starting line:
is_similar(self.lines[0][1], lines_dict[self.start_line_pre_edit])
else:
pass
def find_start_line(self, lines_dict: dict, problems: list) -> bool:
"""Finds the starting line of the hunk in the original code and returns a boolean value accordingly. If the starting line is not found, it appends a problem message to the problems list."""
# ToDo handle the case where the start line is 0 or 1 characters separately
if self.lines[0][0] == ADD:
# handle the case where the start line is an add
start_line = None
# find the first line that is not an add
for index, line in enumerate(self.lines):
if line[0] != ADD:
for line_number, line_content in lines_dict.items():
# if the line is similar to a non-blank line in line_dict, we can pick the line prior to it
if is_similar(line[1], line_content) and line[1] != "":
start_line = line_number - 1
break
# if the start line is not found, append a problem message
if start_line is None:
problems.append(
f"In {self.hunk_to_string()}:can not find the starting line of the diff"
)
return False
else:
# the line prior to the start line is found now we insert it to the first place as the start line
self.start_line_pre_edit = start_line
retain_line = lines_dict.get(start_line, "")
if retain_line:
self.add_retained_line(lines_dict[start_line], 0)
return self.validate_and_correct(lines_dict, problems)
else:
problems.append(
f"In {self.hunk_to_string()}:The starting line of the diff {self.hunk_to_string()} does not exist in the code"
)
return False
pot_start_lines = {
key: is_similar(self.lines[0][1], line) for key, line in lines_dict.items()
}
sum_of_matches = sum(pot_start_lines.values())
if sum_of_matches == 0:
# before we go any further, we should check if it's a comment from LLM
if self.lines[0][1].count("#") > 0:
# if it is, we can mark it as an ADD lines
self.relabel_line(0, ADD)
# and restart the validation at the next line
return self.validate_and_correct(lines_dict, problems)
else:
problems.append(
f"In {self.hunk_to_string()}:The starting line of the diff {self.hunk_to_string()} does not exist in the code"
)
return False
elif sum_of_matches == 1:
start_ind = list(pot_start_lines.keys())[
list(pot_start_lines.values()).index(True)
] # lines are one indexed
else:
logging.warning("multiple candidates for starting index")
# ToDo handle all the cases better again here. Smartest choice is that, for each candidate check match to the next line etc (recursively)
start_ind = list(pot_start_lines.keys())[
list(pot_start_lines.values()).index(True)
]
self.start_line_pre_edit = start_ind
# This should now be fulfilled by default
assert is_similar(self.lines[0][1], lines_dict[self.start_line_pre_edit])
return True
def validate_lines(self, lines_dict: dict, problems: list) -> bool:
"""Validates the lines of the hunk against the original file and returns a boolean value accordingly. If the lines do not match, it appends a problem message to the problems list."""
hunk_ind = 0
file_ind = self.start_line_pre_edit
# make an orig hunk lines for logging
# orig_hunk_lines = deepcopy(self.lines)
while hunk_ind < len(self.lines) and file_ind <= max(lines_dict):
if self.lines[hunk_ind][0] == ADD:
# this cannot be validated, jump one index
hunk_ind += 1
elif not is_similar(self.lines[hunk_ind][1], lines_dict[file_ind]):
# before we go any further, we should relabel the comment from LLM
if self.lines[hunk_ind][1].count("#") > 0:
self.relabel_line(hunk_ind, ADD)
continue
# make a forward block from the code for comparisons
forward_code = "\n".join(
[
lines_dict[ind]
for ind in range(
file_ind,
min(
file_ind + self.forward_block_len,
max(lines_dict.keys()),
),
)
]
)
# make the original forward block for quantitative comparison
forward_block = self.make_forward_block(
hunk_ind, self.forward_block_len
)
orig_count_ratio = count_ratio(forward_block, forward_code)
# Here we have 2 cases
# 1) some lines were simply skipped in the diff and we should add them to the diff
# If this is the case, adding the line to the diff, should give an improved forward diff
forward_block_missing_line = self.make_forward_block(
hunk_ind, self.forward_block_len - 1
)
# insert the missing line in front of the block
forward_block_missing_line = "\n".join(
[lines_dict[file_ind], forward_block_missing_line]
)
missing_line_count_ratio = count_ratio(
forward_block_missing_line, forward_code
)
# 2) Additional lines, not belonging to the code were added to the diff
forward_block_false_line = self.make_forward_block(
hunk_ind + 1, self.forward_block_len
)
false_line_count_ratio = count_ratio(
forward_block_false_line, forward_code
)
if (
orig_count_ratio >= missing_line_count_ratio
and orig_count_ratio >= false_line_count_ratio
):
problems.append(
f"In Hunk:{self.hunk_to_string()}, there was at least one mismatch."
)
return False
elif missing_line_count_ratio > false_line_count_ratio:
self.add_retained_line(lines_dict[file_ind], hunk_ind)
hunk_ind += 1
file_ind += 1
# NOTE: IF THE LLM SKIPS SOME LINES AND HAS ADDs ADJACENT TO THE SKIPPED BLOCK,
# WE CANNOT KNOW WHETHER THE ADDs SHOULD BE BEFORE OR AFTER THE BLOCK. WE OPT FOR PUTTING IT BEFORE.
# IF IT MATTERED, WE ASSUME THE LLM WOULD NOT SKIP THE BLOCK
else:
self.pop_line(self.lines[hunk_ind], hunk_ind)
else:
hunk_ind += 1
file_ind += 1
# if we have not validated all lines, we have a problem
if hunk_ind < len(self.lines) - 1:
remaining_lines = "\n".join(
f"{line_type}: {line_content}"
for line_type, line_content in self.lines[file_ind + 1 :]
)
problems.append(
f"In {self.hunk_to_string()}:Hunk validation stopped before the lines {remaining_lines} were validated. The diff is incorrect"
)
return False
return True
def validate_and_correct(
self,
lines_dict: dict,
problems: list,
) -> bool:
"""
Validates and corrects the hunk based on the original lines.
This function attempts to validate the hunk by comparing its lines to the original file and making corrections
where necessary. It also identifies problems such as non-matching lines or incorrect line types.
"""
start_true = self.check_start_line(lines_dict)
if not start_true:
if not self.find_start_line(lines_dict, problems):
return False
# Now we should be able to validate the hunk line by line and add missing line
if not self.validate_lines(lines_dict, problems):
return False
# Pass the validation
return True
class Diff:
"""
Represents a file diff, containing multiple hunks of changes.
Attributes:
filename_pre (str): The name of the original file.
filename_post (str): The name of the edited file.
hunks (list): A list of Hunk objects representing the changes in the diff.
"""
def __init__(self, filename_pre, filename_post) -> None:
self.filename_pre = filename_pre
self.filename_post = filename_post
self.hunks = []
def is_new_file(self) -> bool:
"""Determines if the diff represents a new file."""
if self.filename_pre == "/dev/null":
return True
return any(hunk.is_new_file for hunk in self.hunks)
def diff_to_string(self) -> str:
"""Converts the diff to a string representation."""
string = f"--- {self.filename_pre}\n+++ {self.filename_post}\n"
for hunk in self.hunks:
string += hunk.hunk_to_string()
return string.strip()
def validate_and_correct(self, lines_dict: dict) -> List[str]:
"""Validates and corrects each hunk in the diff."""
problems = []
past_hunk = None
cut_lines_dict = lines_dict.copy()
for hunk in self.hunks:
if past_hunk is not None:
# make sure to not cut so much that the start_line gets out of range
cut_ind = min(
past_hunk.start_line_pre_edit + past_hunk.hunk_len_pre_edit,
hunk.start_line_pre_edit,
)
cut_lines_dict = {
key: val for key, val in cut_lines_dict.items() if key >= (cut_ind)
}
is_valid = hunk.validate_and_correct(cut_lines_dict, problems)
if not is_valid and len(problems) > 0:
for idx, val in enumerate(problems):
print(f"\nInvalid Hunk NO.{idx}---\n{val}\n---")
self.hunks.remove(hunk)
# now correct the numbers, assuming the start line pre-edit has been fixed
hunk.hunk_len_pre_edit = (
hunk.category_counts[RETAIN] + hunk.category_counts[REMOVE]
)
hunk.hunk_len_post_edit = (
hunk.category_counts[RETAIN] + hunk.category_counts[ADD]
)
if past_hunk is not None:
hunk.start_line_post_edit = (
hunk.start_line_pre_edit
+ past_hunk.hunk_len_post_edit
- past_hunk.hunk_len_pre_edit
+ past_hunk.start_line_post_edit
- past_hunk.start_line_pre_edit
)
else:
hunk.start_line_post_edit = hunk.start_line_pre_edit
past_hunk = hunk
return problems
def is_similar(str1, str2, similarity_threshold=0.9) -> bool:
"""
Compares two strings for similarity, ignoring spaces and case.
Parameters
----------
str1, str2 : str
The strings to compare.
similarity_threshold: float
How similar must the strings be
Returns
-------
bool
True if the strings are similar, False otherwise.
"""
return count_ratio(str1, str2) >= similarity_threshold
def count_ratio(str1, str2) -> float:
"""
Computes the ratio of common characters to the length of the longer string, ignoring spaces and case.
Parameters:
- str1, str2 (str): The strings to compare.
Returns:
- float: The ratio of common characters to the length of the longer string.
"""
str1, str2 = str1.replace(" ", "").lower(), str2.replace(" ", "").lower()
counter1, counter2 = Counter(str1), Counter(str2)
intersection = sum((counter1 & counter2).values())
longer_length = max(len(str1), len(str2))
if longer_length == 0:
return 1
else:
return intersection / longer_length
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/base_memory.py | gpt_engineer/core/base_memory.py | """
Base Memory Module
This module provides a type alias for a mutable mapping that represents the base memory structure
used in the GPT Engineer project. The base memory is a mapping from file names (as strings or Path objects)
to their corresponding code content (as strings).
Type Aliases:
BaseMemory: A mutable mapping from file names to code content.
"""
from pathlib import Path
from typing import MutableMapping, Union
BaseMemory = MutableMapping[Union[str, Path], str]
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/base_agent.py | gpt_engineer/core/base_agent.py | """
Base Agent Module
This module provides an abstract base class for an agent that interacts with code. It defines the interface
for agents capable of initializing and improving code based on a given prompt. Implementations of this class
are expected to provide concrete methods for these actions.
Classes:
BaseAgent: Abstract base class for an agent that interacts with code.
"""
from abc import ABC, abstractmethod
from gpt_engineer.core.files_dict import FilesDict
from gpt_engineer.core.prompt import Prompt
class BaseAgent(ABC):
"""
Abstract base class for an agent that interacts with code.
Defines the interface for agents capable of initializing and improving code based on a given prompt.
Implementations of this class are expected to provide concrete methods for these actions.
"""
@abstractmethod
def init(self, prompt: Prompt) -> FilesDict:
pass
@abstractmethod
def improve(self, files_dict: FilesDict, prompt: Prompt) -> FilesDict:
pass
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/version_manager.py | gpt_engineer/core/version_manager.py | """
Version Manager Module
This module provides an abstract base class for a version manager that handles the creation of snapshots
for code. Implementations of this class are expected to provide methods to create a snapshot of the given
code and return a reference to it.
"""
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Union
from gpt_engineer.core.files_dict import FilesDict
class BaseVersionManager(ABC):
"""
Abstract base class for a version manager.
Defines the interface for version managers that handle the creation of snapshots for code.
Implementations of this class are expected to provide methods to create a snapshot of the given
code and return a reference to it.
"""
@abstractmethod
def __init__(self, path: Union[str, Path]):
pass
@abstractmethod
def snapshot(self, files_dict: FilesDict) -> str:
pass
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
AntonOsika/gpt-engineer | https://github.com/AntonOsika/gpt-engineer/blob/a90fcd543eedcc0ff2c34561bc0785d2ba83c47e/gpt_engineer/core/base_execution_env.py | gpt_engineer/core/base_execution_env.py | from abc import ABC, abstractmethod
from subprocess import Popen
from typing import Optional, Tuple
from gpt_engineer.core.files_dict import FilesDict
class BaseExecutionEnv(ABC):
"""
Abstract base class for an execution environment capable of running code.
This class defines the interface for execution environments that can execute commands,
handle processes, and manage file uploads and downloads.
"""
@abstractmethod
def run(self, command: str, timeout: Optional[int] = None) -> Tuple[str, str, int]:
"""
Runs a command in the execution environment.
"""
raise NotImplementedError
@abstractmethod
def popen(self, command: str) -> Popen:
"""
Runs a command in the execution environment.
"""
raise NotImplementedError
@abstractmethod
def upload(self, files: FilesDict) -> "BaseExecutionEnv":
"""
Uploads files to the execution environment.
"""
raise NotImplementedError
@abstractmethod
def download(self) -> FilesDict:
"""
Downloads files from the execution environment.
"""
raise NotImplementedError
| python | MIT | a90fcd543eedcc0ff2c34561bc0785d2ba83c47e | 2026-01-04T14:39:15.137338Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.