sjw commited on
Commit
ccc5ec3
·
1 Parent(s): ba85564

Upload playground.py

Browse files
Files changed (1) hide show
  1. playground.py +84 -0
playground.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import gradio as gr
4
+ from gradio import components
5
+ from huggingface_hub import Repository, hf_hub_download
6
+ from datetime import datetime
7
+
8
+ DATASET_REPO_URL = "https://huggingface.co/datasets/sjw/data.csv"
9
+ DATASET_REPO_ID = "sjw/data.csv"
10
+ DATA_FILENAME = "data.csv"
11
+ DATA_DIRNAME = "data"
12
+ DATA_FILE = os.path.join(DATA_DIRNAME, DATA_FILENAME)
13
+ HF_TOKEN = os.environ.get("HF_TOKEN")
14
+
15
+ # overriding/appending to the gradio template
16
+ SCRIPT = """
17
+ <script>
18
+ if (!window.hasBeenRun) {
19
+ window.hasBeenRun = true;
20
+ console.log("should only happen once");
21
+ document.querySelector("button.submit").click();
22
+ }
23
+ </script>
24
+ """
25
+
26
+ try:
27
+ hf_hub_download(
28
+ repo_id=DATASET_REPO_ID,
29
+ filename=DATA_FILENAME,
30
+ cache_dir=DATA_DIRNAME
31
+ )
32
+ except:
33
+ print("file not found")
34
+
35
+ repo = Repository(
36
+ local_dir=DATA_DIRNAME, clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
37
+ )
38
+
39
+ def generate_html() -> str:
40
+ with open(DATA_FILE) as csvfile:
41
+ reader = csv.DictReader(csvfile)
42
+ rows = []
43
+ for row in reader:
44
+ rows.append(row)
45
+ rows.reverse()
46
+ if len(rows) == 0:
47
+ return "no messages yet"
48
+ else:
49
+ html = "<div class='chatbot'>"
50
+ for row in rows:
51
+ html += "<div>"
52
+ html += f"<span>{row['name']}</span>"
53
+ html += f"<span class='message'>{row['message']}</span>"
54
+ html += "</div>"
55
+ html += "</div>"
56
+ return html
57
+
58
+ def store_message(name: str, message: str):
59
+ if name and message:
60
+ with open(DATA_FILE, "a") as csvfile:
61
+ writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
62
+ writer.writerow(
63
+ {"name": name, "message": message, "time": str(datetime.now())}
64
+ )
65
+ commit_url = repo.push_to_hub()
66
+ return generate_html()
67
+
68
+ iface = gr.Interface(
69
+ store_message,
70
+ [
71
+ components.Textbox(placeholder="Your name"),
72
+ components.Textbox(placeholder="Your message", lines=2),
73
+ ],
74
+ "html",
75
+ css="""
76
+ .message {background-color:cornflowerblue;color:white; padding:4px;margin:4px;border-radius:4px; }
77
+ """,
78
+ title="Reading/writing to a HuggingFace dataset repo from Spaces",
79
+ description=f"This is a demo of how to do simple *shared data persistence* in a Gradio Space, backed by a dataset repo.",
80
+ article=f"The dataset repo is [{DATASET_REPO_URL}]({DATASET_REPO_URL})",
81
+ allow_flagging="never"
82
+ )
83
+
84
+ iface.launch()