xievic9780 commited on
Commit
ef519b9
Β·
0 Parent(s):

Initial commit: Add chatbot project

Browse files
Files changed (3) hide show
  1. .gitignore +3 -0
  2. ChatBot +102 -0
  3. chatbot.py +168 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
ChatBot ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ from typing import List, Tuple
4
+
5
+ # Configure your API key here
6
+ # openai.api_key = "your-api-key-here"
7
+
8
+ def chat_response(message: str, history: List[Tuple[str, str]]) -> str:
9
+ """
10
+ Generate a response to the user's message.
11
+
12
+ Args:
13
+ message: The user's current message
14
+ history: List of (user_message, assistant_message) tuples
15
+
16
+ Returns:
17
+ The assistant's response
18
+ """
19
+ # Build conversation history for the API
20
+ messages = [{"role": "system", "content": "You are a helpful assistant."}]
21
+
22
+ # Add chat history
23
+ for user_msg, assistant_msg in history:
24
+ messages.append({"role": "user", "content": user_msg})
25
+ messages.append({"role": "assistant", "content": assistant_msg})
26
+
27
+ # Add current message
28
+ messages.append({"role": "user", "content": message})
29
+
30
+ try:
31
+ # Call OpenAI API (uncomment when you have an API key)
32
+ # response = openai.ChatCompletion.create(
33
+ # model="gpt-3.5-turbo",
34
+ # messages=messages,
35
+ # temperature=0.7,
36
+ # max_tokens=500
37
+ # )
38
+ # return response.choices[0].message.content
39
+
40
+ # Mock response for demonstration (remove when using real API)
41
+ return f"This is a demo response to: '{message}'. Replace this with actual OpenAI API call."
42
+
43
+ except Exception as e:
44
+ return f"Error: {str(e)}"
45
+
46
+ # Create the Gradio interface
47
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
48
+ gr.Markdown("# πŸ’¬ ChatGPT-Style Interface")
49
+ gr.Markdown("A simple chat interface similar to ChatGPT")
50
+
51
+ chatbot = gr.Chatbot(
52
+ height=500,
53
+ bubble_full_width=False,
54
+ avatar_images=(None, "πŸ€–")
55
+ )
56
+
57
+ with gr.Row():
58
+ msg = gr.Textbox(
59
+ placeholder="Type your message here...",
60
+ container=False,
61
+ scale=7,
62
+ show_label=False
63
+ )
64
+ submit = gr.Button("Send", scale=1, variant="primary")
65
+
66
+ with gr.Row():
67
+ clear = gr.Button("Clear Chat")
68
+ retry = gr.Button("Retry Last")
69
+
70
+ # Handle message submission
71
+ def user_message(user_msg, history):
72
+ return "", history + [[user_msg, None]]
73
+
74
+ def bot_message(history):
75
+ user_msg = history[-1][0]
76
+ bot_msg = chat_response(user_msg, history[:-1])
77
+ history[-1][1] = bot_msg
78
+ return history
79
+
80
+ # Event handlers
81
+ msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
82
+ bot_message, chatbot, chatbot
83
+ )
84
+ submit.click(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
85
+ bot_message, chatbot, chatbot
86
+ )
87
+
88
+ clear.click(lambda: None, None, chatbot, queue=False)
89
+
90
+ def retry_last_message(history):
91
+ if history:
92
+ history[-1][1] = None
93
+ return bot_message(history)
94
+ return history
95
+
96
+ retry.click(retry_last_message, chatbot, chatbot)
97
+
98
+ # Launch the app
99
+ if __name__ == "__main__":x
100
+ demo.launch(share=False)
101
+
102
+
chatbot.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ from datetime import datetime
4
+
5
+ def simple_chatbot(message: str, history) -> str:
6
+ """
7
+ A simple rule-based chatbot that responds to common queries.
8
+ """
9
+ message_lower = message.lower().strip()
10
+
11
+ # Greetings
12
+ if any(word in message_lower for word in ['hello', 'hi', 'hey', 'greetings']):
13
+ responses = [
14
+ "Hello! How can I help you today?",
15
+ "Hi there! What can I do for you?",
16
+ "Hey! Great to see you. What's on your mind?",
17
+ "Greetings! How may I assist you?"
18
+ ]
19
+ return random.choice(responses)
20
+
21
+ # How are you
22
+ elif any(phrase in message_lower for phrase in ['how are you', 'how are u', 'hows it going', "how's it going"]):
23
+ responses = [
24
+ "I'm doing great, thank you for asking! How about you?",
25
+ "I'm functioning perfectly! How can I help you today?",
26
+ "I'm excellent! What brings you here?",
27
+ "I'm doing well! What about yourself?"
28
+ ]
29
+ return random.choice(responses)
30
+
31
+ # Name questions
32
+ elif any(phrase in message_lower for phrase in ['what is your name', 'your name', 'who are you']):
33
+ return "I'm a friendly chatbot created to assist you! You can call me ChatBot. What's your name?"
34
+
35
+ # Time
36
+ elif 'time' in message_lower and any(word in message_lower for word in ['what', 'current', 'now']):
37
+ current_time = datetime.now().strftime("%I:%M %p")
38
+ return f"The current time is {current_time}."
39
+
40
+ # Date
41
+ elif 'date' in message_lower and any(word in message_lower for word in ['what', 'current', 'today']):
42
+ current_date = datetime.now().strftime("%B %d, %Y")
43
+ return f"Today's date is {current_date}."
44
+
45
+ # Help
46
+ elif any(word in message_lower for word in ['help', 'assist', 'support']):
47
+ return """I can help you with:
48
+ - General conversation
49
+ - Answering simple questions
50
+ - Telling you the time and date
51
+ - Basic math problems (e.g., "what is 5 + 3")
52
+ - And more! Just ask me anything."""
53
+
54
+ # Math operations
55
+ elif any(op in message_lower for op in ['what is', 'calculate', 'compute']):
56
+ try:
57
+ # Extract numbers and operators
58
+ import re
59
+ # Find mathematical expression
60
+ math_pattern = r'(\d+\.?\d*)\s*([\+\-\*\/])\s*(\d+\.?\d*)'
61
+ match = re.search(math_pattern, message)
62
+ if match:
63
+ num1, operator, num2 = match.groups()
64
+ num1, num2 = float(num1), float(num2)
65
+
66
+ if operator == '+':
67
+ result = num1 + num2
68
+ elif operator == '-':
69
+ result = num1 - num2
70
+ elif operator == '*':
71
+ result = num1 * num2
72
+ elif operator == '/':
73
+ if num2 != 0:
74
+ result = num1 / num2
75
+ else:
76
+ return "I can't divide by zero!"
77
+
78
+ return f"The answer is {result}"
79
+ except:
80
+ pass
81
+
82
+ # Jokes
83
+ elif 'joke' in message_lower or 'funny' in message_lower:
84
+ jokes = [
85
+ "Why don't scientists trust atoms? Because they make up everything! πŸ˜„",
86
+ "Why did the Python programmer not respond to the chat? Because he was stuck in an infinite loop! 🐍",
87
+ "What do you call a bear with no teeth? A gummy bear! 🐻",
88
+ "Why did the scarecrow win an award? He was outstanding in his field! 🌾",
89
+ "What's a computer's favorite snack? Microchips! πŸ’»"
90
+ ]
91
+ return random.choice(jokes)
92
+
93
+ # Goodbye
94
+ elif any(word in message_lower for word in ['bye', 'goodbye', 'see you', 'later', 'exit', 'quit']):
95
+ responses = [
96
+ "Goodbye! Have a wonderful day! πŸ‘‹",
97
+ "See you later! Take care! 😊",
98
+ "Bye! Come back anytime!",
99
+ "Farewell! It was nice chatting with you!"
100
+ ]
101
+ return random.choice(responses)
102
+
103
+ # Thank you
104
+ elif any(word in message_lower for word in ['thank', 'thanks', 'thx']):
105
+ responses = [
106
+ "You're welcome! Happy to help! 😊",
107
+ "No problem at all!",
108
+ "My pleasure! Anything else I can help with?",
109
+ "You're very welcome!"
110
+ ]
111
+ return random.choice(responses)
112
+
113
+ # Default response for unknown inputs
114
+ else:
115
+ responses = [
116
+ "That's interesting! Tell me more.",
117
+ "I'm not sure I understand. Can you rephrase that?",
118
+ "Hmm, I'm still learning. Can you ask me something else?",
119
+ "I don't have a good answer for that yet. Try asking me about the time, date, or tell me a joke!",
120
+ "That's a good question! Unfortunately, I don't have enough information to answer it properly."
121
+ ]
122
+ return random.choice(responses)
123
+
124
+ # Create the Gradio interface
125
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
126
+ gr.Markdown("# πŸ’¬ Simple ChatBot")
127
+ gr.Markdown("A friendly chatbot that can chat, do math, tell jokes, and more!")
128
+
129
+ chatbot = gr.Chatbot(
130
+ height=500,
131
+ type='messages'
132
+ )
133
+
134
+ with gr.Row():
135
+ msg = gr.Textbox(
136
+ placeholder="Type your message here...",
137
+ container=False,
138
+ scale=7,
139
+ show_label=False
140
+ )
141
+ submit = gr.Button("Send", scale=1, variant="primary")
142
+
143
+ with gr.Row():
144
+ clear = gr.Button("Clear Chat")
145
+ examples = gr.Button("Show Examples")
146
+
147
+ # Handle message submission
148
+ def respond(message, chat_history):
149
+ bot_message = simple_chatbot(message, chat_history)
150
+ chat_history.append({"role": "user", "content": message})
151
+ chat_history.append({"role": "assistant", "content": bot_message})
152
+ return "", chat_history
153
+
154
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
155
+ submit.click(respond, [msg, chatbot], [msg, chatbot])
156
+
157
+ clear.click(lambda: [], None, chatbot, queue=False)
158
+
159
+ def show_examples():
160
+ return [
161
+ {"role": "assistant", "content": "Try these examples:\n- Hello!\n- What's your name?\n- What time is it?\n- Tell me a joke\n- What is 25 + 17?\n- How are you?"}
162
+ ]
163
+
164
+ examples.click(show_examples, None, chatbot)
165
+
166
+ # Launch the app
167
+ if __name__ == "__main__":
168
+ demo.launch(share=False)