MarcosRodrigo commited on
Commit
6e435cb
·
verified ·
1 Parent(s): aa23a4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -14
app.py CHANGED
@@ -7,26 +7,49 @@ from huggingface_hub import HfApi, upload_file, list_repo_files, hf_hub_download
7
  # Configuration for Hugging Face Repository
8
  REPO_ID = "MarcosRodrigo/Breakfast-Poll" # Use the correct format: namespace/repo_name
9
  HISTORY_DIR = "history" # Directory within the repository to store history
 
10
 
11
  # Hugging Face API (requires a token with write access)
12
  hf_token = st.secrets["HF_TOKEN"] # Use the token stored in the secrets manager
13
  api = HfApi()
14
 
15
- # Initialize session state for temporary and historical storage
16
- if "users" not in st.session_state:
17
- st.session_state.users = []
18
- if "current_selections" not in st.session_state:
19
- st.session_state.current_selections = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  # Load history from the repository
22
  def load_history():
23
  history = []
24
- # Specify `repo_type="space"` to indicate this is a Space repository
25
  files_in_repo = list_repo_files(REPO_ID, token=hf_token, repo_type="space")
26
  history_files = [f for f in files_in_repo if f.startswith(f"{HISTORY_DIR}/") and f.endswith(".txt")]
27
 
28
  for file in history_files:
29
- # Download the file from the Space repository with `repo_type="space"`
30
  local_filepath = hf_hub_download(repo_id=REPO_ID, filename=file, token=hf_token, repo_type="space")
31
  summary_df = pd.read_csv(local_filepath)
32
  date = file.split("/")[-1].split(".txt")[0]
@@ -45,9 +68,11 @@ def save_summary_to_file(summary_df):
45
  # Upload the file to the Space repository with `repo_type="space"`
46
  upload_file(path_or_fileobj=local_filepath, path_in_repo=filename, repo_id=REPO_ID, token=hf_token, repo_type="space")
47
 
48
- # Load history into session state
49
  if "history" not in st.session_state:
 
50
  st.session_state.history = load_history()
 
51
 
52
  # Sidebar for navigating through different views
53
  menu = st.sidebar.selectbox("Select View", ["Poll", "History"])
@@ -68,7 +93,7 @@ if menu == "Poll":
68
  if st.session_state.step == 1:
69
  st.header("Step 1: Enter your name")
70
  name = st.text_input("Name:")
71
- if st.button("Next", key="step1_next") and name: # Unique key for the button
72
  st.session_state.users.append(name)
73
  st.session_state.step = 2
74
 
@@ -81,7 +106,7 @@ if menu == "Poll":
81
  "Italiano", "Café con soja", "Té", "Manzanilla", "Nada"
82
  ]
83
  selected_drinks = st.multiselect("Choose your drinks:", drinks_options)
84
- if st.button("Next", key="step2_next") and selected_drinks: # Unique key for the button
85
  st.session_state.current_selections.append({"Name": st.session_state.users[-1], "Drinks": selected_drinks})
86
  st.session_state.step = 3
87
 
@@ -93,7 +118,7 @@ if menu == "Poll":
93
  "Palmera de chocolate blanco", "Yogurt", "Pincho de tortilla", "Nada"
94
  ]
95
  selected_food = st.multiselect("Choose your food:", food_options)
96
- if st.button("Next", key="step3_next") and selected_food: # Unique key for the button
97
  st.session_state.current_selections[-1]["Food"] = selected_food
98
  st.session_state.step = 4
99
 
@@ -104,17 +129,22 @@ if menu == "Poll":
104
  df = pd.DataFrame(st.session_state.current_selections)
105
  st.table(df)
106
 
107
- if st.button("Submit Summary", key="submit_summary"): # Unique key for the button
108
  # Save the current summary to a text file in the repository
109
  save_summary_to_file(df)
110
-
 
 
 
 
111
  # Add to session state history
112
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
113
  st.session_state.history.append({"Date": timestamp, "Summary": df})
114
-
115
  st.success(f"Summary submitted at {timestamp}")
116
  reset_selections()
117
  st.session_state.step = 1
 
118
 
119
  # History view to check past summaries
120
  elif menu == "History":
 
7
  # Configuration for Hugging Face Repository
8
  REPO_ID = "MarcosRodrigo/Breakfast-Poll" # Use the correct format: namespace/repo_name
9
  HISTORY_DIR = "history" # Directory within the repository to store history
10
+ TEMP_FILE = "current_selections.csv" # Temporary file to store current selections
11
 
12
  # Hugging Face API (requires a token with write access)
