AjithKSenthil commited on
Commit
e5b9c49
·
verified ·
1 Parent(s): 9385d5e

Update chatbot.py

Browse files
Files changed (1) hide show
  1. chatbot.py +96 -11
chatbot.py CHANGED
@@ -1,10 +1,74 @@
1
  import openai
2
  import gradio as gr
3
  import os
 
 
4
 
5
  # Initialize OpenAI client
6
  client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  # Initial system messages for the chatbot
9
  initial_messages = [
10
  {"role": "system", "content": "You are an attachment and close relationship research surveyor"},
@@ -14,7 +78,7 @@ Do you usually discuss your problems and concerns with your mother or a mother-l
14
  """},
15
  ]
16
 
17
- def chatbot(input):
18
  if not hasattr(chatbot, "messages"):
19
  chatbot.messages = initial_messages.copy()
20
 
@@ -24,7 +88,7 @@ def chatbot(input):
24
  model="gpt-3.5-turbo",
25
  messages=chatbot.messages
26
  )
27
- reply = response.choices[0].message.content
28
  chatbot.messages.append({"role": "assistant", "content": reply})
29
 
30
  conversation = ""
@@ -32,15 +96,36 @@ def chatbot(input):
32
  role = "You" if message["role"] == "user" else "AttachmentBot"
33
  conversation += f"{role}: {message['content']}\n"
34
 
 
35
  return conversation
36
 
37
- inputs = gr.Textbox(lines=7, label="Chat with AttachmentBot")
38
- outputs = gr.Textbox(label="Conversation")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- gr.Interface(
41
- fn=chatbot,
42
- inputs=inputs,
43
- outputs=outputs,
44
- title="AttachmentBot",
45
- description="Let me survey you about your attachment with certain people in your life. To begin, enter 'start'."
46
- ).launch()
 
1
  import openai
2
  import gradio as gr
3
  import os
4
+ import psycopg2
5
+ from urllib.parse import urlparse
6
 
7
  # Initialize OpenAI client
8
  client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
9
 
10
+ # Database URL
11
+ DATABASE_URL = os.getenv('DATABASE_URL')
12
+
13
+ # Parse the database URL
14
+ result = urlparse(DATABASE_URL)
15
+
16
+ username = result.username
17
+ password = result.password
18
+ database = result.path[1:]
19
+ hostname = result.hostname
20
+ port = result.port
21
+
22
+ # Connect to the database
23
+ def connect_db():
24
+ try:
25
+ conn = psycopg2.connect(
26
+ dbname=database,
27
+ user=username,
28
+ password=password,
29
+ host=hostname,
30
+ port=port
31
+ )
32
+ return conn
33
+ except Exception as e:
34
+ print(f"Error connecting to the database: {e}")
35
+ return None
36
+
37
+ # Create table if not exists
38
+ def create_table():
39
+ conn = connect_db()
40
+ if conn:
41
+ cur = conn.cursor()
42
+ create_table_query = '''
43
+ CREATE TABLE IF NOT EXISTS chat_transcripts (
44
+ id SERIAL PRIMARY KEY,
45
+ user_id VARCHAR(255) NOT NULL,
46
+ transcript TEXT NOT NULL,
47
+ timestamp TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
48
+ );
49
+ '''
50
+ cur.execute(create_table_query)
51
+ conn.commit()
52
+ cur.close()
53
+ conn.close()
54
+
55
+ # Store chat transcript
56
+ def store_transcript(user_id, transcript):
57
+ conn = connect_db()
58
+ if conn:
59
+ cur = conn.cursor()
60
+ insert_query = '''
61
+ INSERT INTO chat_transcripts (user_id, transcript)
62
+ VALUES (%s, %s);
63
+ '''
64
+ cur.execute(insert_query, (user_id, transcript))
65
+ conn.commit()
66
+ cur.close()
67
+ conn.close()
68
+
69
+ # Initialize the table
70
+ create_table()
71
+
72
  # Initial system messages for the chatbot
73
  initial_messages = [
74
  {"role": "system", "content": "You are an attachment and close relationship research surveyor"},
 
78
  """},
79
  ]
80
 
81
+ def chatbot(user_id, input):
82
  if not hasattr(chatbot, "messages"):
83
  chatbot.messages = initial_messages.copy()
84
 
 
88
  model="gpt-3.5-turbo",
89
  messages=chatbot.messages
90
  )
91
+ reply = response.choices[0].message["content"]
92
  chatbot.messages.append({"role": "assistant", "content": reply})
93
 
94
  conversation = ""
 
96
  role = "You" if message["role"] == "user" else "AttachmentBot"
97
  conversation += f"{role}: {message['content']}\n"
98
 
99
+ store_transcript(user_id, conversation)
100
  return conversation
101
 
102
+ def authenticate(username, password):
103
+ # Replace with actual authentication logic
104
+ if username == "user" and password == "pass":
105
+ return username
106
+ else:
107
+ return None
108
+
109
+ with gr.Blocks() as demo:
110
+ username = gr.Textbox(label="Username")
111
+ password = gr.Textbox(label="Password", type="password")
112
+ login_button = gr.Button("Login")
113
+
114
+ chat_interface = gr.Interface(
115
+ fn=chatbot,
116
+ inputs=[gr.Textbox(label="User ID"), gr.Textbox(lines=7, label="Chat with AttachmentBot")],
117
+ outputs=gr.Textbox(label="Conversation"),
118
+ title="AttachmentBot",
119
+ description="Let me survey you about your attachment with certain people in your life. To begin, enter 'start'."
120
+ )
121
+
122
+ def login(username, password):
123
+ user_id = authenticate(username, password)
124
+ if user_id:
125
+ return gr.update(visible=True), user_id, ""
126
+ else:
127
+ return gr.update(visible=False), "", "Invalid credentials"
128
+
129
+ login_button.click(login, inputs=[username, password], outputs=[chat_interface, gr.Variable(), gr.Textbox(visible=False)])
130
 
131
+ demo.launch()