julien-c
HF staff
commited on
Commit
c5df34f
1 Parent(s): 0b9c402

initial import

Browse files
Files changed (2) hide show
  1. .gitignore +3 -0
  2. app.py +71 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ .env/
2
+ data/
3
+ .vscode/
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import csv
3
+ import gradio as gr
4
+ from gradio import inputs, outputs
5
+ import huggingface_hub
6
+ from huggingface_hub import Repository
7
+ from datetime import datetime
8
+
9
+ DATASET_REPO_URL = "https://huggingface.co/datasets/julien-c/persistent-space-dataset"
10
+ DATA_FILENAME = "data.csv"
11
+ DATA_FILE = os.path.join("data", DATA_FILENAME)
12
+
13
+ HF_TOKEN = os.environ.get("HF_TOKEN")
14
+
15
+
16
+ print("hfh", huggingface_hub.__version__)
17
+
18
+ repo = Repository(
19
+ local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
20
+ )
21
+
22
+
23
+ def generate_html() -> str:
24
+ with open(DATA_FILE) as csvfile:
25
+ reader = csv.DictReader(csvfile)
26
+ rows = []
27
+ for row in reader:
28
+ rows.append(row)
29
+ rows.reverse()
30
+ if len(rows) == 0:
31
+ return "no messages yet"
32
+ else:
33
+ html = "<div class='chatbot'>"
34
+ for row in rows:
35
+ html += "<div>"
36
+ html += f"<span>{row['name']}</span>"
37
+ html += f"<span class='message'>{row['message']}</span>"
38
+ html += "</div>"
39
+ html += "</div>"
40
+ return html
41
+
42
+
43
+ def store_message(name: str, message: str):
44
+ if name and message:
45
+ with open(DATA_FILE, "a") as csvfile:
46
+ writer = csv.DictWriter(csvfile, fieldnames=["name", "message", "time"])
47
+ writer.writerow(
48
+ {"name": name, "message": message, "time": str(datetime.now())}
49
+ )
50
+ commit_url = repo.push_to_hub()
51
+ print(commit_url)
52
+
53
+ return generate_html()
54
+
55
+
56
+ iface = gr.Interface(
57
+ store_message,
58
+ [
59
+ inputs.Textbox(placeholder="Your name"),
60
+ inputs.Textbox(placeholder="Your message", lines=2),
61
+ ],
62
+ "html",
63
+ css="""
64
+ .message {background-color:cornflowerblue;color:white; padding:4px;margin:4px;border-radius:4px; }
65
+ """,
66
+ title="Reading/writing to a HuggingFace dataset repo from Spaces",
67
+ description=f"This is a demo of how to do simple *shared data persistence* in a Gradio Space, backed by a dataset repo.",
68
+ article=f"The dataset repo is [{DATASET_REPO_URL}]({DATASET_REPO_URL})",
69
+ )
70
+
71
+ iface.launch()