arjunguha commited on
Commit
36d1885
·
verified ·
1 Parent(s): ea5557c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import string
4
+ from collections import defaultdict
5
+
6
+ # Store all conversations and users
7
+ conversations = defaultdict(list)
8
+ usernames = {}
9
+
10
+ # Generate a random conversation ID
11
+ def generate_conversation_id():
12
+ return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
13
+
14
+ # Handle new chat creation
15
+ def new_chat():
16
+ conversation_id = generate_conversation_id()
17
+ return f"New conversation created. Share this URL to join: /?chat={conversation_id}"
18
+
19
+ # Handle user joining the conversation
20
+ def join_chat(chat_id, username):
21
+ if chat_id not in usernames:
22
+ usernames[chat_id] = []
23
+ if username not in usernames[chat_id]:
24
+ usernames[chat_id].append(username)
25
+ return f"Welcome {username}! You have joined the chat."
26
+
27
+ # Handle sending and receiving messages
28
+ def chat_interface(chat_id, username, message):
29
+ if chat_id not in conversations:
30
+ return "Invalid chat ID. Please start a new chat."
31
+ if username not in usernames.get(chat_id, []):
32
+ return "You need to join the chat first by providing your username."
33
+
34
+ # Store the message
35
+ conversations[chat_id].append((username, message))
36
+
37
+ # Display all messages
38
+ all_messages = "\n".join([f"{user}: {msg}" for user, msg in conversations[chat_id]])
39
+ return all_messages
40
+
41
+ # Gradio app
42
+ def main():
43
+ with gr.Blocks() as demo:
44
+ gr.Markdown("# Chat Application\nClick 'New Chat' to start a new conversation or join an existing one.")
45
+ new_chat_button = gr.Button("New Chat")
46
+ new_chat_output = gr.Textbox(label="New Chat URL")
47
+
48
+ new_chat_button.click(fn=new_chat, outputs=new_chat_output)
49
+
50
+ with gr.Row():
51
+ chat_id = gr.Textbox(label="Chat ID", placeholder="Enter Chat ID to join or create a new one.")
52
+ username = gr.Textbox(label="Username", placeholder="Enter your username.")
53
+ join_button = gr.Button("Join Chat")
54
+ join_output = gr.Textbox(label="Join Status")
55
+
56
+ join_button.click(fn=join_chat, inputs=[chat_id, username], outputs=join_output)
57
+
58
+ message = gr.Textbox(label="Your Message", placeholder="Type your message here.")
59
+ send_button = gr.Button("Send Message")
60
+ chat_output = gr.Textbox(label="Chat Messages")
61
+
62
+ send_button.click(fn=chat_interface, inputs=[chat_id, username, message], outputs=chat_output)
63
+
64
+ demo.launch()
65
+
66
+ if __name__ == "__main__":
67
+ main()