peterpull commited on
Commit
29ff848
·
1 Parent(s): d19a684

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -15
app.py CHANGED
@@ -4,10 +4,72 @@ import gradio as gr
4
  import sys
5
  import os
6
  import datetime
 
 
 
 
7
 
8
  os.environ["OPENAI_API_KEY"] = os.environ['SECRET_CODE']
9
 
 
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def get_index(index_file_path):
12
  if os.path.exists(index_file_path):
13
  return GPTSimpleVectorIndex.load_from_disk(index_file_path)
@@ -15,25 +77,11 @@ def get_index(index_file_path):
15
  print(f"Error: '{index_file_path}' does not exist.")
16
  sys.exit()
17
 
18
-
19
  def chatbot(input_text, mentioned_person='Mediator John Haynes'):
20
  index = get_index('./index/indexsmall.json')
21
  prompt = f"You are {mentioned_person}: {input_text}\n\n At the end of your answer ask a provocative question."
22
  response = index.query(prompt, response_mode="compact")
23
-
24
-
25
-
26
- # code to save chat log to file
27
- current_time = datetime.datetime.now()
28
- current_time_str = current_time.strftime("%Y-%m-%d_%H-%M-%S")
29
- chat_log_filename = "chat_history.txt"
30
- chat_log_dir = os.path.dirname(os.path.abspath(__file__))
31
- chat_log_filepath = os.path.join(chat_log_dir, chat_log_filename)
32
- with open(chat_log_filepath, "a") as f:
33
- f.write(f"Chat at {current_time_str}\n")
34
- f.write(f"User: {input_text}\n")
35
- f.write(f"Chatbot: {response.response}\n\n")
36
- print(f"Chat log written to {chat_log_filepath}")
37
 
38
  # return the response
39
  return response.response
 
4
  import sys
5
  import os
6
  import datetime
7
+ import huggingface_hub
8
+ from huggingface_hub import Repository
9
+ from datetime import datetime
10
+ import csv
11
 
12
  os.environ["OPENAI_API_KEY"] = os.environ['SECRET_CODE']
13
 
14
+ # Need to write to persistent dataset because cannot store temp data on spaces
15
+ DATASET_REPO_URL = "https://huggingface.co/datasets/peterpull/MediatorBot"
16
+ DATA_FILENAME = "data.csv"
17
+ DATA_FILE = os.path.join("data", DATA_FILENAME)
18
+ HF_TOKEN = os.environ.get("HF_TOKEN")
19
+ print("HF TOKEN is none?", HF_TOKEN is None)
20
+ print("HF hub ver", huggingface_hub.__version__)
21
 
22
+ # overriding/appending to the gradio template
23
+ SCRIPT = """
24
+ <script>
25
+ if (!window.hasBeenRun) {
26
+ window.hasBeenRun = true;
27
+ console.log("should only happen once");
28
+ document.querySelector("button.submit").click();
29
+ }
30
+ </script>
31
+ """
32
+ with open(os.path.join(gr.networking.STATIC_TEMPLATE_LIB, "frontend", "index.html"), "a") as f:
33
+ f.write(SCRIPT)
34
+
35
+
36
+ repo = Repository(
37
+ local_dir="data", clone_from=DATASET_REPO_URL, use_auth_token=HF_TOKEN
38
+ )
39
+
40
+ def generate_html() -> str:
41
+ with open(DATA_FILE) as csvfile:
42
+ reader = csv.DictReader(csvfile)
43
+ rows = []
44
+ for row in reader:
45
+ rows.append(row)
46
+ rows.reverse()
47
+ if len(rows) == 0:
48
+ return "no messages yet"
49
+ else:
50
+ html = "<div class='chatbot'>"
51
+ for row in rows:
52
+ html += "<div>"
53
+ html += f"<span>{row['User input']}</span>"
54
+ html += f"<span class='message'>{row['Chatbot Response']}</span>"
55
+ html += "</div>"
56
+ html += "</div>"
57
+ return html
58
+
59
+ def store_message(name: str, message: str):
60
+ if name and message:
61
+ with open(DATA_FILE, "a") as csvfile:
62
+ writer = csv.DictWriter(csvfile, fieldnames=["User", "Chatbot", "time"])
63
+ writer.writerow(
64
+ {"User": {input_text}, "Chatbot": {response.response}, "time": str(datetime.now())}
65
+ )
66
+ commit_url = repo.push_to_hub()
67
+ print(commit_url)
68
+
69
+ return generate_html()
70
+
71
+
72
+ #gets the index file which is the context data
73
  def get_index(index_file_path):
74
  if os.path.exists(index_file_path):
75
  return GPTSimpleVectorIndex.load_from_disk(index_file_path)
 
77
  print(f"Error: '{index_file_path}' does not exist.")
78
  sys.exit()
79
 
80
+ # passes the prompt to the chatbot
81
  def chatbot(input_text, mentioned_person='Mediator John Haynes'):
82
  index = get_index('./index/indexsmall.json')
83
  prompt = f"You are {mentioned_person}: {input_text}\n\n At the end of your answer ask a provocative question."
84
  response = index.query(prompt, response_mode="compact")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  # return the response
87
  return response.response