pcuenq HF staff commited on
Commit
e804c23
1 Parent(s): 32eaf3b

Shared chatroom demo.

Browse files
Files changed (1) hide show
  1. app.py +99 -35
app.py CHANGED
@@ -1,54 +1,118 @@
1
  import os
2
  import csv
3
  import gradio as gr
4
- from gradio import inputs, outputs
5
- from datetime import datetime
 
6
 
7
  DATA_FILENAME = "data.csv"
8
  DATA_FILE = os.path.join("/data", DATA_FILENAME)
9
 
10
- def generate_html() -> str:
 
 
11
  with open(DATA_FILE) as csvfile:
12
  reader = csv.reader(csvfile)
13
- rows = []
14
- for row in reader:
15
- print(row)
16
- rows.append(row)
17
- print(rows)
18
  if len(rows) == 0:
19
  return "no messages yet"
20
  else:
21
  html = "<div class='chatbot'>"
22
- print(row)
23
- for row in rows:
24
- html += "<div>"
25
- html += f"<span>{row[0]}</span>"
26
- html += f"<span class='message'>{row[1]}</span>"
 
 
 
 
 
 
 
 
27
  html += "</div>"
28
  html += "</div>"
29
  return html
30
 
31
 
32
- def store_message(name: str, message: str):
33
- if name and message:
34
  with open(DATA_FILE, "a") as csvfile:
35
- csv.writer(csvfile).writerow([name, message])
36
-
37
- return generate_html()
38
-
39
-
40
- iface = gr.Interface(
41
- store_message,
42
- [
43
- inputs.Textbox(placeholder="Your name"),
44
- inputs.Textbox(placeholder="Your message", lines=2),
45
- ],
46
- "html",
47
- css="""
48
- .message {background-color:cornflowerblue;color:white; padding:4px;margin:4px;border-radius:4px; }
49
- """,
50
- title="Reading/writing to persistent storage within the Space",
51
- description=f"This is a demo of how to do simple *shared data persistence* in a Gradio Space, backed in the storage of a Space (/data directory).",
52
- )
53
-
54
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import csv
3
  import gradio as gr
4
+ import itertools
5
+ import random
6
+ from collections import deque
7
 
8
  DATA_FILENAME = "data.csv"
9
  DATA_FILE = os.path.join("/data", DATA_FILENAME)
10
 
11
+ MAX_LINES = 20
12
+
13
+ def generate_html(me: str) -> str:
14
  with open(DATA_FILE) as csvfile:
15
  reader = csv.reader(csvfile)
16
+ rows = deque(reader, maxlen=MAX_LINES)
 
 
 
 
17
  if len(rows) == 0:
18
  return "no messages yet"
19
  else:
20
  html = "<div class='chatbot'>"
21
+ for row, _ in itertools.zip_longest(rows, range(MAX_LINES), fillvalue=("", "")):
22
+ username = row[0]
23
+ if username == me:
24
+ msg_type = "own"
25
+ elif username == "[chatbot]":
26
+ msg_type = "admin"
27
+ elif username == "":
28
+ msg_type = "empty"
29
+ else:
30
+ msg_type = "other"
31
+ html += "<div class='message'>"
32
+ html += f"<span class='nick'>{row[0]}</span>"
33
+ html += f"<span class='{msg_type}'>{row[1]}</span>"
34
  html += "</div>"
35
  html += "</div>"
36
  return html
37
 
38
 
39
+ def store_message(writer: str, message: str, me: str):
40
+ if writer and message:
41
  with open(DATA_FILE, "a") as csvfile:
42
+ csv.writer(csvfile).writerow([writer, message])
43
+
44
+ return generate_html(me)
45
+
46
+ anons = "alligator, anteater, armadillo, auroch, axolotl, badger, bat, bear, beaver, blobfish, buffalo, camel, chameleon, cheetah, chipmunk, chinchilla, chupacabra, cormorant, coyote, crow, dingo, dinosaur, dog, dolphin, dragon, duck, dumbo octopus, elephant, ferret, fox, frog, giraffe, goose, gopher, grizzly, hamster, hedgehog, hippo, hyena, jackal, jackalope, ibex, ifrit, iguana, kangaroo, kiwi, koala, kraken, lemur, leopard, liger, lion, llama, manatee, mink, monkey, moose, narwhal, nyan cat, orangutan, otter, panda, penguin, platypus, python, pumpkin, quagga, quokka, rabbit, raccoon, rhino, sheep, shrew, skunk, slow loris, squirrel, tiger, turtle, unicorn, walrus, wolf, wolverine, wombat"
47
+ anons = anons.split(",")
48
+
49
+ def login(username, state):
50
+ if username == "":
51
+ username = f"Anonymous {random.choice(anons).strip()}"
52
+ print(username)
53
+ state["username"] = username
54
+ store_message("[chatbot]", f"{username} joins the chat", username)
55
+ return (
56
+ state,
57
+ gr.update(visible=False),
58
+ gr.update(visible=True),
59
+ generate_html(username),
60
+ )
61
+
62
+ def send_message(message, state):
63
+ username = state["username"]
64
+ store_message(username, message, me=username)
65
+ return (generate_html(username), "")
66
+
67
+ css = """
68
+ .message {height: 28px;}
69
+ .nick {font-weight:bold;}
70
+ .other {background-color:cornflowerblue;color:white; padding:4px;margin:4px;border-radius:4px; }
71
+ .own {background-color:lime;color:white; padding:4px;margin:4px;border-radius:4px; }
72
+ .admin {background-color:orange;color:black; padding:4px;margin:4px;border-radius:4px; }
73
+ """
74
+ with gr.Blocks(css=css) as demo:
75
+ state = gr.Variable({
76
+ 'username': None,
77
+ })
78
+
79
+ gr.Markdown(
80
+ """
81
+ <h1><center>Persistent Storage Chat</center></h1>
82
+ <p>This is a simple demo that implements a chatroom using persistent storage.
83
+ All the messages are saved in a file, but only the last 20 ones are displayed.</p>
84
+ """
85
+ )
86
+
87
+ with gr.Group():
88
+ with (login_box := gr.Row().style(equal_height=True)):
89
+ username = gr.Textbox(
90
+ label="What's your name? (leave empty for anonymous)", show_label=True, max_lines=1
91
+ )
92
+ login_btn = gr.Button("Enter the chat")
93
+
94
+ with (chat_box := gr.Box(visible=False)):
95
+ with gr.Row():
96
+ output = gr.HTML(label="Chat", lines=20)
97
+ with gr.Row():
98
+ message = gr.Textbox(
99
+ label="Your message", show_label=False, max_lines=1
100
+ )
101
+
102
+ username.submit(
103
+ login,
104
+ inputs=[username, state],
105
+ outputs=[state, login_box, chat_box, output],
106
+ )
107
+ login_btn.click(
108
+ fn=login,
109
+ inputs=[username, state],
110
+ outputs=[state, login_box, chat_box, output],
111
+ )
112
+
113
+ message.submit(
114
+ send_message,
115
+ inputs=[message, state],
116
+ outputs=[output, message],
117
+ )
118
+ demo.launch()