Spaces:
Runtime error
Runtime error
Commit ·
90b78ed
1
Parent(s): 447fff1
update features for hugsim competition
Browse filesFiles changed (6)
1 unmodified line234567891090 unmodified lines10110210310410510610713 unmodified lines12112212312412512612712812913013113213313412 unmodified lines1471481491501511521531 unmodified line1551561571581591601611 unmodified line1631641651661671681691 unmodified line1711721731741751761771 unmodified line17918018118218318418529 unmodified lines21521621721821922022131 unmodified lines2532542552562572582597 unmodified lines26726826927027127227384 unmodified lines35835936036136236336436536636736836937037132 unmodified lines4044054064074084094101 unmodified line41241341441541641741826 unmodified lines4454464471 unmodified lineimport osimport threadingimport timefrom fastapi import Depends, FastAPI, File, Form, HTTPException, Request, UploadFilefrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom huggingface_hub import hf_hub_download90 unmodified lines@app.get("/", response_class=HTMLResponse)async def read_form(request: Request):"""This function is used to render the HTML file:param request:13 unmodified lines@app.get("/login_status", response_class=JSONResponse)async def use_oauth(request: Request, user_token: str = Depends(utils.user_authentication)):if user_token:return {"response": 2}return {"response": 1}@app.get("/logout", response_class=HTMLResponse)async def user_logout(request: Request):"""Endpoint that logs out the user (e.g. delete cookie session)."""if "oauth_info" in request.session:12 unmodified lines@app.get("/competition_info", response_class=JSONResponse)async def get_comp_info(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)info = competition_info.competition_descresp = {"response": info}1 unmodified line@app.get("/dataset_info", response_class=JSONResponse)async def get_dataset_info(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)info = competition_info.dataset_descresp = {"response": info}1 unmodified line@app.get("/rules", response_class=JSONResponse)async def get_rules(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)if competition_info.rules is not None:return {"response": competition_info.rules}1 unmodified line@app.get("/submission_info", response_class=JSONResponse)async def get_submission_info(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)info = competition_info.submission_descresp = {"response": info}1 unmodified line@app.post("/leaderboard", response_class=JSONResponse)async def fetch_leaderboard(request: Request, body: LeaderboardRequest, user_token: str = Depends(utils.user_authentication)):lb = body.lb29 unmodified lines@app.post("/my_submissions", response_class=JSONResponse)async def my_submissions(request: Request, user_token: str = Depends(utils.user_authentication)):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)if user_token is None:return {31 unmodified linessubmission_text = SUBMISSION_TEXT.format(competition_info.submission_limit)submission_selection_text = SUBMISSION_SELECTION_TEXT.format(competition_info.selection_limit)team_name = utils.get_team_name(user_token, COMPETITION_ID, HF_TOKEN)resp = {"response": {7 unmodified lines@app.post("/new_submission", response_class=JSONResponse)async def new_submission(request: Request,submission_file: UploadFile = File(None),hub_model: str = Form(...),84 unmodified linesreturn {"success": False, "error": "Team name cannot be empty."}try:utils.update_team_name(user_token, new_team_name, COMPETITION_ID, HF_TOKEN)return {"success": True, "error": ""}except Exception as e:return {"success": False, "error": str(e)}@app.post("/admin/comp_info", response_class=JSONResponse)async def admin_comp_info(request: Request, user_token: str = Depends(utils.user_authentication)):comp_org = COMPETITION_ID.split("/")[0]user_is_admin = utils.is_user_admin(user_token, comp_org)if not user_is_admin:32 unmodified lines@app.post("/admin/update_comp_info", response_class=JSONResponse)async def update_comp_info(request: Request, user_token: str = Depends(utils.user_authentication)):comp_org = COMPETITION_ID.split("/")[0]user_is_admin = utils.is_user_admin(user_token, comp_org)if not user_is_admin:1 unmodified linecompetition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)data = await request.json()config = data["config"]markdowns = data["markdowns"]26 unmodified linesreturn {"success": False}, 500return {"success": True}1 unmodified line2345678910111290 unmodified lines10310410510610710810913 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414512 unmodified lines1581591601611621631641 unmodified line1661671681691701711721 unmodified line1741751761771781791801 unmodified line1821831841851861871881 unmodified line19019119219319419519629 unmodified lines22622722822923023123231 unmodified lines2642652662672682692707 unmodified lines27827928028128228328484 unmodified lines36937037137237337437537637737837938038138232 unmodified lines4154164174184194204211 unmodified line42342442542642742826 unmodified lines4554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844851 unmodified lineimport osimport threadingimport timeimport iofrom typing import Dict, Anyfrom fastapi import Depends, FastAPI, File, Form, HTTPException, Request, UploadFile, Bodyfrom fastapi.responses import HTMLResponse, JSONResponse, FileResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templatesfrom huggingface_hub import hf_hub_download90 unmodified lines@app.get("/", response_class=HTMLResponse)def read_form(request: Request):"""This function is used to render the HTML file:param request:13 unmodified lines@app.get("/login_status", response_class=JSONResponse)def use_oauth(request: Request, user_token: str = Depends(utils.user_authentication)):result = {"is_login": False,"is_admin": False,"is_registered": False,}comp_org = COMPETITION_ID.split("/")[0]if user_token:result["is_login"] = Trueresult["is_admin"] = utils.is_user_admin(user_token, comp_org)result["is_registered"] = utils.team_file_api.get_team_info(user_token) is not Nonereturn {"response": result}@app.get("/logout", response_class=HTMLResponse)def user_logout(request: Request):"""Endpoint that logs out the user (e.g. delete cookie session)."""if "oauth_info" in request.session:12 unmodified lines@app.get("/competition_info", response_class=JSONResponse)def get_comp_info(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)info = competition_info.competition_descresp = {"response": info}1 unmodified line@app.get("/dataset_info", response_class=JSONResponse)def get_dataset_info(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)info = competition_info.dataset_descresp = {"response": info}1 unmodified line@app.get("/rules", response_class=JSONResponse)def get_rules(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)if competition_info.rules is not None:return {"response": competition_info.rules}1 unmodified line@app.get("/submission_info", response_class=JSONResponse)def get_submission_info(request: Request):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)info = competition_info.submission_descresp = {"response": info}1 unmodified line@app.post("/leaderboard", response_class=JSONResponse)def fetch_leaderboard(request: Request, body: LeaderboardRequest, user_token: str = Depends(utils.user_authentication)):lb = body.lb29 unmodified lines@app.post("/my_submissions", response_class=JSONResponse)def my_submissions(request: Request, user_token: str = Depends(utils.user_authentication)):competition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)if user_token is None:return {31 unmodified linessubmission_text = SUBMISSION_TEXT.format(competition_info.submission_limit)submission_selection_text = SUBMISSION_SELECTION_TEXT.format(competition_info.selection_limit)team_name = utils.team_file_api.get_team_info(user_token)["name"]resp = {"response": {7 unmodified lines@app.post("/new_submission", response_class=JSONResponse)def new_submission(request: Request,submission_file: UploadFile = File(None),hub_model: str = Form(...),84 unmodified linesreturn {"success": False, "error": "Team name cannot be empty."}try:utils.team_file_api.update_and_create_team_name(user_token, new_team_name)return {"success": True, "error": ""}except Exception as e:return {"success": False, "error": str(e)}@app.post("/admin/comp_info", response_class=JSONResponse)def admin_comp_info(request: Request, user_token: str = Depends(utils.user_authentication)):comp_org = COMPETITION_ID.split("/")[0]user_is_admin = utils.is_user_admin(user_token, comp_org)if not user_is_admin:32 unmodified lines@app.post("/admin/update_comp_info", response_class=JSONResponse)def update_comp_info(data: Dict[str, Any] = Body(...), user_token: str = Depends(utils.user_authentication)):comp_org = COMPETITION_ID.split("/")[0]user_is_admin = utils.is_user_admin(user_token, comp_org)if not user_is_admin:1 unmodified linecompetition_info = CompetitionInfo(competition_id=COMPETITION_ID, autotrain_token=HF_TOKEN)config = data["config"]markdowns = data["markdowns"]26 unmodified linesreturn {"success": False}, 500return {"success": True}@app.get("/register_template_file")def register_example_file():file_path = os.path.join(BASE_DIR, "static", "Competition Participants Information Collection Template.xlsx")return FileResponse(file_path, media_type="application/octet-stream", filename="Competition Participants Information Collection Template.xlsx")@app.post("/register")def register(teamname: str = Form(...),file: UploadFile = Form(...),user_token: str = Depends(utils.user_authentication)):if user_token is None:return {"success": False, "response": "Please login."}file_bytes = file.file.read()file_stream = io.BytesIO(file_bytes)file_stream.seek(0)utils.team_file_api.create_team(user_token,teamname,file_stream)return {"success": True, "response": "Team created successfully."}
2 unmodified lines3456782 unmodified lines11121314151617138 unmodified lines15615715815916016116216316416516616712 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022 unmodified linesimport jsonimport osimport timefrom dataclasses import dataclassimport pandas as pd2 unmodified linesfrom competitions.enums import SubmissionStatusfrom competitions.info import CompetitionInfofrom competitions.utils import run_evaluation_DOCKERFILE = """138 unmodified lines_readme += "colorTo: indigo\n"_readme += "sdk: docker\n"_readme += "pinned: false\n"_readme += "duplicated_from: autotrain-projects/autotrain-advanced\n"_readme += "---\n"_readme = io.BytesIO(_readme.encode())return _readmedef create_space(self, team_id, submission_id, submission_repo, space_id):api = HfApi(token=self.token)params = {"competition_id": self.competition_id,12 unmodified lines"submission_filenames": self.submission_filenames,}api.add_space_secret(repo_id=space_id, key="PARAMS", value=json.dumps(params))readme = self._create_readme(space_id.split("/")[-1])api.upload_file(path_or_fileobj=readme,path_in_repo="README.md",repo_id=space_id,repo_type="space",)_dockerfile = io.BytesIO(_DOCKERFILE.encode())api.upload_file(path_or_fileobj=_dockerfile,path_in_repo="Dockerfile",repo_id=space_id,repo_type="space",)self._queue_submission(team_id, submission_id)def run(self):2 unmodified lines34567892 unmodified lines12131415161718138 unmodified lines15715815916016116216316416516616716816917017117212 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212 unmodified linesimport jsonimport osimport timeimport uuidfrom dataclasses import dataclassimport pandas as pd2 unmodified linesfrom competitions.enums import SubmissionStatusfrom competitions.info import CompetitionInfofrom competitions.utils import run_evaluation, user_token_api_DOCKERFILE = """138 unmodified lines_readme += "colorTo: indigo\n"_readme += "sdk: docker\n"_readme += "pinned: false\n"_readme += "---\n"_readme = io.BytesIO(_readme.encode())return _readmedef create_space(self, team_id, submission_id, submission_repo, space_id):server_space_id = space_id + "-server"client_space_id = space_id + "-client"space_auth_token = uuid.uuid4().hexuser_token = user_token_api.get(team_id)api = HfApi(token=self.token)params = {"competition_id": self.competition_id,12 unmodified lines"submission_filenames": self.submission_filenames,}api.add_space_secret(repo_id=server_space_id, key="PARAMS", value=json.dumps(params))api.add_space_secret(repo_id=server_space_id, key="HUGSIM_AUTH_TOKEN", value=space_auth_token)api.add_space_secret(repo_id=server_space_id, key="HF_TOKEN", value=self.token)readme = self._create_readme(space_id.split("/")[-1])api.upload_file(path_or_fileobj=readme,path_in_repo="README.md",repo_id=server_space_id,repo_type="space",)api.upload_file(path_or_fileobj=io.BytesIO(_DOCKERFILE.encode()),path_in_repo="Dockerfile",repo_id=space_id,repo_type="space",)api.add_space_secret(repo_id=client_space_id, key="HUGSIM_AUTH_TOKEN", value=space_auth_token)api.snapshot_download(repo_id=submission_repo,repo_type="model",revision="main",token=user_token,local_dir="/tmp/data/user_repo",allow_patterns=["*"],)api.upload_folder(repo_id=client_space_id,repo_type="space",folder_path="/tmp/data/user_repo",)self._queue_submission(team_id, submission_id)def run(self):
5 unmodified lines6789101112131415105 unmodified lines1211221231241251261271285 unmodified lines13413513613713813914014114214314421 unmodified lines1661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112 unmodified lines2142152162172182192202212222232242252262272282292302312 unmodified lines23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626720 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353365 unmodified linesimport pandas as pdfrom huggingface_hub import HfApi, hf_hub_downloadfrom competitions.enums import SubmissionStatusfrom competitions.errors import AuthenticationError, PastDeadlineError, SubmissionError, SubmissionLimitErrorfrom competitions.utils import token_information@dataclass105 unmodified linesif current_datetime > self.end_date:raise PastDeadlineError("Competition has ended.")user_info = self._get_user_info(user_token)team_id = self._get_team_id(user_info, create_team=False)team_submission_info = self._download_team_submissions(team_id)for sub in team_submission_info["submissions"]:5 unmodified linesself._upload_team_submissions(team_id, team_submission_info)def _get_team_subs(self, team_id, private=False):team_submissions_info = self._download_team_submissions(team_id)submissions_df = pd.DataFrame(team_submissions_info["submissions"])if len(submissions_df) == 0:return pd.DataFrame(), pd.DataFrame()if not private:submissions_df = submissions_df.drop(columns=["private_score"])21 unmodified linesreturn user_infodef my_submissions(self, user_token):user_info = self._get_user_info(user_token)current_date_time = datetime.now()private = Falseif current_date_time >= self.end_date:private = Trueteam_id = self._get_team_id(user_info, create_team=False)if not team_id:return pd.DataFrame()return self._get_team_subs(team_id, private=private)def _create_team(self, user_team, user_id, user_name):team_metadata = hf_hub_download(repo_id=self.competition_id,filename="teams.json",token=self.token,repo_type="dataset",)with open(team_metadata, "r", encoding="utf-8") as f:team_metadata = json.load(f)# create a new team, if user is not in any teamteam_id = str(uuid.uuid4())user_team[user_id] = team_idteam_metadata[team_id] = {"id": team_id,"name": user_name,"members": [user_id],"leader": user_id,}user_team_json = json.dumps(user_team, indent=4)user_team_json_bytes = user_team_json.encode("utf-8")user_team_json_buffer = io.BytesIO(user_team_json_bytes)team_metadata_json = json.dumps(team_metadata, indent=4)team_metadata_json_bytes = team_metadata_json.encode("utf-8")team_metadata_json_buffer = io.BytesIO(team_metadata_json_bytes)team_submission_info = {}team_submission_info["id"] = team_idteam_submission_info["submissions"] = []2 unmodified linesteam_submission_info_json_buffer = io.BytesIO(team_submission_info_json_bytes)api = HfApi(token=self.token)api.upload_file(path_or_fileobj=user_team_json_buffer,path_in_repo="user_team.json",repo_id=self.competition_id,repo_type="dataset",)api.upload_file(path_or_fileobj=team_metadata_json_buffer,path_in_repo="teams.json",repo_id=self.competition_id,repo_type="dataset",)api.upload_file(path_or_fileobj=team_submission_info_json_buffer,path_in_repo=f"submission_info/{team_id}.json",2 unmodified lines)return team_iddef _get_team_id(self, user_info, create_team):user_id = user_info["id"]user_name = user_info["name"]user_team = hf_hub_download(repo_id=self.competition_id,filename="user_team.json",token=self.token,repo_type="dataset",)with open(user_team, "r", encoding="utf-8") as f:user_team = json.load(f)if user_id in user_team:return user_team[user_id]if create_team is False:return None# if user_id is not there in user_team, create a new teamteam_id = self._create_team(user_team, user_id, user_name)return team_iddef new_submission(self, user_token, uploaded_file, submission_comment):# verify tokenuser_info = self._get_user_info(user_token)submission_id = str(uuid.uuid4())user_id = user_info["id"]team_id = self._get_team_id(user_info, create_team=True)# check if team can submit to the competitionif self._is_submission_allowed(team_id) is False:20 unmodified linessubmission_id=submission_id,submission_comment=submission_comment,)else:# Download the submission repo and upload it to the competition repo# submission_repo = snapshot_download(# repo_id=uploaded_file,# local_dir=submission_id,# token=user_token,# repo_type="model",# )# api = HfApi(token=self.token)# competition_user = self.competition_id.split("/")[0]# api.create_repo(# repo_id=f"{competition_user}/{submission_id}",# repo_type="model",# private=True,# )# api.upload_folder(# folder_path=submission_repo,# repo_id=f"{competition_user}/{submission_id}",# repo_type="model",# )# create barebones submission runner spaceuser_api = HfApi(token=user_token)# submission_id is the sha of the submitted model repo + "__" + submission_idsubmission_id = user_api.model_info(repo_id=uploaded_file).sha + "__" + submission_idcompetition_organizer = self.competition_id.split("/")[0]space_id = f"{competition_organizer}/comp-{submission_id}"api = HfApi(token=self.token)api.create_repo(repo_id=space_id,repo_type="space",space_sdk="docker",space_hardware=self.hardware,private=True,)api.add_space_secret(repo_id=space_id, key="USER_TOKEN", value=user_token)submissions_made = self._increment_submissions(team_id=team_id,user_id=user_id,submission_id=submission_id,submission_comment=submission_comment,submission_repo=uploaded_file,space_id=space_id,)remaining_submissions = self.submission_limit - submissions_madereturn remaining_submissions5 unmodified lines678910111213141516105 unmodified lines1221231241251261271285 unmodified lines13413513613713813914014114214314414514614721 unmodified lines1691701711721731741751761771781791801811821831842 unmodified lines1871881891901911922 unmodified lines19519619719819920020120220320420520620720 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672685 unmodified linesimport pandas as pdfrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils._errors import EntryNotFoundErrorfrom competitions.enums import SubmissionStatusfrom competitions.errors import AuthenticationError, PastDeadlineError, SubmissionError, SubmissionLimitErrorfrom competitions.utils import token_information, team_file_api, user_token_api@dataclass105 unmodified linesif current_datetime > self.end_date:raise PastDeadlineError("Competition has ended.")team_id = team_file_api.get_team_info(user_token)["id"]team_submission_info = self._download_team_submissions(team_id)for sub in team_submission_info["submissions"]:5 unmodified linesself._upload_team_submissions(team_id, team_submission_info)def _get_team_subs(self, team_id, private=False):try:team_submissions_info = self._download_team_submissions(team_id)except EntryNotFoundError:return pd.DataFrame()submissions_df = pd.DataFrame(team_submissions_info["submissions"])if len(submissions_df) == 0:return pd.DataFrame()if not private:submissions_df = submissions_df.drop(columns=["private_score"])21 unmodified linesreturn user_infodef my_submissions(self, user_token):current_date_time = datetime.now()private = Falseif current_date_time >= self.end_date:private = Trueteam_id = team_file_api.get_team_info(user_token)["id"]if not team_id:return pd.DataFrame()return self._get_team_subs(team_id, private=private)def _create_submission(self, team_id: str):team_submission_info = {}team_submission_info["id"] = team_idteam_submission_info["submissions"] = []2 unmodified linesteam_submission_info_json_buffer = io.BytesIO(team_submission_info_json_bytes)api = HfApi(token=self.token)api.upload_file(path_or_fileobj=team_submission_info_json_buffer,path_in_repo=f"submission_info/{team_id}.json",2 unmodified lines)return team_iddef new_submission(self, user_token, uploaded_file, submission_comment):# verify tokenuser_info = self._get_user_info(user_token)submission_id = str(uuid.uuid4())user_id = user_info["id"]team_id = team_file_api.get_team_info(user_token)["id"]self._create_submission(team_id)# check if team can submit to the competitionif self._is_submission_allowed(team_id) is False:20 unmodified linessubmission_id=submission_id,submission_comment=submission_comment,)return self.submission_limit - submissions_madeuser_api = HfApi(token=user_token)# submission_id is the sha of the submitted model repo + "__" + submission_idsubmission_id = user_api.model_info(repo_id=uploaded_file).sha + "__" + submission_idcompetition_organizer = self.competition_id.split("/")[0]space_id = f"{competition_organizer}/comp-{submission_id}"server_space_id = space_id + "-server"client_space_id = space_id + "-client"api = HfApi(token=self.token)api.create_repo(repo_id=server_space_id,repo_type="space",space_sdk="docker",space_hardware=self.hardware,private=False,)api.create_repo(repo_id=client_space_id,repo_type="space",space_sdk="docker",space_hardware=self.hardware,private=True,)user_token_api.put(team_id, user_token)# api.add_space_secret(repo_id=space_id, key="USER_TOKEN", value=user_token)submissions_made = self._increment_submissions(team_id=team_id,user_id=user_id,submission_id=submission_id,submission_comment=submission_comment,submission_repo=uploaded_file,space_id=space_id,)remaining_submissions = self.submission_limit - submissions_madereturn remaining_submissions
139 unmodified lines14014114214314414514614714814915015115215315416 unmodified lines171172173174175176177178179180181182183158 unmodified lines342343344345346347348349350351352353105 unmodified lines4594604614624634644654664674684694704714724734744754764773 unmodified lines481482483484485486163 unmodified lines650651652653654655292 unmodified lines948949950951139 unmodified lines}).then(data => {const contentDiv = document.getElementById('content');// console.log(data.response.submissions);// contentDiv.innerHTML = marked.parse(data.response.submission_text) + data.response.submissions;if (data.response.submissions && data.response.submissions.length > 0 && data.response.error.length == 0) {// Start building the table HTMLlet tableHTML = `<div class="flex items-center"><input type="text" name="team_name" id="team_name" class="mt-1 mb-1 block me-2" value="${data.response.team_name}"><button id="updateTeamNameButton" type="button" class="confirm text-white bg-green-600 hover:bg-green-800 focus:ring-4 focus:outline-none focus:ring-green-300 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center me-2">Update Team Name</button></div>`;tableHTML += '<table border="1"><tr><th>Datetime</th><th>Submission ID</th><th>Public Score</th><th>Submission Comment</th><th>Selected</th><th>Status</th></tr>';// Iterate over each submission and add it to the table16 unmodified linesdocument.getElementById('updateSelectedSubmissionsButton').addEventListener('click', function () {updateSelectedSubmissions();});document.getElementById('updateTeamNameButton').addEventListener('click', function () {updateTeamName();});} else {// Display message if there are no submissionscontentDiv.innerHTML = marked.parse(data.response.submission_text) + marked.parse(data.response.error);}articleLoadingSpinner.classList.add('hidden');}).catch(error => {158 unmodified linesfunction checkOAuth() {var url = "/login_status";makeApiRequest(url, function (response) {if (response === 1) {document.getElementById("loginButton").style.display = "block";document.getElementById("logoutButton").style.display = "none";} else if (response === 2) {document.getElementById("loginButton").style.display = "none";document.getElementById("logoutButton").style.display = "block";}});105 unmodified lines</li><li><a href="#" id="my_submissions"class="flex items-center w-full p-2 text-gray-900 transition duration-75 rounded-lg pl-11 group hover:bg-gray-100">Mysubmissions</a></li><li><a href="#" id="new_submission"class="flex items-center w-full p-2 text-gray-900 transition duration-75 rounded-lg pl-11 group hover:bg-gray-100">Newsubmission</a></li></ul></li><li><a href="#" id="admin"class="flex items-center p-2 text-gray-900 rounded-lg hover:bg-gray-100 group"><svg class="flex-shrink-0 w-5 h-5 text-gray-500 transition duration-75 group-hover:text-gray-900"aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor"viewBox="0 0 24 24">3 unmodified lines<span class="flex-1 ms-3 whitespace-nowrap">Admin</span></a></li><li id="loginButton" style="display: none;"><a href="/login/huggingface"class="flex justify-center items-center bg-blue-400 hover:bg-blue-600 text-white text-center font-bold py-2 px-4 rounded transition duration-200 ease-in-out">163 unmodified lines</div></div></div><script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.js"></script><script>document.addEventListener("DOMContentLoaded", function () {292 unmodified lines});</script></html>139 unmodified lines14014114214314414514614714814915015115215315415516 unmodified lines172173174175176177178179180181182183184158 unmodified lines343344345346347348349350351352353354355356357358359360361362363364365366367105 unmodified lines4734744754764774784794804814824834844854864874884894904913 unmodified lines495496497498499500501502503504505506163 unmodified lines670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722292 unmodified lines101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074139 unmodified lines}).then(data => {const contentDiv = document.getElementById('content');const teamNameDiv = `<div class="flex items-center"><input type="text" name="team_name" id="team_name" class="mt-1 mb-1 block me-2" value="${data.response.team_name}"><button id="updateTeamNameButton" type="button" class="confirm text-white bg-green-600 hover:bg-green-800 focus:ring-4 focus:outline-none focus:ring-green-300 font-medium rounded-lg text-sm inline-flex items-center px-5 py-2.5 text-center me-2">Update Team Name</button></div>`;// console.log(data.response.submissions);// contentDiv.innerHTML = marked.parse(data.response.submission_text) + data.response.submissions;if (data.response.submissions && data.response.submissions.length > 0 && data.response.error.length == 0) {// Start building the table HTMLlet tableHTML = teamNameDiv;tableHTML += '<table border="1"><tr><th>Datetime</th><th>Submission ID</th><th>Public Score</th><th>Submission Comment</th><th>Selected</th><th>Status</th></tr>';// Iterate over each submission and add it to the table16 unmodified linesdocument.getElementById('updateSelectedSubmissionsButton').addEventListener('click', function () {updateSelectedSubmissions();});} else {// Display message if there are no submissionscontentDiv.innerHTML = teamNameDiv + marked.parse(data.response.submission_text) + marked.parse(data.response.error);}document.getElementById('updateTeamNameButton').addEventListener('click', function () {updateTeamName();});articleLoadingSpinner.classList.add('hidden');}).catch(error => {158 unmodified linesfunction checkOAuth() {var url = "/login_status";makeApiRequest(url, function ({is_login, is_admin, is_registered}) {const registerRemoveStyle = ["pointer-events-none", "text-gray-400", "cursor-not-allowed"];const registerNewStyle = ["ext-gray-900", "hover:bg-gray-100"]if (is_login) {document.getElementById("loginButton").style.display = "none";document.getElementById("logoutButton").style.display = "block";} else {document.getElementById("loginButton").style.display = "block";document.getElementById("logoutButton").style.display = "none";}if (is_admin) {document.getElementById("admin").classList.remove("hidden");}if (is_registered) {document.getElementById("my_submissions").classList.remove(...registerRemoveStyle);document.getElementById("my_submissions").classList.add(...registerNewStyle);document.getElementById("new_submission").classList.remove(...registerRemoveStyle);document.getElementById("new_submission").classList.add(...registerNewStyle);} else {document.getElementById("logoutButton").style.display = "block";}});105 unmodified lines</li><li><a href="#" id="my_submissions"class="flex items-center w-full p-2 transition duration-75 rounded-lg pl-11 group pointer-events-none text-gray-400 cursor-not-allowed">Mysubmissions</a></li><li><a href="#" id="new_submission"class="flex items-center w-full p-2 transition duration-75 rounded-lg pl-11 group pointer-events-none text-gray-400 cursor-not-allowed">Newsubmission</a></li></ul></li><li><a href="#" id="admin"class="flex items-center p-2 text-gray-900 rounded-lg hover:bg-gray-100 group hidden"><svg class="flex-shrink-0 w-5 h-5 text-gray-500 transition duration-75 group-hover:text-gray-900"aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor"viewBox="0 0 24 24">3 unmodified lines<span class="flex-1 ms-3 whitespace-nowrap">Admin</span></a></li><li id="registerButton" style="display: none;"><a href="#"class="flex justify-center items-center bg-blue-400 hover:bg-blue-600 text-white text-center font-bold py-2 px-4 rounded transition duration-200 ease-in-out">Register</a></li><li id="loginButton" style="display: none;"><a href="/login/huggingface"class="flex justify-center items-center bg-blue-400 hover:bg-blue-600 text-white text-center font-bold py-2 px-4 rounded transition duration-200 ease-in-out">163 unmodified lines</div></div></div><div id="register-modal" tabindex="-1"class="hidden fixed inset-0 z-40 flex items-center justify-center w-full h-full bg-black bg-opacity-50"><div class="relative w-full max-w-xl p-4"><div class="relative bg-white rounded-lg shadow-2xl"><button type="button"class="absolute top-3 right-3 text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 inline-flex justify-center items-center"data-modal-hide="register-modal"><svg class="w-4 h-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"viewBox="0 0 14 14"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6" /></svg><span class="sr-only">Close</span></button><div class="p-6 md:p-8 text-center"><form id="registerForm" class="max-w-md mx-auto p-6 bg-white rounded-lg shadow space-y-4"><div class="grid grid-cols-3 items-center gap-4"><label for="teamname" class="text-sm font-medium text-gray-700 text-right">Team Name</label><input type="text" id="teamname" name="teamname"class="col-span-2 px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"></div><div class="grid grid-cols-3 items-center gap-4"><label for="reigsterFile" class="text-sm font-medium text-gray-700 text-right">Team Datas</label><input type="file" id="reigsterFile" name="reigsterFile"class="col-span-2 text-sm text-gray-500 file:mr-4 file:py-2 file:px-4file:rounded-md file:border-0file:text-sm file:font-semiboldfile:bg-blue-50 file:text-blue-700hover:file:bg-blue-100"></div><p class="mt-1 text-xs text-gray-500">Please upload a .xlsx file with the following format: <br><a href="/register_template_file" download class="text-blue-600 hover:underline">Download here</a>.</p><p id="errorMessage" class="text-red-600 text-sm hidden"></p><button type="submit"id="submitRegisterButton"class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition disabled:bg-blue-800 disabled:opacity-80 disabled:cursor-not-allowed">Submit</button></form></div></div></div></div><script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.js"></script><script>document.addEventListener("DOMContentLoaded", function () {292 unmodified lines});</script><script>document.getElementById("registerButton").addEventListener("click", function () {document.getElementById("register-modal").classList.remove("hidden");});document.querySelector("[data-modal-hide='register-modal']").addEventListener("click", function () {document.getElementById("register-modal").classList.add("hidden");});document.getElementById('registerForm').addEventListener('submit', function (e) {e.preventDefault();const teamname = document.getElementById('teamname').value.trim();const fileInput = document.getElementById('reigsterFile');const file = fileInput.files[0];const errorMessage = document.getElementById('errorMessage');const submitBtn = document.getElementById('submitRegisterButton');submitBtn.disabled = true;submitBtn.textContent = 'Submiting...';errorMessage.textContent = '';errorMessage.classList.add('hidden');if (!teamname) {errorMessage.textContent = 'Team name is required.';errorMessage.classList.remove('hidden');return;}if (!file) {errorMessage.textContent = 'Please upload a file.';errorMessage.classList.remove('hidden');return;}const formData = new FormData();formData.append('teamname', teamname);formData.append('file', file);fetch('/register', { method: 'POST', body: formData }).then(response => response.json()).then(data => {if (data.success) {document.getElementById('register-modal').classList.add("hidden");window.location.reload();} else {submitBtn.disabled = false;submitBtn.textContent = 'Submit';errorMessage.textContent = data.response || 'An error occurred.';errorMessage.classList.remove('hidden');}})});</script></html>
3 unmodified lines4567891011121314301 unmodified lines3163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863 unmodified linesimport shleximport subprocessimport tracebackimport requestsfrom fastapi import Requestfrom huggingface_hub import HfApi, hf_hub_downloadfrom loguru import loggerfrom competitions.enums import SubmissionStatusfrom competitions.params import EvalParams301 unmodified linesreturn Falsedef get_team_name(user_token, competition_id, hf_token):user_info = token_information(token=user_token)user_id = user_info["id"]user_team = hf_hub_download(repo_id=competition_id,filename="user_team.json",token=hf_token,repo_type="dataset",)with open(user_team, "r", encoding="utf-8") as f:user_team = json.load(f)if user_id not in user_team:return Noneteam_id = user_team[user_id]team_metadata = hf_hub_download(repo_id=competition_id,filename="teams.json",token=hf_token,repo_type="dataset",)with open(team_metadata, "r", encoding="utf-8") as f:team_metadata = json.load(f)team_name = team_metadata[team_id]["name"]return team_namedef update_team_name(user_token, new_team_name, competition_id, hf_token):user_info = token_information(token=user_token)user_id = user_info["id"]user_team = hf_hub_download(repo_id=competition_id,filename="user_team.json",token=hf_token,repo_type="dataset",)with open(user_team, "r", encoding="utf-8") as f:user_team = json.load(f)if user_id not in user_team:raise Exception("User is not part of a team")team_id = user_team[user_id]team_metadata = hf_hub_download(repo_id=competition_id,filename="teams.json",token=hf_token,repo_type="dataset",)with open(team_metadata, "r", encoding="utf-8") as f:team_metadata = json.load(f)team_metadata[team_id]["name"] = new_team_nameteam_metadata_json = json.dumps(team_metadata, indent=4)team_metadata_json_bytes = team_metadata_json.encode("utf-8")team_metadata_json_buffer = io.BytesIO(team_metadata_json_bytes)api = HfApi(token=hf_token)api.upload_file(path_or_fileobj=team_metadata_json_buffer,path_in_repo="teams.json",repo_id=competition_id,repo_type="dataset",)return new_team_name3 unmodified lines45678910111213141516171819301 unmodified lines3213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225233 unmodified linesimport shleximport subprocessimport tracebackimport threadingimport uuidimport base64from typing import Optional, Dict, Anyimport requestsfrom fastapi import Requestfrom huggingface_hub import HfApi, hf_hub_downloadfrom loguru import loggerfrom cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom competitions.enums import SubmissionStatusfrom competitions.params import EvalParams301 unmodified linesreturn Falseclass TeamAlreadyExistsError(Exception):"""Custom exception for when a team already exists."""passclass TeamFileApi:def __init__(self, hf_token: str, competition_id: str):self.hf_token = hf_tokenself.competition_id = competition_idself._lock = threading.Lock()def _get_team_info(self, user_id: str) -> Optional[Dict[str, Any]]:user_team = hf_hub_download(repo_id=self.competition_id,filename="user_team.json",token=self.hf_token,repo_type="dataset",)with open(user_team, "r", encoding="utf-8") as f:user_team = json.load(f)if user_id not in user_team:return Noneteam_id = user_team[user_id]team_metadata = hf_hub_download(repo_id=self.competition_id,filename="teams.json",token=self.hf_token,repo_type="dataset",)with open(team_metadata, "r", encoding="utf-8") as f:team_metadata = json.load(f)return team_metadata[team_id]def _create_team(self, user_id: str, team_name: str, team_file: Optional[io.BytesIO]) -> str:with self._lock:user_team = hf_hub_download(repo_id=self.competition_id,filename="user_team.json",token=self.hf_token,repo_type="dataset",)with open(user_team, "r", encoding="utf-8") as f:user_team = json.load(f)team_metadata = hf_hub_download(repo_id=self.competition_id,filename="teams.json",token=self.hf_token,repo_type="dataset",)with open(team_metadata, "r", encoding="utf-8") as f:team_metadata = json.load(f)# create a new team, if user is not in any teamteam_id = str(uuid.uuid4())user_team[user_id] = team_idteam_metadata[team_id] = {"id": team_id,"name": team_name,"members": [user_id],"leader": user_id,}user_team_json = json.dumps(user_team, indent=4)user_team_json_bytes = user_team_json.encode("utf-8")user_team_json_buffer = io.BytesIO(user_team_json_bytes)team_metadata_json = json.dumps(team_metadata, indent=4)team_metadata_json_bytes = team_metadata_json.encode("utf-8")team_metadata_json_buffer = io.BytesIO(team_metadata_json_bytes)api = HfApi(token=self.hf_token)api.upload_file(path_or_fileobj=user_team_json_buffer,path_in_repo="user_team.json",repo_id=self.competition_id,repo_type="dataset",)api.upload_file(path_or_fileobj=team_metadata_json_buffer,path_in_repo="teams.json",repo_id=self.competition_id,repo_type="dataset",)if team_file is not None:resp = api.upload_file(path_or_fileobj=team_file,path_in_repo=f"team_datas/{team_id}.xlsx",repo_id=self.competition_id,repo_type="dataset",)return team_iddef create_team(self, user_token: str, team_name: str, team_file: io.BytesIO) -> str:user_info = token_information(token=user_token)return self._create_team(user_info["id"], team_name, team_file)def get_team_info(self, user_token: str) -> Optional[Dict[str, Any]]:user_info = token_information(token=user_token)return self._get_team_info(user_info["id"])def update_and_create_team_name(self, user_token, new_team_name):user_info = token_information(token=user_token)user_id = user_info["id"]team_info = self._get_team_info(user_id)if team_info is None:self._create_team(user_id, new_team_name)return new_team_namewith self._lock:team_metadata = hf_hub_download(repo_id=self.competition_id,filename="teams.json",token=self.hf_token,repo_type="dataset",)with open(team_metadata, "r", encoding="utf-8") as f:team_metadata = json.load(f)team_metadata[team_info["id"]]["name"] = new_team_nameteam_metadata_json = json.dumps(team_metadata, indent=4)team_metadata_json_bytes = team_metadata_json.encode("utf-8")team_metadata_json_buffer = io.BytesIO(team_metadata_json_bytes)api = HfApi(token=self.hf_token)api.upload_file(path_or_fileobj=team_metadata_json_buffer,path_in_repo="teams.json",repo_id=self.competition_id,repo_type="dataset",)return new_team_nameteam_file_api = TeamFileApi(os.environ.get("HF_TOKEN", None),os.environ.get("COMPETITION_ID"),)class UserTokenApi:def __init__(self, hf_token: str, key_base64: str, competition_id: str):self.hf_token = hf_tokenself.key = base64.b64decode(key_base64)self.competition_id = competition_iddef _encrypt(self, text: str) -> str:aesgcm = AESGCM(self.key)nonce = os.urandom(12)encrypted_data = aesgcm.encrypt(nonce, text.encode(), None)return base64.b64encode(nonce + encrypted_data).decode()def _decrypt(self, encrypted_text: str) -> str:aesgcm = AESGCM(self.key)data = base64.b64decode(encrypted_text)nonce = data[:12]ciphertext = data[12:]plaintext = aesgcm.decrypt(nonce, ciphertext, None)return plaintext.decode()def put(self, team_id: str, user_token: str):encrypted_token = self._encrypt(user_token)api = HfApi(token=self.hf_token)api.upload_file(path_or_fileobj=io.BytesIO(encrypted_token.encode()),path_in_repo=f"team_user_tokens/{team_id}",repo_id=self.competition_id,repo_type="dataset",)def get(self, team_id: str) -> Optional[str]:try:user_token = hf_hub_download(repo_id=self.competition_id,filename=f"team_user_tokens/{team_id}",token=self.hf_token,repo_type="dataset",)except Exception as e:logger.error(f"Failed to download user token - {e}")return Nonewith open(user_token, "r", encoding="utf-8") as f:encrypted_token = f.read()return self._decrypt(encrypted_token)user_token_api = UserTokenApi(os.environ.get("HF_TOKEN", None),os.environ.get("USER_TOKEN_KEY_BASE64"),os.environ.get("COMPETITION_ID"))
competitions/app.py+57-19
competitions/runner.py+27-8
competitions/static/Competition Participants Information Collection Template.xlsxAdded
competitions/submissions.py+47-115
competitions/templates/index.html+139-16
competitions/utils.py+196-59