Spaces:
Paused

File size: 9,063 Bytes
0a2d520
 
 
 
d134619
0a2d520
aae556d
d0eecf1
0a2d520
d134619
 
 
0a2d520
d134619
4b4c384
d134619
 
0335271
d134619
8fe603e
 
 
 
 
 
 
 
 
 
d134619
 
 
 
 
 
 
 
 
 
f287a2f
d134619
 
 
 
 
0a2d520
25e0cf5
d134619
 
25e0cf5
d134619
0a2d520
25e0cf5
d134619
 
0a2d520
 
25e0cf5
 
0a2d520
 
13631a5
d134619
 
 
25e0cf5
d134619
25e0cf5
d134619
 
25e0cf5
d134619
 
0a2d520
 
d134619
25e0cf5
0a2d520
25e0cf5
 
0a2d520
 
d134619
 
 
 
0a2d520
 
 
d134619
0a2d520
 
 
 
d134619
0a2d520
 
 
 
 
 
d134619
 
8a25df8
25e0cf5
 
 
d134619
0a2d520
 
 
 
 
 
d134619
0a2d520
 
 
d134619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2d520
d134619
 
 
 
 
0a2d520
d134619
 
 
0a2d520
 
d134619
0a2d520
 
 
d134619
 
 
 
 
25e0cf5
 
 
 
 
 
 
d134619
0a2d520
 
 
d134619
 
 
0a2d520
 
 
 
 
d134619
0a2d520
d134619
0a2d520
 
 
 
 
 
 
d134619
0a2d520
 
 
d134619
0a2d520
 
d134619
0a2d520
 
 
 
25e0cf5
0a2d520
0335271
0a2d520
d134619
25e0cf5
0a2d520
 
 
 
13631a5
 
25e0cf5
13631a5
0a2d520
d134619
 
0a2d520
5a5e07d
0a2d520
d134619
0a2d520
 
 
 
 
d134619
0a2d520
 
 
 
d134619
0a2d520
 
d134619
13631a5
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import gradio as gr
import pandas as pd
from datetime import datetime
import matplotlib
matplotlib.use('Agg')  # Use non-interactive backend
import matplotlib.pyplot as plt
import os
import json

# Import gspread and google-auth for Google Sheets access
import gspread
from google.oauth2.service_account import Credentials

# Set your desired voting start date and time
VOTING_START = datetime(2025, 4, 14, 7, 0, 0)  

# Google Sheets constants
SPREADSHEET_NAME = "TeamNameVoting"  # Name of your Google Sheet


# Retrieve the JSON string from your Hugging Face secrets
gsheet_creds_json = os.environ.get("G_TOKEN")
if gsheet_creds_json is None:
    raise ValueError("Google Sheets credentials not found in environment variables.")

# Convert JSON string to dictionary
gsheet_creds_info = json.loads(gsheet_creds_json)


def get_worksheet(worksheet_index=0):
    """
    Connect to the Google Sheet and return the worksheet at the given index.
    Tab index 0 should be for submissions and index 1 for votes.
    """
    scope = [
        "https://www.googleapis.com/auth/spreadsheets",
        "https://www.googleapis.com/auth/drive"
    ]
    # Authenticate using the service account JSON file
    creds = Credentials.from_service_account_info(gsheet_creds_info, scopes=scope)
    client = gspread.authorize(creds)
    spreadsheet = client.open(SPREADSHEET_NAME)
    worksheet = spreadsheet.get_worksheet(worksheet_index)
    
    return worksheet

def add_name(name, description, tag):
    """
    Append a new team name submission to the "Submissions" tab (worksheet index 0).
    Checks for duplicates (case-insensitive) and validates input.
    """
    name = str(name).strip()
    description = str(description).strip()
    tag = str(tag).strip()
    
    if name == "":
        return "⚠️ Please enter a team name."
    if description == "":
        return "⚠️ Please include a description."
    if tag == "":
        return "⚠️ Please include an anonymous tag."
    
    worksheet = get_worksheet(0)
    data = worksheet.get_all_values()
    
    # If the sheet is empty, add the header row with proper ordering
    if not data:
        worksheet.append_row(["Name", "Description", "Tag", "Timestamp"])
        data = worksheet.get_all_values()
    
    # Check for duplicate team names (case-insensitive)
    submitted_names = [row[0].strip().lower() for row in data[1:]]
    if name.lower() in submitted_names:
        return f"⚠️ The name '{name}' has already been submitted."
    
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    worksheet.append_row([name, description, tag, timestamp])
    
    return f"✅ Team name '{name}' submitted successfully at {timestamp}!"


def cast_votes(selected_names, votes_remaining):
    """
    Append votes for the selected team names to the "Votes" tab (worksheet index 1).
    Enforces the vote limit per user and checks the voting start time.
    """
    if datetime.now() < VOTING_START:
        return votes_remaining, f"⚠️ Voting is not open yet. Please come back after {VOTING_START.strftime('%Y-%m-%d %H:%M:%S')}."
    
    if not selected_names:
        return votes_remaining, "⚠️ No names selected. Please choose up to 3."
    
    if isinstance(selected_names, str):
        selected_names = [selected_names]
    
    if votes_remaining <= 0:
        return votes_remaining, "⚠️ You have no votes remaining."
    
    if len(selected_names) > votes_remaining:
        return votes_remaining, f"⚠️ You can only vote for {votes_remaining} more name(s)."
    
    # Get the votes worksheet (tab index 1)
    worksheet = get_worksheet(1)
    for item in selected_names:
        name_only = item.split(":")[0].strip()
        worksheet.append_row([name_only])
    
    
    new_remaining = votes_remaining - len(selected_names)
    message = "✅ Vote recorded!" if len(selected_names) == 1 else "✅ Votes recorded!"
    if new_remaining > 0:
        message += f" You have {new_remaining} vote(s) left."
    else:
        message += " You have no votes left."
    
    return new_remaining, message

