team-up / app.py
maringetxway's picture
Update app.py
e2a5983 verified
raw
history blame
11 kB
import gradio as gr
import json
import pandas as pd
import os
import shutil
import datetime
# Path to the data file
DATA_FILE = os.path.join("data", "teamup_data.json")
# Load the ADMIN_CODE environment variable
ADMIN_CODE = os.getenv("ADMIN_CODE", "")
# Ensure data file exists
os.makedirs("data", exist_ok=True)
if not os.path.exists(DATA_FILE) or os.path.getsize(DATA_FILE) == 0:
with open(DATA_FILE, "w") as f:
json.dump([], f)
# Function to create a backup of the data
def backup_data():
source_file = DATA_FILE
backup_dir = './data/backup'
os.makedirs(backup_dir, exist_ok=True)
timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
backup_file = os.path.join(backup_dir, f'teamup_data_backup_{timestamp}.json')
shutil.copy(source_file, backup_file)
print(f"βœ… Backup created at {backup_file}")
# Function to submit or update a profile
def submit_profile(name, discord, city, country, address, looking, onlinecheck, languages, laptop, robot, skills, describe3, experience, idea):
print("🟒 Submit button clicked.")
print(f"Incoming: {discord=}, {city=}, {country=}, {languages=}, {laptop=}, {robot=}")
if not discord or not city or not country or not laptop or not robot:
return "❌ Please fill in all required fields."
if not languages or not isinstance(languages, list) or len(languages) == 0:
return "❌ Please select at least one language."
# Ensure country is stored as a string (in case form allows lists)
if isinstance(country, list):
country = country[0] if country else ""
with open(DATA_FILE, "r") as f:
data = json.load(f)
for d in data:
if d["Discord"].lower() == discord.lower():
d.update({
"Name": name,
"City": city,
"Country": country,
"Address": address,
"Looking for Team": looking,
"Onlinecheck": onlinecheck,
"Languages": languages,
"Laptop": laptop,
"Robot": robot,
"Skills": skills,
"Describe3": describe3,
"Experience": experience,
"Project Idea": idea
})
break
else:
data.append({
"Name": name,
"Discord": discord,
"City": city,
"Country": country,
"Address": address,
"Looking for Team": looking,
"Onlinecheck": onlinecheck,
"Languages": languages,
"Laptop": laptop,
"Robot": robot,
"Skills": skills,
"Describe3": describe3,
"Experience": experience,
"Project Idea": idea
})
try:
with open(DATA_FILE, "w") as f:
json.dump(data, f, indent=2)
print(f"βœ… Successfully wrote {len(data)} profiles to {DATA_FILE}")
backup_data() # Backup after every update
except Exception as e:
print(f"❌ Failed to write to {DATA_FILE}: {e}")
return "❌ Error saving your profile. Please try again."
return "βœ… Profile saved!"
# Function to filter participants by fields
def filter_by_fields(selected_country, selected_city, selected_language):
with open(DATA_FILE, "r") as f:
data = json.load(f)
df = pd.DataFrame(data)
# Convert list values to readable strings
df["Languages"] = df["Languages"].apply(lambda langs: ", ".join(langs) if isinstance(langs, list) else langs)
if df.empty or "Country" not in df.columns or "Languages" not in df.columns:
return "<p>No participants found.</p>"
if selected_country != "All":
df = df[df["Country"] == selected_country]
if selected_city != "All":
df = df[df["City"] == selected_city]
if selected_language != "All":
df = df[df["Languages"].apply(lambda langs: selected_language in langs)]
# Hide address
if "Address" in df.columns:
df = df.drop(columns=["Address"])
# Rename column headers for display only
display_names = {
"Discord": "Discord",
"Name": "Name",
"City": "City",
"Country": "Country",
"Looking for Team": "Looking for Team",
"Onlinecheck": "How?",
"Languages": "Languages",
"Laptop": "Laptop",
"Robot": "Robot",
"Skills": "Skills",
"Describe3": "Describe",
"Experience": "Experience",
"Project Idea": "Project Idea"
}
html = '<h3 style="margin-top:20px;">πŸ” Find your matching Teammates & Register your team <a href="https://forms.gle/gJEMGD4CEA2emhD18" target="_blank">here</a>πŸ‘ˆπŸ‘ˆ</h3>'
html += "<table style='width:100%; border-collapse: collapse;'>"
# Header row
html += "<tr>" + "".join(
f"<th style='border: 1px solid #ccc; padding: 6px;'>{display_names.get(col, col)}</th>"
for col in df.columns
) + "</tr>"
# Data rows
for _, row in df.iterrows():
html += "<tr>"
for col in df.columns:
val = row[col]
if col == "Discord":
val = f"<a href='https://discord.com/users/{val}' target='_blank'>{val}</a>"
html += f"<td style='border: 1px solid #eee; padding: 6px;'>{val}</td>"
html += "</tr>"
html += "</table>"
return html
# List of all countries in alphabetical order
ALL_COUNTRIES = [
"Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria",
"Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan",
"Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cabo Verde", "Cambodia",
"Cameroon", "Canada", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo (Congo-Brazzaville)",
"Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia (Czech Republic)", "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica",
"Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Eswatini (fmr. 'Swaziland')", "Ethiopia",
"Fiji", "Finland", "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada",
"Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hungary", "Iceland", "India", "Indonesia",
"Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya",
"Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia",
"Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco",
"Mozambique", "Myanmar (formerly Burma)", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria",
"North Macedonia", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa",
"San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia",
"Solomon Islands", "Somalia", "South Africa", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Sweden", "Switzerland",
"Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia",
"Turkey", "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States of America", "Uruguay",
"Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"
]
# Function to update the dropdown choices
def update_dropdown_choices():
return gr.update(choices=["All"] + ALL_COUNTRIES, value="All")
# Setup Gradio interface
with gr.Blocks(css=".gr-dropdown { max-height: 100px; overflow-y: auto; font-size: 12px; }") as demo:
gr.Markdown("# 🌍 LeRobot Worldwide Hackathon - Team-Up Dashboard")
gr.Markdown("1. Submit or update your profile to find matching teammates and contact them on Discord. (Required fields marked with *.) ")
# Input fields and buttons setup
with gr.Row():
with gr.Column():
name = gr.Text(label="Name")
discord = gr.Text(label="πŸ‘€ Discord Username *")
city = gr.Text(label="πŸ“ City *")
country = gr.Dropdown(label="🌍 Country *", choices=ALL_COUNTRIES, value="All") # Dropdown for Country
address = gr.Text(label="Address (optional)")
looking = gr.Radio(["Yes", "No"], label="πŸ” Looking for a team?")
onlinecheck = gr.Radio(["Participate Online", "Join a Local Hackathon"], label="πŸš€ I will...")
languages = gr.CheckboxGroup(choices=["English", "French", "Spanish", "German", "Portuguese", "Chinese", "Arabic", "Hindi"], label="Languages Spoken *")
laptop = gr.Text(label="πŸ’» Laptop Setup *")
robot = gr.Text(label="Robot Setup *")
skills = gr.Text(label="🧠 Your Skills (comma separated)")
describe3 = gr.Text(label="πŸ€— 3 Words That Describe You")
experience = gr.Dropdown(choices=["Beginner", "Intermediate", "Advanced"], label="Experience Level", value="Beginner")
idea = gr.Textbox(label="Project Idea (optional)")
submit_btn = gr.Button("Submit or Update Profile βœ…")
status = gr.Textbox(label="", interactive=False)
with gr.Column():
gr.Markdown("🎯 2. Choose your preferences to find your teammates (country, city or language)")
country_filter = gr.Dropdown(label="Filter by Country", choices=["All"], value="All", allow_custom_value=False)
city_filter = gr.Dropdown(label="Filter by City", choices=["All"], value="All", allow_custom_value=False)
language_filter = gr.Dropdown(label="Filter by Language", choices=["All"], value="All", allow_custom_value=False)
table_html = gr.HTML(label="Matching Participants")
submit_btn.click(
submit_profile,
inputs=[name, discord, city, country, address, looking, onlinecheck, languages, laptop, robot, skills, describe3, experience, idea],
outputs=[status]
)
country_filter.change(fn=filter_by_fields, inputs=[country_filter, city_filter, language_filter], outputs=table_html)
city_filter.change(fn=filter_by_fields, inputs=[country_filter, city_filter, language_filter], outputs=table_html)
language_filter.change(fn=filter_by_fields, inputs=[country_filter, city_filter, language_filter], outputs=table_html)
demo.launch()