basma-b's picture
Update app.py
9d1966a verified
import gradio as gr
from huggingface_hub import HfApi, Repository, whoami, snapshot_download
import json
import tempfile
import os
# Config
DATASET_REPO = "competition-private/teams"
DATASET_FILE = "teams.json"
hf_token = os.environ.get("TOKEN")
# Authenticate HF user via Gradio
def submit_form(email, team, affiliation, student, oauth_token: gr.OAuthToken = None):
# Use HF API with token
api = HfApi()
if oauth_token is None or oauth_token.token is None:
raise gr.Error("You must be logged in to register!")
user_info = api.whoami(token=oauth_token.token)
hf_user_id = user_info['name']
# Validate required fields
if not email or not team or not student:
raise gr.Error("Please fill all required fields.")
# Prepare new record
new_record = {
"email": email,
"team": team,
"affiliation": affiliation or "",
"student": student,
"hf_id": hf_user_id
}
# Clone repo to temp folder
# Step 1: Download snapshot of the dataset repo
local_dir = snapshot_download(
repo_id=DATASET_REPO,
repo_type="dataset",
use_auth_token=hf_token,
local_dir=tempfile.mkdtemp(), # So you can write to it
local_dir_use_symlinks=False # Important for modifying files
)
dataset_path = os.path.join(local_dir, DATASET_FILE)
# Step 2: Load existing data
if os.path.exists(dataset_path):
with open(dataset_path, "r") as f:
data = json.load(f)
else:
data = []
# Step 3: Prevent duplicate submissions
if any(entry["hf_id"] == hf_user_id for entry in data):
return "You have already registered."
data.append(new_record)
# Step 4: Save updated file locally
with open(dataset_path, "w") as f:
json.dump(data, f, indent=2)
# Step 5: Upload the updated file to the dataset repo
api = HfApi()
api.upload_file(
path_or_fileobj=dataset_path,
path_in_repo=DATASET_FILE,
repo_id=DATASET_REPO,
repo_type="dataset",
token=hf_token,
commit_message=f"Add registration for {hf_user_id}"
)
return "Registration successful! Now you need to join the competition's HF organization click on https://huggingface.co/organizations/e2lmc-competition/share/RyoEZjTiJQMpOLyTaHCsaTEFdRABGJkUrh"
return f"""πŸš€ Registration successful!
πŸ‘‰ Now you need to join the competition's HF organization, [**join the competition organization**](https://huggingface.co/organizations/e2lmc-competition/share/RyoEZjTiJQMpOLyTaHCsaTEFdRABGJkUrh)
"""
def check_registration(oauth_token: gr.OAuthToken = None):
if oauth_token is None or oauth_token.token is None:
raise gr.Error("You must be logged in to register!")
api = HfApi()
user_info = api.whoami(token=oauth_token.token)
hf_user_id = user_info['name']
local_dir = snapshot_download(
repo_id=DATASET_REPO,
repo_type="dataset",
use_auth_token=hf_token,
local_dir=tempfile.mkdtemp(),
local_dir_use_symlinks=False
)
dataset_path = os.path.join(local_dir, DATASET_FILE)
if os.path.exists(dataset_path):
with open(dataset_path, "r") as f:
data = json.load(f)
else:
data = []
for entry in data:
if entry["hf_id"] == hf_user_id:
return f"""βœ… You are registered in team: **{entry['team']}**
πŸ‘‰ To submit your system, [**join the competition organization**](https://huggingface.co/organizations/e2lmc-competition/share/RyoEZjTiJQMpOLyTaHCsaTEFdRABGJkUrh)
"""
return "❌ You are not registered yet."
with gr.Blocks() as demo:
gr.Markdown("### Registration Form (HuggingFace login required)")
# gr.Markdown("Login to Hugging Face to register to E2LM Competition.")
gr.Markdown("<span style='color:red'><strong>Note</strong>: You must log-in to Hugging Face to register to the competition.</span>")
gr.LoginButton(min_width=250)
# Hidden text to store HF username from auth
hf_username = gr.Textbox(label="HF Username", visible=False)
#with gr.Row():
email = gr.Textbox(label="E-mail*", placeholder="[email protected]", lines=1)
team = gr.Textbox(label="Team name*", lines=1)
affiliation = gr.Textbox(label="Affiliation (optional)", lines=1)
student = gr.Radio(
choices=["Yes", "No"],
label="Are you a student?*",
value=None
)
#output = gr.Textbox(label="Status", interactive=False)
output = gr.Markdown(label="Status")
submit_btn = gr.Button("Submit")
submit_btn.click(
fn=submit_form,
inputs=[email, team, affiliation, student],
outputs=output
)
check_btn = gr.Button("Check Registration Status")
check_btn.click(
fn=check_registration,
outputs=output
)
demo.launch()