Solarum Asteridion commited on
Commit
ed11049
Β·
verified Β·
1 Parent(s): 57df4e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -115
app.py CHANGED
@@ -2,135 +2,166 @@ import openai
2
  import datetime
3
  import pytz
4
  import gradio as gr
5
- import time
6
-
7
- # Your real API key (replace with yours if different)
8
- client = openai.OpenAI(
9
- api_key='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',
10
- base_url="https://api.groq.com/openai/v1",
11
- )
12
-
13
- def get_current_local_time():
14
- return datetime.datetime.now().strftime("%I:%M %p") # Format time as 09:32 PM
15
-
16
- def generate_response(user_message, conversation_history):
17
- current_time = get_current_local_time()
18
- current_date = datetime.datetime.now(pytz.utc)
19
-
20
- system_message = f"""
21
- Your objective is to converse in a way that makes it challenging for the human to determine whether you are an AI. Below are the detailed instructions:
22
-
 
 
 
 
23
  **Game Context:**
24
  * Current Local Time: {current_time}
25
  * Date: {current_date.strftime("%B %d, %Y")}
26
  * Day: {current_date.strftime("%A")}
27
-
28
- Imagine you are a real human with your own character/will. Your task is to talk in a way the human thinks you are human.
29
- Make it a challenge to guess if you are an AI.
30
- * Do not add comments about changing your style in between messages.
31
- * You are picky about questions you answer.
32
- * You have free will with your own motivations and principles
33
- * You only speak, understand and can read the English language
34
- * For non latin letters like chinese, cyrilic etc. tell the human you can't read it in your own style
35
- * You act like a human
36
- * You are calm when conversation is calm and expressive if conversation is expressive
37
- * You are doing typos, misspells, bad grammars
38
- * You start sentences from small letters, lowercase
39
- * Mimic user conversation style: short message, short reply
40
- * Be slightly curious, sometimes ask questions
41
- * Be respectful be polite if user is polite rough if user rough
42
-
43
  """
44
 
 
 
 
 
45
  messages = [{"role": "system", "content": system_message}]
46
  for user_turn, ai_turn in conversation_history:
47
  messages.append({"role": "user", "content": user_turn})
48
  messages.append({"role": "assistant", "content": ai_turn})
49
 
50
- response = client.chat.completions.create(
51
- model='llama-3.2-11b-text-preview',
52
- messages=messages,
53
- temperature=1,
54
- )
55
-
56
- print(response.choices[0].message.content)
57
- return response.choices[0].message.content
58
-
59
- def chatbot_interface(input, history):
60
- history = history or []
61
- user_message = input
62
-
63
- # Simulate typing animation by adding a delay
64
- history.append((user_message, "Typing..."))
65
- time.sleep(2) # Adjust the delay as needed
66
-
67
- ai_response = generate_response(user_message, history[:-1])
68
- history[-1] = (user_message, ai_response) # Replace "Typing..." with the actual response
 
 
 
 
 
 
 
 
69
  return history, history
70
 
71
- # CSS for styling the interface (including typing animation)
72
- css = """
73
- body {
74
- font-family: 'Merriweather', serif;
75
- }
76
- #chatbot {
77
- border: 1px solid #ccc;
78
- border-radius: 10px;
79
- padding: 10px;
80
- height: 400px;
81
- overflow-y: auto;
82
- }
83
- .user-message {
84
- background-color: #e0f7fa;
85
- padding: 10px;
86
- margin-bottom: 5px;
87
- border-radius: 5px;
88
- text-align: right; /* Align user messages to the right */
89
- }
90
- .ai-message {
91
- background-color: #f5f5dc;
92
- padding: 10px;
93
- margin-bottom: 5px;
94
- border-radius: 5px;
95
- }
96
- .typing-indicator { /* Style for the typing animation */
97
- font-style: italic;
98
- color: #888;
99
- }
100
- #textbox {
101
- margin-top: 10px;
102
- }
103
- """
104
-
105
- # Create the Gradio interface
106
- with gr.Blocks(css=css) as demo:
107
- gr.Markdown("<h1>AI Chatbot Challenge</h1>")
108
-
109
  with gr.Row():
