Skip to content

Commit 06b6d47

Browse files
author
Muhammad Ali
committed
finished for now
1 parent 149a79d commit 06b6d47

File tree

2 files changed

+120
-42
lines changed

2 files changed

+120
-42
lines changed

key-values.csv

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
City, Title
2-
city1, title1
3-
City2, title2
4-
city3, title3
1+
City,Title
2+
city1,title1
3+
City2,title2
4+
city3,title3

main.py

Lines changed: 116 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,131 @@
11
import os
2+
import sys
3+
import pandas as pd
4+
from colorama import init , Fore , Back
25

3-
prompt_file = False
4-
csv_file = False
6+
# Initialize colorama
7+
init(autoreset=True)
58

6-
def clear_console():
7-
# Clear the console based on the OS
8-
if os.name == 'posix': # Unix/Linux/MacOS
9-
os.system('clear')
10-
elif os.name == 'nt': # Windows
11-
os.system('cls')
12-
else:
13-
# Unsupported OS
14-
print("Clearing the console is not supported on this operating system.")
9+
error = False
1510

11+
class CustomError(Exception):
12+
def __init__(self, message):
13+
self.message = message
1614

17-
def check_files():
18-
if os.path.exists("prompt.txt"):
19-
print(">Prompt Template Found.")
20-
else:
21-
print(">Prompt Template Missing")
22-
23-
if os.path.exists("key-values.csv"):
24-
print(">CSV File Found.")
25-
else:
26-
print(">CSV File Missing")
15+
def print_error(message):
16+
print("\n" + Fore.RED + "×" + " " + message + "\n")
17+
error = True
18+
19+
def print_success(message):
20+
print("\n" + Fore.GREEN + "✓" + " " + message + "\n")
21+
22+
def print_warning(message):
23+
print("\n" + Fore.YELLOW + "¿" + " " + message + "\n")
24+
25+
def print_info(message):
26+
print("\n" + Fore.CYAN + "·" + " " + message + "\n")
27+
28+
def clear_screen():
29+
print("\033[H\033[J")
30+
31+
def print_normal(message):
32+
print("\n" + message + "\n")
33+
34+
def confirm_pause():
35+
input("\nPress any key to continue...")
2736

2837

29-
def ask_choice(title: str, options: list):
30-
while True:
31-
print(title+":")
32-
for index , item in iter(options):
33-
print(f"{index}. {item}")
38+
def help():
39+
print_info("Usage: main.py [OPTION]")
40+
print_normal("Options:")
41+
print_normal(" -d, --description Start the program in description mode")
42+
print_normal(" -h, --help Show this help message")
43+
print_info("Learn more about the program at: https://github.com/tensor35/Python-Prompt-Generator-Script/blob/master/README.md")
44+
45+
46+
def main(description_mode: bool = False):
47+
clear_screen()
48+
49+
# print_info mode of operation
50+
if description_mode:
51+
print_info("Generating Prompts in Description Mode")
52+
else :
53+
print_info("Generating Prompts in Normal Mode")
54+
55+
# Checking requirements
56+
try:
57+
with open ("prompt.txt", "r" ,encoding="utf-8") as template:
58+
template_data = template.read()
59+
if template_data == "":
60+
# throw error
61+
raise CustomError("Template file is empty. Please add some text to it.")
3462

35-
selection = input()
36-
if type(selection) is not int:
37-
print
38-
if selection > 0 and selection <= len(options):
39-
return selection - 1
40-
41-
63+
with open ("key-values.csv", "r", encoding="utf-8") as csv_values:
64+
csv_data = csv_values.read()
65+
if csv_data == "":
66+
raise CustomError("CSV file is empty. Please add some data to it.")
67+
68+
except Exception as e:
69+
print_error("Error:",e,"")
70+
return
71+
72+
print_success("Checking Requirements")
4273

4374

75+
# Checking for key-value pairs
76+
print_info("Generating Prompts")
77+
try:
78+
df = pd.read_csv("key-values.csv")
79+
[row_count , column_count] = df.shape
80+
columns = df.columns.values
81+
if columns[0] != "City" or columns[1] != "Title":
82+
raise CustomError("Invalid CSV Headers. Please make sure the CSV file has the correct format.")
83+
if column_count != 2:
84+
raise CustomError("Invalid CSV columns count. Please make sure the CSV file has the correct format.")
85+
print_info(f"{row_count} records found in CSV file. {row_count} prompts will be generated ")
86+
confirm_pause()
4487

88+
# Generate prompts
89+
if description_mode:
90+
for index, row in df.iterrows():
91+
prompt = template_data.replace("**/City/**", row["City"]).replace("**/Title/**", "")
92+
if not os.path.exists("prompts"):
93+
os.makedirs("prompts")
4594

95+
with open(f"prompts/{row['City']}_description.txt", "w", encoding="utf-8") as prompt_file:
96+
prompt_file.write(prompt)
97+
print_success(f"{index + 1} out of {row_count} generated successfully.")
98+
else:
99+
for index, row in df.iterrows():
100+
prompt = template_data.replace("**/City/**", row["City"]).replace("**/Title/**", row["Title"])
101+
if not os.path.exists("prompts"):
102+
os.makedirs("prompts")
103+
104+
with open(f"prompts/{row['City']}_{row['Title']}.txt", "w", encoding="utf-8") as prompt_file:
105+
prompt_file.write(prompt)
106+
print_success(f"{index + 1} out of {row_count} generated successfully.")
107+
108+
except Exception as e:
109+
print_error("Error: ", e, "")
110+
return
111+
112+
print_success("Prompts Generated Successfully")
113+
print_info("Prompts are saved in the prompts folder.")
46114

47115

48116

49-
clear_console()
50-
print('Welcome to Python Prompt Generator.\n')
51-
print('Please wait. Checking for required files and perimeters...')
52-
check_files()
53-
ask_choice("Select mode", ["Normal Mode" , "Description Mode (won't include title in prompt.)"])
117+
if __name__ == "__main__":
118+
if len(sys.argv) != 1:
119+
if sys.argv[1] == "-d":
120+
main(True)
121+
elif sys.argv[1] == "-h" or sys.argv[1] == "--help":
122+
help()
123+
else:
124+
print_warning("Invalid Argument. Use -h or --help for help.")
125+
else:
126+
main()
127+
128+
if error:
129+
print_info("Visit Github for more information and help: https://github.com/tensor35/Python-Prompt-Generator-Script")
130+
print("\n")
131+
exit()

0 commit comments

Comments
 (0)