File size: 6,474 Bytes
6bbbe77
 
 
5f7ff4f
cb21807
472305f
 
20b3e31
 
 
472305f
cb21807
20b3e31
cb21807
6bbbe77
63c00d6
 
20b3e31
63c00d6
20b3e31
63c00d6
20b3e31
63c00d6
20b3e31
63c00d6
6e435cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20b3e31
6e435cb
 
20b3e31
6e435cb
 
5f7ff4f
cb21807
5f7ff4f
 
c852af8
cb21807
 
 
c852af8
cb21807
 
 
5f7ff4f
 
cb21807
5f7ff4f
 
cb21807
 
 
c852af8
5f7ff4f
6e435cb
6bbbe77
20b3e31
5f7ff4f
6e435cb
6bbbe77
 
20b3e31
6bbbe77
 
 
 
 
 
 
 
 
 
 
 
 
6e435cb
6bbbe77
 
 
 
 
 
 
 
 
 
 
 
6e435cb
6bbbe77
 
 
 
 
 
 
 
 
 
 
6e435cb
6bbbe77
 
 
 
 
 
 
 
 
 
6e435cb
5f7ff4f
20b3e31
6e435cb
6bbbe77
 
 
 
6e435cb
6bbbe77
20b3e31
 
 
 
 
 
 
6bbbe77
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import streamlit as st
import pandas as pd
from datetime import datetime
import os
from huggingface_hub import HfApi, upload_file, list_repo_files, hf_hub_download

# Configuration for Hugging Face Repository
REPO_ID = "MarcosRodrigo/Breakfast-Poll"
HISTORY_DIR = "history"
TEMP_FILE = "current_selections.csv"

# Hugging Face API (requires a token with write access)
hf_token = st.secrets["HF_TOKEN"]
api = HfApi()

# Initialize all required session state variables
if "users" not in st.session_state:
    st.session_state.users = []
if "current_selections" not in st.session_state:
    st.session_state.current_selections = []
if "step" not in st.session_state:
    st.session_state.step = 1
if "history" not in st.session_state:
    st.session_state.history = []

# Load temporary selections from the shared file
def load_current_selections():
    if os.path.exists(TEMP_FILE):
        return pd.read_csv(TEMP_FILE)
    else:
        return pd.DataFrame(columns=["Name", "Drinks", "Food"])

# Save current user selections to the shared CSV file
def save_current_selection_to_file(current_selections):
    current_selections.to_csv(TEMP_FILE, index=False)

# Upload the shared file to Hugging Face repository for persistence
def upload_temp_file_to_repo():
    if os.path.exists(TEMP_FILE):
        upload_file(
            path_or_fileobj=TEMP_FILE,
            path_in_repo=TEMP_FILE,
            repo_id=REPO_ID,
            token=hf_token,
            repo_type="space"
        )

# Download the shared file from the repository to ensure persistence and real-time updates
def download_temp_file_from_repo():
    try:
        hf_hub_download(repo_id=REPO_ID, filename=TEMP_FILE, repo_type="space", token=hf_token, local_dir=".")
    except Exception:
        pd.DataFrame(columns=["Name", "Drinks", "Food"]).to_csv(TEMP_FILE, index=False)

# Load history from the repository
def load_history():
    history = []
    files_in_repo = list_repo_files(REPO_ID, token=hf_token, repo_type="space")
    history_files = [f for f in files_in_repo if f.startswith(f"{HISTORY_DIR}/") and f.endswith(".txt")]

    for file in history_files:
        local_filepath = hf_hub_download(repo_id=REPO_ID, filename=file, token=hf_token, repo_type="space")
        summary_df = pd.read_csv(local_filepath)
        date = file.split("/")[-1].split(".txt")[0]
        history.append({"Date": date, "Summary": summary_df})
    return history

# Save the current summary to a text file and upload to the repository
def save_summary_to_file(summary_df):
    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    filename = f"{HISTORY_DIR}/{timestamp}.txt"
    local_filepath = f"{timestamp}.txt"
    summary_df.to_csv(local_filepath, index=False)
    upload_file(path_or_fileobj=local_filepath, path_in_repo=filename, repo_id=REPO_ID, token=hf_token, repo_type="space")

# Load persistent history and temporary selections on app start
if "history" not in st.session_state:
    download_temp_file_from_repo()
    st.session_state.history = load_history()
    st.session_state.current_selections = load_current_selections().to_dict(orient="records")

# Sidebar for navigating through different views
menu = st.sidebar.selectbox("Select View", ["Poll", "Current", "History"])

# Function to reset the current selections after submission
def reset_selections():
    st.session_state.users = []
    st.session_state.current_selections = []

# Poll view with four consecutive steps
if menu == "Poll":
    st.title("Breakfast Poll Application")

    if st.session_state.step == 1:
        st.header("Step 1: Enter your name")
        name = st.text_input("Name:")
        if st.button("Next", key="step1_next") and name:
            st.session_state.users.append(name)
            st.session_state.step = 2

    # Step 2: Select Drinks
    if st.session_state.step == 2:
        st.header("Step 2: Select your drink(s)")
        drinks_options = [
            "Café con leche", "Colacao", "Descafeinado con leche", "Cortado", 
            "Aguasusia", "Aguasusia susia", "Café descafeinado con leche desnatada", 
            "Italiano", "Café con soja", "Té", "Manzanilla", "Nada"
        ]
        selected_drinks = st.multiselect("Choose your drinks:", drinks_options)
        if st.button("Next", key="step2_next") and selected_drinks:
            st.session_state.current_selections.append({"Name": st.session_state.users[-1], "Drinks": selected_drinks})
            st.session_state.step = 3

    # Step 3: Select Food
    if st.session_state.step == 3:
        st.header("Step 3: Select your food(s)")
        food_options = [
            "Barrita con aceite", "Barrita con tomate", "Palmera de chocolate", 
            "Palmera de chocolate blanco", "Yogurt", "Pincho de tortilla", "Nada"
        ]
        selected_food = st.multiselect("Choose your food:", food_options)
        if st.button("Next", key="step3_next") and selected_food:
            st.session_state.current_selections[-1]["Food"] = selected_food
            st.session_state.step = 4

    # Step 4: Display Summary
    if st.session_state.step == 4:
        st.header("Step 4: Summary of Selections")
        if st.session_state.current_selections:
            df = pd.DataFrame(st.session_state.current_selections)
            st.table(df)

            if st.button("Submit Summary", key="submit_summary"):
                save_summary_to_file(df)
                save_current_selection_to_file(pd.DataFrame(st.session_state.current_selections))
                upload_temp_file_to_repo()
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                st.session_state.history.append({"Date": timestamp, "Summary": df})
                st.success(f"Summary submitted at {timestamp}")
                st.session_state.step = 1
                st.experimental_rerun()

# "Current" view to display the current summary of all users' selections
elif menu == "Current":
    st.title("Current Selections of All Users")
    download_temp_file_from_repo()  # Ensure the latest file is downloaded
    current_df = load_current_selections()
    st.table(current_df)

# History view to check past summaries
elif menu == "History":
    st.title("Breakfast Poll History")
    if st.session_state.history:
        for record in st.session_state.history:
            st.subheader(f"Date: {record['Date']}")
            st.table(record["Summary"])
    else:
        st.write("No history records found.")