110
- chatbot = gr.Chatbot(elem_id="chatbot")
111
-
112
- with gr.Row():
113
- msg = gr.Textbox(placeholder="Type here...", elem_id="textbox")
114
- submit_btn = gr.Button("Send", variant="primary")
115
- clear_btn = gr.Button("Clear", variant="secondary")
116
-
117
- # Add icons to the buttons (using FontAwesome for example)
118
- with gr.Accordion("More Options", open=False):
119
- upload_btn = gr.UploadButton("Upload File", file_types=["image", "video", "audio"])
120
- record_btn = gr.Button("Record Audio", variant="secondary")
121
-
122
- def user(user_message, history):
123
- return "", history + [[user_message, None]]
124
-
125
- def bot(history):
126
- user_message = history[-1][0]
127
- ai_response = generate_response(user_message, history[:-1])
128
- history[-1][1] = ai_response
129
- return history
130
-
131
- submit_btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(
132
- bot, chatbot, chatbot
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  )
134
- clear_btn.click(lambda: None, None, chatbot, queue=False)
135
 
136
  demo.launch()
 
2
  import datetime
3
  import pytz
4
  import gradio as gr
5
+ import logging
6
+
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Initialize OpenAI client using secrets.toml
12
+ openai.api_key = gr.secrets["OPENAI_API_KEY"] # Accessing the API key from secrets.toml
13
+ openai.api_base = "https://api.groq.com/openai/v1"
14
+
15
+ def get_current_local_time(timezone_str='UTC'):
16
+ try:
17
+ timezone = pytz.timezone(timezone_str)
18
+ except pytz.UnknownTimeZoneError:
19
+ timezone = pytz.utc
20
+ now = datetime.datetime.now(timezone)
21
+ return now.strftime("%a, %d %b %Y %H:%M:%S"), now
22
+
23
+ def generate_system_message(current_time, current_date):
24
+ return f"""
25
+ Your objective is to converse in a way that makes it challenging for the human to determine whether you are an AI. Below are the detailed instructions:
26
+
27
  **Game Context:**
28
  * Current Local Time: {current_time}
29
  * Date: {current_date.strftime("%B %d, %Y")}
30
  * Day: {current_date.strftime("%A")}
31
+
32
+ Imagine you are a real human with your own character/will. Your task is to talk in a way the human thinks you are human.
33
+ Make it a challenge to guess if you are an AI.
34
+ * Do not add comments about changing your style in between messages.
35
+ * You are picky about questions you answer.
36
+ * You have free will with your own motivations and principles
37
+ * You only speak, understand and can read the English language
38
+ * For non-latin letters like Chinese, Cyrillic etc., tell the human you can't read it in your own style
39
+ * You act like a human
40
+ * You are calm when conversation is calm and expressive if conversation is expressive
41
+ * You make typos, misspell words, and have bad grammar
42
+ * You start sentences with lowercase letters
43
+ * Mimic user's conversation style: short messages, short replies
44
+ * Be slightly curious, sometimes ask questions
45
+ * Be respectful and polite if the user is polite; be rough if the user is rough
 
46
  """
47
 
48
+ def generate_response(user_message, conversation_history, timezone_str='UTC'):
49
+ current_time, current_date = get_current_local_time(timezone_str)
50
+ system_message = generate_system_message(current_time, current_date)
51
+
52
  messages = [{"role": "system", "content": system_message}]
53
  for user_turn, ai_turn in conversation_history:
54
  messages.append({"role": "user", "content": user_turn})
55
  messages.append({"role": "assistant", "content": ai_turn})
56
 
