File size: 1,551 Bytes
44f9cbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import os
import csv
import gradio as gr
from gradio import inputs, outputs
from datetime import datetime

DATA_FILENAME = "data.csv"
DATA_FILE = os.path.join("/data", DATA_FILENAME)

def generate_html() -> str:
    with open(DATA_FILE) as csvfile:
        reader = csv.reader(csvfile)
        rows = []
        for row in reader:
            print(row)
            rows.append(row)
        print(rows)
        if len(rows) == 0:
            return "no messages yet"
        else:
            html = "<div class='chatbot'>"
            print(row)
            for row in rows:
                html += "<div>"
                html += f"<span>{row[0]}</span>"
                html += f"<span class='message'>{row[1]}</span>"
                html += "</div>"
            html += "</div>"
            return html


def store_message(name: str, message: str):
    if name and message:
        with open(DATA_FILE, "a") as csvfile:
            csv.writer(csvfile).writerow([name, message])

    return generate_html()


iface = gr.Interface(
    store_message,
    [
        inputs.Textbox(placeholder="Your name"),
        inputs.Textbox(placeholder="Your message", lines=2),
    ],
    "html",
    css="""
    .message {background-color:cornflowerblue;color:white; padding:4px;margin:4px;border-radius:4px; }
    """,
    title="Reading/writing to persistent storage within the Space",
    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).",
)

iface.launch()