Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added some comments and changed some things to use fstrings #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions hackGPT.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,13 @@


# Load API key from an environment variable or secret management service

load_dotenv(".env")
apiToken = os.environ.get('OPENAI_TOKEN')
openai.api_key = apiToken

if 'OPENAI_TOKEN' in os.environ:
pass
else:
# If API key is not found, prompt user to enter it
error='''
* ) ) (
`( ( /(( ( ( )\
Expand Down Expand Up @@ -72,6 +71,7 @@

load_dotenv()
apiToken = os.environ.get("OPENAI_TOKEN")
# Add headers to API requests containing our OpenAI API key
headers = {
"Accept": "application/json; charset=utf-8",
"Authorization": "Token" + str(apiToken)
Expand Down Expand Up @@ -126,7 +126,7 @@ def progress(percent=0, width=15):
for pair in zip(*map(str.splitlines, (fadedhack, fadedgpt))):
print(*pair)
#------------------------------------ main menu prompt ------------------------------------

# Open the hackGPT_log file and create a new row for Date, Persona, Query, and Response
with open('output/chat_hackGPT_log.csv', 'a+', encoding='UTF8', newline='') as f:
w = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
w.writerow(['Date', 'Persona', 'Query', 'Response'])
Expand All @@ -140,7 +140,7 @@ def progress(percent=0, width=15):

answers = inquirer.prompt(questions)
hackgpt_persona = answers['Persona']

# Checks the value of hackgpt_persona and selects the corresponding persona text file to read
if hackgpt_persona =='hackGPT':
hackGPT_mode = open('personas/hackGPTv1.md' ,"r")
hackGPT_mode = hackGPT_mode.read()
Expand Down Expand Up @@ -181,28 +181,35 @@ def progress(percent=0, width=15):
# w.writerow([date_string, hackgpt_persona, str(line).strip('\n'), str(response).lstrip('\n')])
# f.close()
#
# Function to add user input text to the chatbot
def add_text(state, text):
# Create a response using OpenAI GPT-3 language model
response = openai.Completion.create(
model="text-davinci-003",
prompt=str(hackGPT_mode) + str(text),
prompt=f"{hackGPT_mode}{text}",
temperature=0,
max_tokens=3000,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\"\"\""]
)
# Extract response text from the response object
response = response['choices'][0]['text']
# Add the user input text and generated response to the state variable
state = state + [(str(response),str(text))]

try:
try:
# Append the user input text and generated response to the chat log CSV file
with open('output/chat_hackGPT_log.csv', 'a+', encoding='UTF8', newline='') as f:
w = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
w.writerow([date_string, hackgpt_persona, str(text).strip('\n'), str(response).lstrip('\n')])
f.close()

finally:
# Return the updated state variable
return state, state
# Function to add a file to the chatbot
def add_file(file_state, file):
with open(file.name, 'r') as targets:
search = targets.read()
Expand All @@ -218,8 +225,10 @@ def add_file(file_state, file):
)

file_response = response['choices'][0]['text']
file_state = file_state + [("" + str(file_response), "Processed file: "+ str(file.name))]
# Add the file name and generated response to the file state variable
file_state = file_state + [(f"" + str(file_response), f"Processed file: {file.name}")]
try:
# Append the file name and generated response to the file log CSV file
with open('output/chat_hackGPT_file_log.csv', 'a+', encoding='UTF8', newline='') as f:
w = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
w.writerow([date_string, hackgpt_persona, str(search).strip('\n'), str(response).lstrip('\n')])
Expand All @@ -228,7 +237,7 @@ def add_file(file_state, file):
finally:
return file_state, file_state


# Set up the chatbot interface
with gr.Blocks(css="#chatbot .output::-webkit-scrollbar {display: none;}") as hackerchat:
state = gr.State([])
chatbot = gr.Chatbot()
Expand All @@ -242,7 +251,7 @@ def add_file(file_state, file):
txt.submit(add_text, [state, txt], [ chatbot, state])
txt.submit(lambda :"", None, txt)
btn.upload(add_file, [state, btn], [state, chatbot])

# Open the chatbot in a web browser
webbrowser.open("http://127.0.0.1:1337")
#subprocess.call(["sort", "-h output/chat_hackGPT_log.csv", "|", "res/tools/csv_hack", "|", "lolcat -p 23"])
#------------------------------------ results sample ------------------------------------
Expand Down
48 changes: 37 additions & 11 deletions hackerParents/hackerParents.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@




# Load OpenAI API key from .env file
load_dotenv('.env')
openai.api_key = os.environ.get('OPENAI_API_KEY')

# If API key is not found, prompt user to enter it
if not openai.api_key:
openai.api_key = st.text_input("Enter OPENAI_API_KEY API key")
openai.api_key = st.text_input("Enter OPENAI_API_KEY API key: ")
set_key('.env', 'OPENAI_API_KEY', openai.api_key)

# Set environment variable for OpenAI API key
os.environ['OPENAI_API_KEY'] = openai.api_key

# Set streamlit page configuration, title, favicon, and layout
st.set_page_config(page_title="𝚑𝚊𝚌𝚔🅶🅿🆃", page_icon="https://raw.githubusercontent.com/NoDataFound/hackGPT/main/res/hackgpt_fav.png", layout="wide")
st.header("Welcome to 𝚑𝚊𝚌𝚔𝚎𝚛🅿🅰🆁🅴🅽🆃🆂")
st.text("powered by:")
Expand All @@ -31,6 +32,8 @@
logo_col, text_col = st.sidebar.columns([1, 3])
logo_col.image('https://seeklogo.com/images/O/open-ai-logo-8B9BFEDC26-seeklogo.com.png', width=32)
text_col.write('<div style="text-align: left;">OpenAI analysis of results</div>', unsafe_allow_html=True)

# Load list of local persona files
def get_persona_files():
return [f.split(".")[0] for f in os.listdir("personas") if f.endswith(".md")]
persona_files = get_persona_files()
Expand All @@ -39,23 +42,26 @@ def get_persona_files():

selected_persona = st.sidebar.selectbox("👤 Select Local Persona", [""] + persona_files)

# Set default temperature value
default_temperature = 0.0
# Allow user to adjust temperature slider
temperature = st.sidebar.slider(
"Temperature | Creative >0.5", min_value=0.0, max_value=1.0, step=0.1, value=default_temperature
)

# Load social media data from CSV file
with open(os.path.join("social_data.csv"), "r") as f:

#url = "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"
data = pd.read_csv(f)
new_row = pd.DataFrame({"Social Media": [" "], "Privacy Policy Link": [""]})
data = pd.concat([data, new_row], ignore_index=True)

# Data Sources
# Extract social media and privacy policy link data
social_media = data['Social Media']
privacy_link = data['Privacy Policy Link']

# Filter
# Select which services to check for privacy policies (filter)
options = st.multiselect(
'**Select the services to check:**',
options=social_media,
Expand All @@ -65,32 +71,41 @@ def get_persona_files():
#if query:
# data = data[data['prompt'].str.contains(query, case=False)]

# Display persona management options in sidebar
persona_files = [f.split(".")[0] for f in os.listdir("personas") if f.endswith(".txt")]

# Create an expander in the sidebar to manage personas
expand_section = st.sidebar.expander("👤 Manage Personas", expanded=False)
with expand_section:
#st.subheader("👤 Manage Personas")
# If a persona is selected, display its name and prompt
if selected_persona:
with open(os.path.join("personas", f"{selected_persona}.md"), "r") as f:
persona_text = f.read()
# Allow users to edit the name and prompt of the persona
new_persona_name = st.text_input("Persona Name:", value=selected_persona)
new_persona_prompt = st.text_area("Persona Prompt:", value=persona_text, height=100)
# If the name or prompt has changed, update the file
if new_persona_name != selected_persona or new_persona_prompt != persona_text:
with open(os.path.join("personas", f"{new_persona_name}.md"), "w") as f:
f.write(new_persona_prompt)
# If the name has changed, delete the old file and update the list of persona files
if new_persona_name != selected_persona:
os.remove(os.path.join("personas", f"{selected_persona}.md"))
persona_files.remove(selected_persona)
persona_files.append(new_persona_name)
selected_persona = new_persona_name
# Allow users to delete the persona
if st.button("➖ Delete Persona"):
if st.warning("Persona Deleted"):
os.remove(os.path.join("personas", f"{selected_persona}.md"))
persona_files.remove(selected_persona)
selected_persona = ""
# Create an expander in the sidebar to manage social media sources
expand_section = st.sidebar.expander("🥷 Social Media Sources", expanded=False)
with expand_section:
# Select a social media source from a dropdown list
selected_act = st.selectbox('', data['Social Media'])
# Show or hide the social media table
show_remote_prompts = st.checkbox("Show Social Media Table")
if selected_act and selected_act.strip():
selected_prompt = data.loc[data['Social Media'] == selected_act, 'Privacy Policy Link'].values[0]
Expand All @@ -100,33 +115,41 @@ def get_persona_files():
# os.mkdir("personas")
# with open(os.path.join("personas", f"{selected_act}_remote.md"), "w") as f:
# f.write(selected_prompt)
# Create an expander in the sidebar to add a new persona
expand_section = st.sidebar.expander("➕ Add new Persona", expanded=False)
# Display social media table if `show_remote_prompts` is True
if show_remote_prompts:
st.write(data[['Social Media', 'Privacy Policy Link']].style.hide(axis="index").set_properties(subset='Privacy Policy Link', **{
'max-width': '100%',
'white-space': 'pre-wrap'
}))
# Add a new persona using the expander
with expand_section:
st.subheader("➕ Add new Persona")
st.text("Press enter to update/save")
# Get existing persona files
persona_files = get_persona_files()
# Take new persona name as input
new_persona_name = st.text_input("Persona Name:")
# Check if the new persona name is existing or not
if new_persona_name in persona_files:
st.error("This persona name already exists. Please choose a different name.")
else:
# Take persona prompt as input and write it to file
new_persona_prompt = st.text_area("Persona Prompt:", height=100)
if new_persona_name and new_persona_prompt:
with open(os.path.join("personas", f"{new_persona_name}.md"), "w") as f:
f.write(new_persona_prompt)
# Update the list of persona files and show only newly created persona
persona_files.append(new_persona_name)
selected_persona = new_persona_name
# If a persona is selected, show the chat interface
if selected_persona:
# Read persona text data from file
with open(os.path.join("personas", f"{selected_persona}.md"), "r") as f:
persona_text = f.read()
#st.text("Press Enter to add")



# Take user input and append it to chat history
with open(os.path.join("personas", f"{selected_persona}.md"), "r") as f:
persona_text = f.read()
#st.text("Press Enter/Return to send text")
Expand All @@ -137,8 +160,9 @@ def get_persona_files():
with open(os.path.join("personas", f"{selected_persona}.md"), "r") as f:
persona_text = f.read()
chat_history.append(("You", user_input))

# Generate a prompt using persona text and chat history and get AI-generated response
prompt = f"Based on {persona_text} {' '.join([f'{m[0]}: {m[1]}' for m in chat_history])} check against {options} and return a yes or no if appropriate and summarize why. "
# Generate AI response using the text-davinci-003 engine
completions = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
Expand All @@ -147,7 +171,9 @@ def get_persona_files():
stop=None,
temperature=temperature,
)
# Get the AI-generated response and append it to chat history
results = completions.choices[0].text.strip()
chat_history.append((selected_persona, results))
# Show AI-generated response in chat interface
st.markdown(results, unsafe_allow_html=True)