def get_leaderboard():
    """
    Read both the Submissions and Votes tabs to build a leaderboard.
    Returns a DataFrame with team names and their respective vote counts.
    """
    submissions_ws = get_worksheet(0)
    votes_ws = get_worksheet(1)
    
    submissions_data = submissions_ws.get_all_values()
    votes_data = votes_ws.get_all_values()
    
    if len(submissions_data) < 2:
        return pd.DataFrame(columns=["Team Name", "Votes"])
    
    # Extract team names from submissions (skip header)
    submitted_names = [row[0] for row in submissions_data[1:]]
    unique_names = list(dict.fromkeys(submitted_names))
    
    # Count votes for each team name
    vote_counts = {}
    for row in votes_data:
        if row:
            vote_name = row[0]
            vote_counts[vote_name] = vote_counts.get(vote_name, 0) + 1
    
    leaderboard_data = []
    for name in unique_names:
        leaderboard_data.append([name, vote_counts.get(name, 0)])
    
    leaderboard_data.sort(key=lambda x: x[1], reverse=True)
    leader_df = pd.DataFrame(leaderboard_data, columns=["Team Name", "Votes"])
    
    return leader_df

def refresh_name_list():
    """
    Refresh the list of submitted team names for the voting interface.
    """
    submissions_ws = get_worksheet(0)
    data = submissions_ws.get_all_values()
    names_list = []
    if len(data) > 1:
        for row in data[1:]:
            name, description = row[0], row[1]
            display_str = f"{name}: {description}"
            names_list.append(display_str)
    # names_list = [row[0] for row in data[1:]] if len(data) > 1 else []
    
    return gr.update(choices=names_list, value=[])

def generate_leaderboard_chart():
    """
    Create a bar chart from the leaderboard data using matplotlib.
    """
    leader_df = get_leaderboard()
    if leader_df.empty:
        fig, ax = plt.subplots()
        ax.text(0.5, 0.5, 'No data available', horizontalalignment='center', verticalalignment='center', fontsize=14)
        ax.axis('off')
        plt.close()
        return fig
        
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.bar(leader_df["Team Name"], leader_df["Votes"], color="skyblue")
    ax.set_xlabel("Team Name")
    ax.set_ylabel("Votes")
    ax.set_title("Leaderboard Votes")
    plt.xticks(rotation=45, ha="right")
    fig.tight_layout()
    plt.close()
    
    return fig

# Build the Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("## 🏆 **Team Name Voting App**\nSubmit ideas and vote for your favorite team name.")
    
    with gr.Tab("Submit Team Name"):
        gr.Markdown("**Propose a New Team Name**")
        with gr.Row():
            name_input = gr.Textbox(label="Team Name", placeholder="Enter a team name idea")
            description_input = gr.Textbox(label="Description", placeholder="Enter a description for the team name") 
            tag_input = gr.Textbox(label="Anonymous Tag", placeholder="e.g., your initials")

        submit_btn = gr.Button("Submit")
        submit_msg = gr.Markdown()  # Feedback message
        submit_btn.click(fn=add_name, inputs=[name_input, description_input, tag_input], outputs=submit_msg)
    
    with gr.Tab("Vote for Name"):
        gr.Markdown("**Vote for Your Top 3 Choices** (each user can vote for up to 3 names in total)")
        # Initialize checkbox options from current submissions
        submissions_ws = get_worksheet(0)
        data = submissions_ws.get_all_values()
        initial_names = [f"{row[0]}: {row[1]}" for row in data[1:]] if len(data) > 1 else []
        vote_group = gr.CheckboxGroup(choices=initial_names, label="Select up to 3 names")
        vote_btn = gr.Button("Vote")
        vote_msg = gr.Markdown()  # Feedback message for voting
        votes_state = gr.State(3)  # Track remaining votes for the session
        vote_btn.click(fn=cast_votes, inputs=[vote_group, votes_state], outputs=[votes_state, vote_msg])
        refresh_btn = gr.Button("🔄 Refresh Names List")
        refresh_btn.click(fn=refresh_name_list, inputs=None, outputs=vote_group)
    
    with gr.Tab("Leaderboard"):
        gr.Markdown("**Current Vote Leaderboard** (names sorted by votes)")
        leader_display = gr.Dataframe(value=pd.DataFrame(columns=["Team Name", "Votes"]), headers=["Team Name", "Votes"], interactive=False)
        refresh_leader_btn = gr.Button("🔄 Refresh Leaderboard")
        leader_plot = gr.Plot(label="Leaderboard Chart")
        # Refresh both the table and the chart
        refresh_leader_btn.click(fn=get_leaderboard, inputs=None, outputs=leader_display)
        refresh_leader_btn.click(fn=generate_leaderboard_chart, inputs=None, outputs=leader_plot)
        demo.load(fn=get_leaderboard, inputs=None, outputs=leader_display)
        demo.load(fn=generate_leaderboard_chart, inputs=None, outputs=leader_plot)
    
    demo.load(fn=get_leaderboard, inputs=None, outputs=leader_display)

# Launch the app
demo.launch(share=True)