13
  hf_token = st.secrets["HF_TOKEN"] # Use the token stored in the secrets manager
14
  api = HfApi()
15
 
16
+ # Load temporary selections from the shared file
17
+ def load_current_selections():
18
+ if os.path.exists(TEMP_FILE):
19
+ return pd.read_csv(TEMP_FILE)
20
+ else:
21
+ return pd.DataFrame(columns=["Name", "Drinks", "Food"])
22
+
23
+ # Save current user selections to the shared CSV file
24
+ def save_current_selection_to_file(current_selections):
25
+ current_selections.to_csv(TEMP_FILE, index=False)
26
+
27
+ # Upload the shared file to Hugging Face repository for persistence
28
+ def upload_temp_file_to_repo():
29
+ if os.path.exists(TEMP_FILE):
30
+ upload_file(
31
+ path_or_fileobj=TEMP_FILE,
32
+ path_in_repo=TEMP_FILE,
33
+ repo_id=REPO_ID,
34
+ token=hf_token,
35
+ repo_type="space"
36
+ )
37
+
38
+ # Download the shared file from the repository to ensure persistence
39
+ def download_temp_file_from_repo():
40
+ try:
41
+ hf_hub_download(repo_id=REPO_ID, filename=TEMP_FILE, repo_type="space", token=hf_token)
42
+ except Exception:
43
+ # If the file does not exist in the repo, create an empty file
44
+ pd.DataFrame(columns=["Name", "Drinks", "Food"]).to_csv(TEMP_FILE, index=False)
45
 
46
  # Load history from the repository
47
  def load_history():
48
  history = []
 
49
  files_in_repo = list_repo_files(REPO_ID, token=hf_token, repo_type="space")
50
  history_files = [f for f in files_in_repo if f.startswith(f"{HISTORY_DIR}/") and f.endswith(".txt")]
51
 
52
  for file in history_files:
 
53
  local_filepath = hf_hub_download(repo_id=REPO_ID, filename=file, token=hf_token, repo_type="space")
54
  summary_df = pd.read_csv(local_filepath)
55
  date = file.split("/")[-1].split(".txt")[0]
 
68
  # Upload the file to the Space repository with `repo_type="space"`
69
  upload_file(path_or_fileobj=local_filepath, path_in_repo=filename, repo_id=REPO_ID, token=hf_token, repo_type="space")
70
 
71
+ # Load persistent history and temporary selections on app start
72
  if "history" not in st.session_state:
73
+ download_temp_file_from_repo() # Ensure the latest temp file is present
74
  st.session_state.history = load_history()
75
+ st.session_state.current_selections = load_current_selections().to_dict(orient="records")
76
 
77
  # Sidebar for navigating through different views
78
  menu = st.sidebar.selectbox("Select View", ["Poll", "History"])
 
93
  if st.session_state.step == 1:
94
  st.header("Step 1: Enter your name")
95
  name = st.text_input("Name:")
96
+ if st.button("Next", key="step1_next") and name:
97
  st.session_state.users.append(name)
98
  st.session_state.step = 2
99
 
 
106
  "Italiano", "Café con soja", "Té", "Manzanilla", "Nada"
107
  ]
108
  selected_drinks = st.multiselect("Choose your drinks:", drinks_options)
109
+ if st.button("Next", key="step2_next") and selected_drinks:
110
  st.session_state.current_selections.append({"Name": st.session_state.users[-1], "Drinks": selected_drinks})
111
  st.session_state.step = 3
112
 
 
118
  "Palmera de chocolate blanco", "Yogurt", "Pincho de tortilla", "Nada"
119
  ]
120
  selected_food = st.multiselect("Choose your food:", food_options)
121
+ if st.button("Next", key="step3_next") and selected_food:
122
  st.session_state.current_selections[-1]["Food"] = selected_food
123
  st.session_state.step = 4
124
 
 
129
  df = pd.DataFrame(st.session_state.current_selections)
130
  st.table(df)
131
 
132
+ if st.button("Submit Summary", key="submit_summary"):
133
  # Save the current summary to a text file in the repository
134
  save_summary_to_file(df)
135
+
136
+ # Save and upload current selections for real-time updates
137
+ save_current_selection_to_file(df)
138
+ upload_temp_file_to_repo()
139
+
140
  # Add to session state history
141
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
142
  st.session_state.history.append({"Date": timestamp, "Summary": df})
143
+
144
  st.success(f"Summary submitted at {timestamp}")
145
  reset_selections()
146
  st.session_state.step = 1
147
+ st.experimental_rerun()
148
 
149
  # History view to check past summaries
150
  elif menu == "History":