Spaces:
Sleeping
Sleeping
File size: 5,885 Bytes
85570bf 7649c90 e5b9c49 85570bf 558a24d 85570bf e5b9c49 0611f13 e5b9c49 0611f13 e5b9c49 0611f13 e5b9c49 7649c90 85570bf 558a24d 314a38e 85570bf 2733ff9 85570bf 2733ff9 558a24d b7658ca 2733ff9 85570bf e5b9c49 2733ff9 85570bf 2733ff9 85570bf e5b9c49 2733ff9 85570bf e5b9c49 0611f13 d9aac70 0611f13 844eeba 2733ff9 14208b2 e5b9c49 2733ff9 e5b9c49 2733ff9 e5b9c49 0611f13 2733ff9 0611f13 2733ff9 0611f13 2733ff9 f10ccac 2733ff9 f10ccac 2733ff9 f10ccac 85570bf f10ccac |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
import openai
import gradio as gr
import os
import psycopg2
from urllib.parse import urlparse
# Initialize OpenAI client
client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Database URL
DATABASE_URL = os.getenv('DATABASE_URL')
# Parse the database URL
result = urlparse(DATABASE_URL)
username = result.username
password = result.password
database = result.path[1:]
hostname = result.hostname
port = result.port
# Connect to the database
def connect_db():
try:
conn = psycopg2.connect(
dbname=database,
user=username,
password=password,
host=hostname,
port=port
)
return conn
except Exception as e:
print(f"Error connecting to the database: {e}")
return None
# Create table if not exists
def create_table():
conn = connect_db()
if conn:
cur = conn.cursor()
create_table_query = '''
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_transcripts (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
transcript TEXT NOT NULL,
timestamp TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);
'''
cur.execute(create_table_query)
conn.commit()
cur.close()
conn.close()
# Store chat transcript
def store_transcript(user_id, transcript):
conn = connect_db()
if conn:
cur = conn.cursor()
insert_query = '''
INSERT INTO chat_transcripts (user_id, transcript)
VALUES (%s, %s);
'''
cur.execute(insert_query, (user_id, transcript))
conn.commit()
cur.close()
conn.close()
# Register new user
def register_user(username, password):
conn = connect_db()
if conn:
cur = conn.cursor()
insert_query = '''
INSERT INTO users (username, password)
VALUES (%s, %s) RETURNING id;
'''
cur.execute(insert_query, (username, password))
user_id = cur.fetchone()[0]
conn.commit()
cur.close()
conn.close()
return user_id
return None
# Authenticate user
def authenticate(username, password):
conn = connect_db()
if conn:
cur = conn.cursor()
select_query = '''
SELECT id FROM users WHERE username = %s AND password = %s;
'''
cur.execute(select_query, (username, password))
user_id = cur.fetchone()
cur.close()
conn.close()
if user_id:
return user_id[0]
return None
# Initialize the table
create_table()
# Initial system messages for the chatbot
initial_messages = [
{"role": "system", "content": "You are an attachment and close relationship research surveyor"},
{"role": "user", "content": """ask me each question from this questionnaire and rewrite it as an open ended question and wait for each response. Empathize with me and regularly ask for clarification why I answered with a certain response. Here is the questionnaire:
Can you describe your relationship with your mother or a mother-like figure in your life?
Do you usually discuss your problems and concerns with your mother or a mother-like figure?
"""},
]
def chatbot(input, state):
user_id = state[0]
messages = state[1]
if input:
messages.append({"role": "user", "content": input})
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages
)
reply = response.choices[0].message["content"]
messages.append({"role": "assistant", "content": reply})
conversation = ""
for message in messages[2:]:
role = "You" if message["role"] == "user" else "AttachmentBot"
conversation += f"{role}: {message['content']}\n"
store_transcript(user_id, conversation)
return conversation, [user_id, messages]
with gr.Blocks() as demo:
username = gr.Textbox(label="Username")
password = gr.Textbox(label="Password", type="password")
login_button = gr.Button("Login")
register_button = gr.Button("Register")
auth_message = gr.Textbox(visible=False)
chat_input = gr.Textbox(lines=7, label="Chat with AttachmentBot", visible=False)
chat_output = gr.Textbox(label="Conversation", visible=False)
state = gr.State([None, initial_messages.copy()])
def login(username, password):
user_id = authenticate(username, password)
if user_id:
return gr.update(visible=True), gr.update(visible=True), [user_id, initial_messages.copy()], ""
else:
return gr.update(visible=False), gr.update(visible=False), [None, initial_messages.copy()], "Invalid credentials"
def register(username, password):
user_id = register_user(username, password)
if user_id:
return gr.update(visible=True), gr.update(visible=True), [user_id, initial_messages.copy()], "Registration successful, you can now login."
else:
return gr.update(visible=False), gr.update(visible=False), [None, initial_messages.copy()], "Registration failed, try a different username."
login_button.click(login, inputs=[username, password], outputs=[chat_input, chat_output, state, auth_message])
register_button.click(register, inputs=[username, password], outputs=[chat_input, chat_output, state, auth_message])
chat_interface = gr.Interface(
fn=chatbot,
inputs=[chat_input, state],
outputs=[chat_output, state],
title="AttachmentBot",
description="Let me survey you about your attachment with certain people in your life. To begin, enter 'start'."
)
demo.launch() |