File size: 2,945 Bytes
906df3a
 
 
0a2a5dd
2b4d0c5
 
 
906df3a
ce8a39e
906df3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154c4b6
906df3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import os
import csv
import gradio as gr
from gradio import inputs

os.system("pip install -U huggingface_hub")

import huggingface_hub
print("hfh", huggingface_hub.__version__)
from huggingface_hub import hf_hub_download, upload_file
from datetime import datetime

DATASET_REPO_ID = "datasets/elonmuskceo/persistent-space-dataset"
DATASET_REPO_URL = f"https://huggingface.co/{DATASET_REPO_ID}"
DATA_DIRNAME = "data"
DATA_FILENAME = "data.csv"
DATA_FILE = os.path.join(DATA_DIRNAME, DATA_FILENAME)

HF_TOKEN = os.environ.get("HF_TOKEN")


print("hfh", huggingface_hub.__version__)

# overriding/appending to the gradio template
SCRIPT = """
<script>
if (!window.hasBeenRun) {
    window.hasBeenRun = true;
    console.log("should only happen once");
    document.querySelector("button.submit").click();
}
</script>
"""
with open(os.path.join(gr.networking.STATIC_TEMPLATE_LIB, "frontend", "index.html"), "a") as f:
    f.write(SCRIPT)


try:
    hf_hub_download(
        repo_id=DATASET_REPO_ID,
        filename=DATA_FILENAME,
        cache_dir=DATA_DIRNAME,
        force_filename=DATA_FILENAME
    )
except:
    # file not found, we'll create it on the fly.
    print("file not found, probably")


def generate_html() -> str:
    with open(DATA_FILE) as csvfile:
        reader = csv.DictReader(csvfile)
        rows = []
        for row in reader:
            rows.append(row)
        rows.reverse()
        if len(rows) == 0:
            return "no messages yet"
        else:
            html = "<div class='chatbot'>"
            for row in rows:
                html += "<div>"
                html += f"<span>{row['name']}</span>"
                html += f"<span class='message'>{row['message']}</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:
            writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
            writer.writerow(
                {"name": name, "message": message, "time": str(datetime.now())}
            )
        commit_url = upload_file(
            DATA_FILE,
            path_in_repo=DATA_FILENAME,
            repo_id=DATASET_REPO_ID,
            token=HF_TOKEN,
        )

        print(commit_url)

    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 a HuggingFace dataset repo from Spaces",
    description=f"This is a demo of how to do simple *shared data persistence* in a Gradio Space, backed by a dataset repo.",
    article=f"The dataset repo is [{DATASET_REPO_URL}]({DATASET_REPO_URL})",
)

iface.launch()