Spaces:
Sleeping
Sleeping
import streamlit as st | |
import streamlit_authenticator as stauth | |
from deta import Deta | |
import yaml | |
from yaml.loader import SafeLoader | |
import os | |
from cryptography.fernet import Fernet | |
from free_speech_app.DataLoadDb import * | |
from free_speech_app.FreeSpeechPromptsResponses import * | |
from langchain.chat_models import ChatOpenAI | |
#connect to/create Deta user database | |
deta = Deta(st.secrets["deta_key"]) | |
db = deta.Base("user_data") | |
#fernet key (generated locally, stored in streamlit secrets) | |
fernet = Fernet(bytes(st.secrets["fernet_key"],'utf-8')) | |
#activeloop_token | |
os.environ["ACTIVELOOP_TOKEN"] = st.secrets["deeplake_key"] | |
config_drive = deta.Drive("passwords") | |
config = config_drive.get("config.yaml").read() | |
config = yaml.load(config, Loader=SafeLoader) | |
# Create an authenticator | |
authenticator = stauth.Authenticate( | |
config['credentials'], | |
config['cookie']['name'], | |
config['cookie']['key'], | |
config['cookie']['expiry_days'], | |
config['preauthorized'] | |
) | |
def get_user_data(user): | |
data = db.fetch().items | |
for person in data: | |
if person['key'] == user: | |
return person | |
return None | |
def encrypt(api_key: str, fernet) -> bytes: | |
"""Encrypt the API key.""" | |
return fernet.encrypt(api_key.encode()) | |
def decrypt(encrypted_api_key: bytes, fernet) -> str: | |
"""Decrypt the encrypted API key.""" | |
return fernet.decrypt(encrypted_api_key).decode() | |
# Render the login module | |
name, authentication_status, username = authenticator.login('Login', 'main') | |
# If the user is authenticated | |
if authentication_status: | |
authenticator.logout('Logout', 'main', key='unique_key') | |
st.write(f'Welcome *{name}*') | |
# Sidebar for navigation | |
page = st.sidebar.radio("Choose a page", ["Account Setup", "OpenAI API Key Setup", "Respond to Post"]) | |
# Fetch user data from the database | |
user_data = get_user_data(username) | |
if page == "Account Setup": | |
st.title("Account Setup") | |
st.markdown("Please use this page to provide your OpenAI API Key, Principles and Writing Style. **Please make sure to press the Save Changes button after providing the information.**") | |
# Input boxes with existing data | |
if 'api_key' not in st.session_state: | |
st.session_state.api_key = "" | |
api_input = st.text_input("Paste OpenAI API Key", value=decrypt(user_data["api_key"].encode()[2:-1], fernet) if user_data and "api_key" in user_data else "", type="password") | |
encrypted_api_key = str(encrypt(api_input, fernet)) | |
st.session_state.api_key = api_input | |
principles = st.text_input("My Principles (Paste Principles here)", placeholder = "Enter the main principles of your life you wish this response to uphold", value=user_data["principles"] if user_data and "principles" in user_data else "") | |
writing_style = st.text_input("My Writing Style (Paste Examples)", placeholder = "Provide examples of your writing style here", value=user_data["writing_style"] if user_data and "writing_style" in user_data else "") | |
sources = st.text_area("Sources (This autopopulates for your reference)", value=st.session_state.sources if 'sources' in st.session_state else '', key = 'sources_key', height = 100) | |
# Update button | |
if st.button("Save Changes"): | |
db.put({"key": username, "principles": principles, "writing_style": writing_style, "sources": sources, "api_key": encrypted_api_key}) | |
if page == "OpenAI API Key Setup": | |
st.title("OpenAI API Key Setup") | |
st.header('What is an API key?') | |
st.write('An API (Application Programming Interface) key is like a password that allows you to access certain functions or data from a website or service. Many sites use API keys to identify you and control access to their APIs.') | |
st.header('Why do you need an API key?') | |
st.write('API keys allow sites to track usage and prevent abuse of their services. They help keep things secure. When you request an API key, the site knows the calls are coming from you.') | |
image = 'apikeyex.png' | |
st.header('How to get an OpenAI API key:') | |
st.write('1. Go to https://platform.openai.com/account/api-keys') | |
st.write('2. Log in or create an OpenAI account if you do not have one') | |
st.write('3. Click "Create new secret key" and give your key a name') | |
st.image(image, caption=None, width=None, use_column_width=None, clamp=False, channels="RGB", output_format="auto") | |
st.write('4. Copy the generated API key and keep it private like a password') | |
st.header('Using your API key') | |
st.write('When making calls to the OpenAI API, include your API key in the request headers or parameters to authenticate.') | |
st.code('headers = {"Authorization": f"Bearer {YOUR_API_KEY}"}') | |
st.warning('Treat your API key like a secret! Do not share it publicly.') | |
elif page == "Respond to Post": | |
st.title("Respond to Post") | |
left_col, right_col = st.columns(2) | |
# Input boxes | |
with right_col: | |
background_info = st.text_area("Background information on original post (This autopopulates for your reference)", height = 700, value=st.session_state.background_info if 'background_info' in st.session_state else '', key = 'background_info_key') | |
with left_col: | |
original_post = st.text_area("Paste Original Post Here \n", height=100) | |
chat_mdl = None | |
draft_response = '' | |
# Check if the "Submit" button is clicked | |
if st.button("Submit"): | |
if st.session_state.api_key: | |
os.environ["OPENAI_API_KEY"] = st.session_state.api_key | |
# add condition to check for passphrase to allow use of DSI api key stored in secrets | |
if (os.environ["OPENAI_API_KEY"] == st.secrets["secret_passphrase"]): | |
os.environ["OPENAI_API_KEY"] = st.secrets["dsi_openai_key"] | |
chat_mdl = ChatOpenAI(model_name='gpt-4', temperature=0.1) | |
if chat_mdl is not None: | |
if user_data is None: | |
draft_response, background_text, sources_text = generate_custom_response(original_post, chat_mdl, "", "") | |
st.session_state.draft_response = draft_response.content | |
st.session_state.background_text = background_text | |
st.session_state.sources_text = sources_text | |
st.session_state.background_info = background_text | |
st.session_state.sources = sources_text | |
st.rerun() | |
else: | |
draft_response, background_text, sources_text = generate_custom_response(original_post, chat_mdl, user_data['principles'], user_data['writing_style']) | |
st.session_state.draft_response = draft_response.content | |
st.session_state.background_text = background_text | |
st.session_state.sources_text = sources_text | |
st.session_state.background_info = background_text | |
st.session_state.sources = sources_text | |
st.rerun() | |
# Ensure session state variables are initialized | |
if 'draft_response' not in st.session_state: | |
st.session_state.draft_response = '' | |
if 'regenerate_prompt' not in st.session_state: | |
st.session_state.regenerate_prompt = '' | |
# Output from function | |
response_textarea = st.text_area( | |
label="Draft Response. Please edit here or prompt suggestions in the box below.", | |
value=st.session_state.draft_response if 'draft_response' in st.session_state else '', | |
height=350, | |
key='draft_response_key' | |
) | |
# Initialization of the regeneration flag | |
if 'is_regenerating' not in st.session_state: | |
st.session_state.is_regenerating = False | |
# Check if the app is in the "regeneration" phase | |
if st.session_state.is_regenerating: | |
# Display the regenerated response explicitly | |
regenerate_prompt = st.text_area( | |
"Request a new draft", | |
value=st.session_state.regenerate_prompt, | |
placeholder="You may edit the regenerated draft directly above, or request further changes here.", | |
height=100, | |
key='regenerate_prompt_key' | |
) | |
# Reset the regeneration flag | |
st.session_state.is_regenerating = False | |
else: | |
# Normal behavior: display the text area for manual input | |
regenerate_prompt = st.text_area( | |
"Request a new draft", | |
placeholder="You may edit the draft directly above, or request a new draft with additional guidance here.", | |
height=100, | |
key='regenerate_prompt_key' | |
) | |
if (draft_response is not None) and (regenerate_prompt is not None): | |
if st.button("Regenerate"): | |
if st.session_state.api_key: | |
os.environ['OPENAI_API_KEY'] = st.session_state.api_key | |
# add condition to check for passphrase to allow use of DSI api key stored in secrets | |
if (os.environ["OPENAI_API_KEY"] == st.secrets["secret_passphrase"]): | |
os.environ["OPENAI_API_KEY"] = st.secrets["dsi_openai_key"] #umang key | |
elif (os.environ["OPENAI_API_KEY"] == st.secrets["secret_passphrase2"]): | |
os.environ["OPENAI_API_KEY"] = st.secrets["dsi_openai_key2"] #abbie key | |
chat_mdl = ChatOpenAI(model_name='gpt-4', temperature=0.1) | |
if chat_mdl is not None: | |
updated_response = regenerate_custom_response(chat_mdl, regenerate_prompt, st.session_state.draft_response).content | |
st.session_state.draft_response = updated_response | |
st.session_state.is_regenerating = True | |
st.rerun() | |
elif authentication_status is False: | |
st.error('Username/password is incorrect') | |
#added registration module if username/password is incorrect | |
try: | |
if authenticator.register_user('New User Registration', preauthorization=False): | |
st.success('User Registered Successfully! Please log in above.') | |
except Exception as e: | |
st.error(e) | |
elif authentication_status is None: | |
st.warning('Please enter your username and password') | |
try: | |
if authenticator.register_user('New User Registration', preauthorization=False): | |
st.success('User Registered Successfully! Please log in above.') | |
except Exception as e: | |
st.error(e) | |
with open('config.yaml', 'w') as file: | |
yaml.dump(config, file, default_flow_style=False) | |
config_drive.put("config.yaml", path = "config.yaml") | |