Spaces:
Sleeping
Sleeping
File size: 8,265 Bytes
85570bf 7649c90 e5b9c49 6d39a16 85570bf 558a24d 0bcd8c0 85570bf e5b9c49 3d80860 e5b9c49 3d80860 e5b9c49 0611f13 e5b9c49 0611f13 e5b9c49 a634a94 e5b9c49 0611f13 a634a94 6d39a16 a634a94 e5b9c49 a634a94 7649c90 85570bf 558a24d 314a38e 85570bf 2733ff9 85570bf 2733ff9 0bcd8c0 b7658ca 2733ff9 85570bf 66cbf2b 2733ff9 85570bf 2733ff9 85570bf e5b9c49 2733ff9 85570bf e5b9c49 6d39a16 a634a94 e5b9c49 2733ff9 e5b9c49 2733ff9 e5b9c49 0611f13 2733ff9 0611f13 1ce9293 0611f13 91f2b1e a634a94 2733ff9 a634a94 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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
import openai
import gradio as gr
import os
import psycopg2
from urllib.parse import urlparse
import json
# 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)
db_username = result.username
db_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=db_username,
password=db_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
);
CREATE TABLE IF NOT EXISTS survey_responses (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
responses JSONB,
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
# Store survey responses
def store_survey_responses(user_id, responses):
conn = connect_db()
if conn:
cur = conn.cursor()
insert_query = '''
INSERT INTO survey_responses (user_id, responses)
VALUES (%s, %s);
'''
cur.execute(insert_query, (user_id, json.dumps(responses))) # Convert dictionary to JSON string
conn.commit()
cur.close()
conn.close()
# Initialize the table
create_table()
# Survey questions with different input types
survey_questions = [
{"question": "On a scale of 1 to 5, how are you feeling today?", "type": "scale", "options": ["1", "2", "3", "4", "5"]},
{"question": "How often do you feel stressed?", "type": "multiple_choice", "options": ["Never", "Rarely", "Sometimes", "Often", "Always"]},
{"question": "Do you have trouble sleeping? (True/False)", "type": "true_false"}
]
# Function to create survey inputs dynamically
def create_survey_inputs():
inputs = []
for q in survey_questions:
if q["type"] == "scale":
inputs.append(gr.Radio(label=q["question"], choices=q["options"]))
elif q["type"] == "multiple_choice":
inputs.append(gr.Radio(label=q["question"], choices=q["options"]))
elif q["type"] == "true_false":
inputs.append(gr.Radio(label=q["question"], choices=["True", "False"]))
return inputs
# 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:
with gr.Row():
with gr.Column():
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)
with gr.Column():
survey_inputs = create_survey_inputs()
submit_survey = gr.Button("Submit Survey")
with gr.Column():
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."
def submit_survey_fn(*responses):
state = responses[-1]
responses = responses[:-1]
user_id = state[0]
survey_responses = {survey_questions[i]["question"]: responses[i] for i in range(len(responses))}
store_survey_responses(user_id, survey_responses)
return gr.update(visible=True), gr.update(visible=True), state
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])
submit_survey.click(submit_survey_fn, inputs=survey_inputs + [state], outputs=[chat_input, chat_output, state])
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() |