Spaces:
Paused
Paused
Download app.py from kode24/name_votinG: direct link, hf CLI and curl.
- Browser
- Download file 9.06 kB
-
https://huggingface.co/spaces/kode24/name_votinG/resolve/main/app.py
- Command line
-
hf download hf://spaces/kode24/name_votinG/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kode24/name_votinG/resolve/main/app.py
9.06 kB
| 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) |