diff --git a/hackGPT.py b/hackGPT.py index 30d15ef..b6d7787 100755 --- a/hackGPT.py +++ b/hackGPT.py @@ -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=''' * ) ) ( `( ( /(( ( ( )\ @@ -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) @@ -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']) @@ -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() @@ -181,10 +181,12 @@ 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, @@ -192,17 +194,22 @@ def add_text(state, text): 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() @@ -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')]) @@ -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() @@ -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 ------------------------------------ diff --git a/hackerParents/hackerParents.py b/hackerParents/hackerParents.py index 5fa41bd..24f8d3e 100644 --- a/hackerParents/hackerParents.py +++ b/hackerParents/hackerParents.py @@ -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:") @@ -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('
OpenAI analysis of results
', 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() @@ -39,11 +42,14 @@ 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" @@ -51,11 +57,11 @@ def get_persona_files(): 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, @@ -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] @@ -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") @@ -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, @@ -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)