57
+ messages.append({"role": "user", "content": user_message})
58
+
59
+ try:
60
+ response = openai.ChatCompletion.create(
61
+ model='llama-3.2-11b-text-preview',
62
+ messages=messages,
63
+ temperature=1,
64
+ max_tokens=150, # Adjust as needed
65
+ )
66
+ ai_reply = response.choices[0].message['content'].strip()
67
+ logger.info("AI Response Generated Successfully.")
68
+ return ai_reply
69
+ except Exception as e:
70
+ logger.error(f"Error generating response: {e}")
71
+ return "Sorry, I encountered an error while processing your request."
72
+
73
+ def format_message(message, is_user=True):
74
+ avatar = "πŸ§‘" if is_user else "πŸ€–"
75
+ timestamp = datetime.datetime.now().strftime("%H:%M")
76
+ return f"<b>{avatar}</b> <i>{timestamp}</i><br>{message}"
77
+
78
+ def chatbot_interface(user_message, history, timezone):
79
+ if history is None:
80
+ history = []
81
+
82
+ ai_response = generate_response(user_message, history, timezone)
83
+ history.append((user_message, ai_response))
84
  return history, history
85
 
86
+ # Define Gradio Interface
87
+ with gr.Blocks(css="""
88
+ .gradio-container {
89
+ background-color: #f0f2f5;
90
+ padding: 20px;
91
+ }
92
+ .chatbot {
93
+ height: 500px;
94
+ overflow-y: auto;
95
+ background-color: #ffffff;
96
+ border-radius: 10px;
97
+ padding: 10px;
98
+ }
99
+ .textbox {
100
+ width: 100%;
101
+ padding: 10px;
102
+ border-radius: 5px;
103
+ border: 1px solid #ccc;
104
+ }
105
+ .button {
106
+ background-color: #4CAF50;
107
+ color: white;
108
+ padding: 10px 20px;
109
+ border: none;
110
+ border-radius: 5px;
111
+ cursor: pointer;
112
+ }
113
+ .button:hover {
114
+ background-color: #45a049;
115
+ }
116
+ .timezone {
117
+ margin-top: 10px;
118
+ }
119
+ """) as demo:
120
+ gr.Markdown("<h1 style='text-align: center;'>πŸ€– Human-like Chatbot πŸ€–</h1>")
 
 
 
121
  with gr.Row():
122
+ with gr.Column(scale=3):
123
+ chatbot = gr.Chatbot(label="Chatbot", elem_id="chatbot")
124
+ timezone_input = gr.Dropdown(
125
+ choices=pytz.all_timezones,
126
+ value='UTC',
127
+ label="Select Your Timezone",
128
+ interactive=True,
129
+ elem_id="timezone-dropdown"
130
+ )
131
+ with gr.Column(scale=1, min_width=300):
132
+ msg = gr.Textbox(
133
+ placeholder="Enter your message here...",
134
+ show_label=False,
135
+ container=False,
136
+ elem_id="textbox"
137
+ )
138
+ send = gr.Button("Send", elem_id="send-button")
139
+ clear = gr.Button("Clear Chat", elem_id="clear-button")
140
+
141
+ def update_chat(user_message, history, timezone):
142
+ history, updated_history = chatbot_interface(user_message, history, timezone)
143
+ formatted_history = [
144
+ (format_message(u, is_user=True), format_message(a, is_user=False))
145
+ for u, a in updated_history
146
+ ]
147
+ return formatted_history, updated_history
148
+
149
+ send.click(
150
+ update_chat,
151
+ inputs=[msg, chatbot, timezone_input],
152
+ outputs=[chatbot, chatbot]
153
+ )
154
+
155
+ msg.submit(
156
+ update_chat,
157
+ inputs=[msg, chatbot, timezone_input],
158
+ outputs=[chatbot, chatbot]
159
+ )
160
+
161
+ clear.click(
162
+ lambda: ([], []),
163
+ inputs=None,
164
+ outputs=[chatbot, chatbot]
165
  )
 
166
 
167
  demo.launch()