Spaces:
Running
Running
Commit
·
7be4d47
1
Parent(s):
2f08ce9
update nav
Browse files- .gitattributes +2 -1
- .gitignore +1 -0
- Dockerfile +1 -1
- README.md +1 -1
- competitions/app.py +3 -22
- competitions/runner.py +160 -161
- competitions/submissions.py +3 -35
- competitions/templates/index.html +4 -5
- competitions/utils.py +5 -317
- download_pre_datas.py +10 -0
- requirements.txt +5 -0
.gitattributes
CHANGED
|
@@ -32,4 +32,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 32 |
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 32 |
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
CHANGED
|
@@ -151,3 +151,4 @@ dmypy.json
|
|
| 151 |
|
| 152 |
# lock
|
| 153 |
submission_lock/*
|
|
|
|
|
|
| 151 |
|
| 152 |
# lock
|
| 153 |
submission_lock/*
|
| 154 |
+
test_gt_datas
|
Dockerfile
CHANGED
|
@@ -50,4 +50,4 @@ COPY --chown=1000:1000 . /app/
|
|
| 50 |
|
| 51 |
RUN pip install -r requirements.txt
|
| 52 |
|
| 53 |
-
CMD ["
|
|
|
|
| 50 |
|
| 51 |
RUN pip install -r requirements.txt
|
| 52 |
|
| 53 |
+
CMD ["bash", "-c", "python download_pre_datas.py && python -m uvicorn competitions.app:app --workers 1 --port 7860 --host 0.0.0.0"]
|
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
emoji: 🏃
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: pink
|
|
|
|
| 1 |
---
|
| 2 |
+
title: ICCV2025-RealADSim-NVS Competition
|
| 3 |
emoji: 🏃
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: pink
|
competitions/app.py
CHANGED
|
@@ -27,8 +27,8 @@ from competitions.oauth import attach_oauth
|
|
| 27 |
from competitions.runner import JobRunner
|
| 28 |
from competitions.submissions import Submissions
|
| 29 |
from competitions.text import SUBMISSION_SELECTION_TEXT, SUBMISSION_TEXT
|
| 30 |
-
from competitions.utils import team_file_api, submission_api, leaderboard_api
|
| 31 |
-
from competitions.enums import SubmissionStatus
|
| 32 |
|
| 33 |
|
| 34 |
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
|
@@ -294,10 +294,7 @@ def my_submissions(request: Request, user_token: str = Depends(utils.user_authen
|
|
| 294 |
team_name = team_info["name"]
|
| 295 |
|
| 296 |
for sub in subs:
|
| 297 |
-
|
| 298 |
-
sub["log_file_url"] = "/error_log?" + urlencode({"token": error_log_api.generate_log_token(sub["submission_id"])})
|
| 299 |
-
else:
|
| 300 |
-
sub["log_file_url"] = ""
|
| 301 |
|
| 302 |
resp = {
|
| 303 |
"response": {
|
|
@@ -523,22 +520,6 @@ def register(
|
|
| 523 |
return {"success": True, "response": "Team created successfully."}
|
| 524 |
|
| 525 |
|
| 526 |
-
@app.get("/error_log")
|
| 527 |
-
def get_error_log(token: str = Query(..., description="Token to access the error log file.")):
|
| 528 |
-
try:
|
| 529 |
-
log_content = error_log_api.get_log_by_token(token)
|
| 530 |
-
log_file = io.BytesIO(log_content.encode('utf-8'))
|
| 531 |
-
log_file.seek(0)
|
| 532 |
-
return StreamingResponse(
|
| 533 |
-
log_file,
|
| 534 |
-
media_type="text/plain",
|
| 535 |
-
headers={"Content-Disposition": "attachment; filename=error_log.txt"}
|
| 536 |
-
)
|
| 537 |
-
except Exception as e:
|
| 538 |
-
logger.error(f"Error while fetching log file: {e}")
|
| 539 |
-
raise HTTPException(status_code=500, detail="Internal server error.")
|
| 540 |
-
|
| 541 |
-
|
| 542 |
@app.get("/register_page", response_class=HTMLResponse)
|
| 543 |
def register_page(request: Request):
|
| 544 |
"""
|
|
|
|
| 27 |
from competitions.runner import JobRunner
|
| 28 |
from competitions.submissions import Submissions
|
| 29 |
from competitions.text import SUBMISSION_SELECTION_TEXT, SUBMISSION_TEXT
|
| 30 |
+
from competitions.utils import team_file_api, submission_api, leaderboard_api
|
| 31 |
+
from competitions.enums import SubmissionStatus
|
| 32 |
|
| 33 |
|
| 34 |
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
|
|
|
| 294 |
team_name = team_info["name"]
|
| 295 |
|
| 296 |
for sub in subs:
|
| 297 |
+
sub.pop("final_score", "")
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
resp = {
|
| 300 |
"response": {
|
|
|
|
| 520 |
return {"success": True, "response": "Team created successfully."}
|
| 521 |
|
| 522 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
@app.get("/register_page", response_class=HTMLResponse)
|
| 524 |
def register_page(request: Request):
|
| 525 |
"""
|
competitions/runner.py
CHANGED
|
@@ -1,21 +1,48 @@
|
|
| 1 |
-
import glob
|
| 2 |
-
import io
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
import time
|
| 6 |
-
import
|
| 7 |
import shutil
|
|
|
|
|
|
|
| 8 |
from dataclasses import dataclass
|
| 9 |
from typing import List, Dict, Any
|
| 10 |
-
from collections import defaultdict
|
| 11 |
|
|
|
|
| 12 |
import pandas as pd
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
from loguru import logger
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
from competitions.enums import SubmissionStatus
|
| 17 |
from competitions.info import CompetitionInfo
|
| 18 |
-
from competitions.utils import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
@dataclass
|
|
@@ -57,8 +84,6 @@ class JobRunner:
|
|
| 57 |
"datetime": sub["datetime"],
|
| 58 |
"status": sub["status"],
|
| 59 |
"submission_repo": sub["submission_repo"],
|
| 60 |
-
"space_id": sub["space_id"],
|
| 61 |
-
"server_url": sub["server_url"],
|
| 62 |
"hardware": sub["hardware"],
|
| 63 |
}
|
| 64 |
)
|
|
@@ -78,187 +103,161 @@ class JobRunner:
|
|
| 78 |
pending_submissions = pending_submissions.sort_values("datetime")
|
| 79 |
pending_submissions = pending_submissions.reset_index(drop=True)
|
| 80 |
return pending_submissions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
def
|
| 83 |
-
|
| 84 |
-
for
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
filename=f"submission_info/{team_id}.json",
|
| 93 |
-
token=self.token,
|
| 94 |
-
repo_type="dataset",
|
| 95 |
-
)
|
| 96 |
-
with open(team_fname, "r", encoding="utf-8") as f:
|
| 97 |
-
team_submission_info = json.load(f)
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
|
| 105 |
-
team_submission_info_json_bytes = team_submission_info_json.encode("utf-8")
|
| 106 |
-
team_submission_info_json_buffer = io.BytesIO(team_submission_info_json_bytes)
|
| 107 |
api = HfApi(token=self.token)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
api.upload_file(
|
| 109 |
-
path_or_fileobj=
|
| 110 |
-
path_in_repo=f"
|
| 111 |
repo_id=self.competition_id,
|
| 112 |
repo_type="dataset",
|
| 113 |
)
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
| 121 |
)
|
| 122 |
-
with open(team_fname, "r", encoding="utf-8") as f:
|
| 123 |
-
team_submission_info = json.load(f)
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
| 133 |
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
)
|
| 141 |
|
| 142 |
-
|
| 143 |
-
_readme = "---\n"
|
| 144 |
-
_readme += f"title: {project_name}\n"
|
| 145 |
-
_readme += "emoji: 🚀\n"
|
| 146 |
-
_readme += "colorFrom: green\n"
|
| 147 |
-
_readme += "colorTo: indigo\n"
|
| 148 |
-
_readme += "sdk: docker\n"
|
| 149 |
-
_readme += "pinned: false\n"
|
| 150 |
-
_readme += "---\n"
|
| 151 |
-
return _readme
|
| 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 |
-
repo_type="dataset",
|
| 181 |
-
)
|
| 182 |
-
api.create_repo(
|
| 183 |
-
repo_id=space_id,
|
| 184 |
-
repo_type="space",
|
| 185 |
-
space_sdk="docker",
|
| 186 |
-
space_hardware=hardware,
|
| 187 |
-
private=True,
|
| 188 |
-
)
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
token=user_token,
|
| 199 |
-
local_dir=client_code_local_dir,
|
| 200 |
-
allow_patterns=["*"],
|
| 201 |
-
)
|
| 202 |
-
with open(f"{client_code_local_dir}/README.md", "w", encoding="utf-8") as f:
|
| 203 |
-
f.write(self._create_readme(space_id))
|
| 204 |
-
shutil.copyfile("./other_files/network_filter.so", os.path.join(client_code_local_dir, "network_filter.so"))
|
| 205 |
-
for filename in os.listdir(client_code_local_dir):
|
| 206 |
-
if filename.lower() == "dockerfile":
|
| 207 |
-
filepath = os.path.join(client_code_local_dir, filename)
|
| 208 |
-
with open(filepath, "r", encoding="utf-8") as f:
|
| 209 |
-
dockerfile_content = f.read()
|
| 210 |
-
with open(filepath, "w", encoding="utf-8") as f:
|
| 211 |
-
f.write(dockerfile_modifier.modify_dockerfile_content(dockerfile_content)[0])
|
| 212 |
-
try:
|
| 213 |
-
api.upload_folder(
|
| 214 |
-
repo_id=space_id,
|
| 215 |
-
repo_type="space",
|
| 216 |
-
folder_path=client_code_local_dir,
|
| 217 |
-
)
|
| 218 |
-
finally:
|
| 219 |
-
shutil.rmtree(client_code_local_dir, ignore_errors=True)
|
| 220 |
-
self._queue_submission(team_id, submission_id)
|
| 221 |
|
| 222 |
def run(self):
|
| 223 |
-
cur = 0
|
| 224 |
while True:
|
| 225 |
time.sleep(5)
|
| 226 |
-
if cur == 10000:
|
| 227 |
-
cur = 0
|
| 228 |
-
cur += 1
|
| 229 |
-
all_submissions = self._get_all_submissions()
|
| 230 |
-
|
| 231 |
-
# Clean up spaces every 100 iterations
|
| 232 |
-
if cur % 100 == 1:
|
| 233 |
-
logger.info("Cleaning up spaces...")
|
| 234 |
-
for space in all_submissions:
|
| 235 |
-
if space["status"] in {SubmissionStatus.QUEUED.value, SubmissionStatus.PROCESSING.value}:
|
| 236 |
-
logger.info(f"Cleaning up space {space['space_id']} for submission {space['submission_id']}")
|
| 237 |
-
space_cleaner.clean_space(
|
| 238 |
-
space["space_id"],
|
| 239 |
-
space["team_id"],
|
| 240 |
-
space["submission_id"],
|
| 241 |
-
)
|
| 242 |
|
|
|
|
| 243 |
pending_submissions = self._get_pending_subs(all_submissions)
|
| 244 |
if pending_submissions is None:
|
| 245 |
continue
|
| 246 |
first_pending_sub = pending_submissions.iloc[0]
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
|
|
|
| 251 |
try:
|
| 252 |
-
self.
|
| 253 |
except Exception as e:
|
| 254 |
logger.error(
|
| 255 |
-
f"Failed to
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
)
|
| 257 |
-
|
| 258 |
-
self.mark_submission_failed(first_pending_sub['team_id'], first_pending_sub['submission_id'], ErrorMessage.FAILED_TO_CREATE_SPACE.value)
|
| 259 |
-
try:
|
| 260 |
-
space_cleaner.delete_space(first_pending_sub["space_id"])
|
| 261 |
-
except Exception as e:
|
| 262 |
-
logger.error(f"Failed to delete space {first_pending_sub['space_id']}: {e}")
|
| 263 |
-
logger.error(f"Marked submission {first_pending_sub['submission_id']} as failed.")
|
| 264 |
continue
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import os
|
| 3 |
import time
|
| 4 |
+
import io
|
| 5 |
import shutil
|
| 6 |
+
from uuid import uuid4
|
| 7 |
+
import glob
|
| 8 |
from dataclasses import dataclass
|
| 9 |
from typing import List, Dict, Any
|
|
|
|
| 10 |
|
| 11 |
+
import torch
|
| 12 |
import pandas as pd
|
| 13 |
+
import lpips
|
| 14 |
+
import numpy as np
|
| 15 |
+
from huggingface_hub import HfApi, snapshot_download
|
| 16 |
from loguru import logger
|
| 17 |
+
from PIL import Image
|
| 18 |
+
from torchvision.transforms.functional import to_tensor
|
| 19 |
+
from torchmetrics.image import PeakSignalNoiseRatio, StructuralSimilarityIndexMeasure
|
| 20 |
|
| 21 |
+
from competitions.enums import SubmissionStatus
|
| 22 |
from competitions.info import CompetitionInfo
|
| 23 |
+
from competitions.utils import submission_api, user_token_api
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _psnr_mask(img1, img2, mask):
|
| 27 |
+
|
| 28 |
+
# Flatten mask
|
| 29 |
+
mask_flat = mask.reshape(-1)
|
| 30 |
+
img1_flat = img1.reshape(-1)
|
| 31 |
+
img2_flat = img2.reshape(-1)
|
| 32 |
+
|
| 33 |
+
# Non-zero indices
|
| 34 |
+
nonzero_indices = torch.nonzero(~mask_flat).squeeze()
|
| 35 |
+
|
| 36 |
+
# Only keep non-zero pixel
|
| 37 |
+
img1_nonzero = torch.index_select(img1_flat, 0, nonzero_indices)
|
| 38 |
+
img2_nonzero = torch.index_select(img2_flat, 0, nonzero_indices)
|
| 39 |
+
|
| 40 |
+
# MSE
|
| 41 |
+
mse = ((img1_nonzero - img2_nonzero) ** 2).mean()
|
| 42 |
+
|
| 43 |
+
# PSNR
|
| 44 |
+
psnr_value = 20 * torch.log10(1.0 / torch.sqrt(mse))
|
| 45 |
+
return psnr_value
|
| 46 |
|
| 47 |
|
| 48 |
@dataclass
|
|
|
|
| 84 |
"datetime": sub["datetime"],
|
| 85 |
"status": sub["status"],
|
| 86 |
"submission_repo": sub["submission_repo"],
|
|
|
|
|
|
|
| 87 |
"hardware": sub["hardware"],
|
| 88 |
}
|
| 89 |
)
|
|
|
|
| 103 |
pending_submissions = pending_submissions.sort_values("datetime")
|
| 104 |
pending_submissions = pending_submissions.reset_index(drop=True)
|
| 105 |
return pending_submissions
|
| 106 |
+
|
| 107 |
+
def _avg_score(self, score_list: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 108 |
+
psnr, ssim, lpips = [], [], []
|
| 109 |
+
for score in score_list:
|
| 110 |
+
psnr.append(score['psnr'])
|
| 111 |
+
ssim.append(score['ssim'])
|
| 112 |
+
lpips.append(score['lpips'])
|
| 113 |
+
return {'psnr': sum(psnr)/len(psnr), 'ssim': sum(ssim)/len(ssim), 'lpips': sum(lpips)/len(lpips)}
|
| 114 |
|
| 115 |
+
def _calculate_score(self, results: Dict[str, Any]) -> Dict[str, Any]:
|
| 116 |
+
all_scores, level1, level2, level3 = [], [], [], []
|
| 117 |
+
for im_name, scores in results.items():
|
| 118 |
+
all_scores.append(scores)
|
| 119 |
+
if "level1" in im_name:
|
| 120 |
+
level1.append(scores)
|
| 121 |
+
if "level2" in im_name:
|
| 122 |
+
level2.append(scores)
|
| 123 |
+
if "level3" in im_name:
|
| 124 |
+
level3.append(scores)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
return {
|
| 127 |
+
"all": self._avg_score(all_scores),
|
| 128 |
+
"level1": self._avg_score(level1),
|
| 129 |
+
"level2": self._avg_score(level2),
|
| 130 |
+
"level3": self._avg_score(level3),
|
| 131 |
+
}
|
| 132 |
|
| 133 |
+
def _process_submission(self, submission: Dict[str, Any]):
|
|
|
|
|
|
|
| 134 |
api = HfApi(token=self.token)
|
| 135 |
+
user_repo = submission["submission_repo"]
|
| 136 |
+
team_id = submission["team_id"]
|
| 137 |
+
submission_id = submission["submission_id"]
|
| 138 |
+
|
| 139 |
+
user_token = user_token_api.get(team_id)
|
| 140 |
+
client_commits = api.list_repo_commits(user_repo, repo_type="dataset")
|
| 141 |
+
client_code_local_dir = f"/tmp/data/client_repo/{uuid4().hex}"
|
| 142 |
+
try:
|
| 143 |
+
api.snapshot_download(
|
| 144 |
+
repo_id=user_repo,
|
| 145 |
+
repo_type="dataset",
|
| 146 |
+
revision=client_commits[0].commit_id,
|
| 147 |
+
token=user_token,
|
| 148 |
+
local_dir=client_code_local_dir,
|
| 149 |
+
allow_patterns=["*"],
|
| 150 |
+
)
|
| 151 |
+
evel_result = self._eval("./test_gt_datas", client_code_local_dir)
|
| 152 |
+
finally:
|
| 153 |
+
shutil.rmtree(client_code_local_dir, ignore_errors=True)
|
| 154 |
+
evel_result_json_string = json.dumps(evel_result, indent=2)
|
| 155 |
+
evel_result_json_bytes = evel_result_json_string.encode("utf-8")
|
| 156 |
+
evel_result_json_buffer = io.BytesIO(evel_result_json_bytes)
|
| 157 |
api.upload_file(
|
| 158 |
+
path_or_fileobj=evel_result_json_buffer,
|
| 159 |
+
path_in_repo=f"eval_results/{submission_id}.json",
|
| 160 |
repo_id=self.competition_id,
|
| 161 |
repo_type="dataset",
|
| 162 |
)
|
| 163 |
+
final_score = self._calculate_score(evel_result)
|
| 164 |
+
score = final_score["all"]["psnr"] * 0.4 + final_score["all"]["ssim"] * 0.3 - final_score["all"]["lpips"] * 0.3
|
| 165 |
+
submission_api.update_submission_data(
|
| 166 |
+
team_id=team_id,
|
| 167 |
+
submission_id=submission_id,
|
| 168 |
+
data={
|
| 169 |
+
"status": SubmissionStatus.SUCCESS.value,
|
| 170 |
+
"final_score": final_score,
|
| 171 |
+
"score": np.round(score, 3),
|
| 172 |
+
}
|
| 173 |
)
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
def _eval(self, gt_folder_path: str, test_folder_path: str) -> Dict[str, Any]:
|
| 176 |
+
# list all files
|
| 177 |
+
files1 = sorted(glob.glob(os.path.join(gt_folder_path, '*/*/images', "*")))
|
| 178 |
+
files2 = sorted(glob.glob(os.path.join(test_folder_path, '*/*/images', "*")))
|
| 179 |
|
| 180 |
+
# filter by extensions
|
| 181 |
+
image_extensions = ('.png', '.jpg', '.jpeg')
|
| 182 |
+
images1 = [os.path.relpath(f, gt_folder_path) for f in files1 if f.lower().endswith(image_extensions)]
|
| 183 |
+
images2 = [os.path.relpath(f, test_folder_path) for f in files2 if f.lower().endswith(image_extensions)]
|
| 184 |
|
| 185 |
+
# format check
|
| 186 |
+
if set(images1) != set(images2):
|
| 187 |
+
raise ValueError("Submission Format Error")
|
| 188 |
+
|
| 189 |
+
# metrics
|
| 190 |
+
ssim_metric = StructuralSimilarityIndexMeasure(data_range=1.0).to("cuda" if torch.cuda.is_available() else "cpu")
|
| 191 |
+
lpips_metric = lpips.LPIPS(net='alex').to("cuda" if torch.cuda.is_available() else "cpu")
|
| 192 |
|
| 193 |
+
results = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
+
for img_name in images1:
|
| 196 |
+
path1 = os.path.join(gt_folder_path, img_name)
|
| 197 |
+
path2 = os.path.join(test_folder_path, img_name)
|
| 198 |
|
| 199 |
+
try:
|
| 200 |
+
# load images
|
| 201 |
+
img1 = Image.open(path1).convert("RGB")
|
| 202 |
+
img2 = Image.open(path2).convert("RGB")
|
| 203 |
+
if os.path.exists(path1.replace('images', 'masks')):
|
| 204 |
+
dynamic_mask = Image.open(path1.replace('images', 'masks'))
|
| 205 |
+
else:
|
| 206 |
+
dynamic_mask = Image.open(path1.replace('images', 'masks').replace('.jpg', '.png'))
|
| 207 |
+
|
| 208 |
+
# to tensor
|
| 209 |
+
tensor1 = to_tensor(img1).unsqueeze(0)
|
| 210 |
+
tensor2 = to_tensor(img2).unsqueeze(0)
|
| 211 |
+
dynamic_mask = to_tensor(dynamic_mask).unsqueeze(0).bool()
|
| 212 |
+
dynamic_mask = dynamic_mask.expand(-1, 3, -1, -1)
|
| 213 |
+
tensor1[dynamic_mask] *= 0
|
| 214 |
+
tensor2[dynamic_mask] *= 0
|
| 215 |
|
| 216 |
+
# move to devices
|
| 217 |
+
tensor1 = tensor1.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 218 |
+
tensor2 = tensor2.to("cuda" if torch.cuda.is_available() else "cpu")
|
| 219 |
|
| 220 |
+
# metrics
|
| 221 |
+
psnr_val = _psnr_mask(tensor1, tensor2, dynamic_mask).item()
|
| 222 |
+
ssim_val = ssim_metric(tensor1, tensor2).item()
|
| 223 |
+
lpips_val = lpips_metric(tensor1 * 2 - 1, tensor2 * 2 - 1).item()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
+
results[img_name] = {
|
| 226 |
+
"psnr": psnr_val,
|
| 227 |
+
"ssim": ssim_val,
|
| 228 |
+
"lpips": lpips_val
|
| 229 |
+
}
|
| 230 |
+
except Exception:
|
| 231 |
+
raise RuntimeError
|
| 232 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
def run(self):
|
|
|
|
| 235 |
while True:
|
| 236 |
time.sleep(5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
+
all_submissions = self._get_all_submissions()
|
| 239 |
pending_submissions = self._get_pending_subs(all_submissions)
|
| 240 |
if pending_submissions is None:
|
| 241 |
continue
|
| 242 |
first_pending_sub = pending_submissions.iloc[0]
|
| 243 |
+
submission_api.update_submission_status(
|
| 244 |
+
team_id=first_pending_sub['team_id'],
|
| 245 |
+
submission_id=first_pending_sub['submission_id'],
|
| 246 |
+
status=SubmissionStatus.PROCESSING.value,
|
| 247 |
+
)
|
| 248 |
try:
|
| 249 |
+
self._process_submission(first_pending_sub)
|
| 250 |
except Exception as e:
|
| 251 |
logger.error(
|
| 252 |
+
f"Failed to process {first_pending_sub['submission_id']}: {e}"
|
| 253 |
+
)
|
| 254 |
+
submission_api.update_submission_data(
|
| 255 |
+
team_id=first_pending_sub['team_id'],
|
| 256 |
+
submission_id=first_pending_sub['submission_id'],
|
| 257 |
+
data={
|
| 258 |
+
"status": SubmissionStatus.FAILED.value,
|
| 259 |
+
"error_message": str(e)
|
| 260 |
+
}
|
| 261 |
)
|
| 262 |
+
raise e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
continue
|
competitions/submissions.py
CHANGED
|
@@ -5,12 +5,12 @@ from dataclasses import dataclass
|
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
import pandas as pd
|
| 8 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 9 |
from huggingface_hub.utils._errors import EntryNotFoundError
|
| 10 |
|
| 11 |
from competitions.enums import SubmissionStatus
|
| 12 |
from competitions.errors import AuthenticationError, PastDeadlineError, SubmissionError, SubmissionLimitError
|
| 13 |
-
from competitions.utils import token_information, team_file_api, user_token_api
|
| 14 |
|
| 15 |
|
| 16 |
@dataclass
|
|
@@ -57,12 +57,9 @@ class Submissions:
|
|
| 57 |
submission_id,
|
| 58 |
submission_comment,
|
| 59 |
submission_repo=None,
|
| 60 |
-
space_id=None,
|
| 61 |
):
|
| 62 |
if submission_repo is None:
|
| 63 |
submission_repo = ""
|
| 64 |
-
if space_id is None:
|
| 65 |
-
space_id = ""
|
| 66 |
team_fname = hf_hub_download(
|
| 67 |
repo_id=self.competition_id,
|
| 68 |
filename=f"submission_info/{team_id}.json",
|
|
@@ -80,15 +77,13 @@ class Submissions:
|
|
| 80 |
"submission_id": submission_id,
|
| 81 |
"submission_comment": submission_comment,
|
| 82 |
"submission_repo": submission_repo,
|
| 83 |
-
"space_id": space_id,
|
| 84 |
"submitted_by": user_id,
|
| 85 |
"status": SubmissionStatus.PENDING.value,
|
| 86 |
"selected": False,
|
| 87 |
"public_score": {},
|
| 88 |
"private_score": {},
|
| 89 |
-
"score":
|
| 90 |
"error_message": "",
|
| 91 |
-
"server_url": server_manager.get_next_server(),
|
| 92 |
"hardware": self.hardware,
|
| 93 |
}
|
| 94 |
)
|
|
@@ -155,7 +150,6 @@ class Submissions:
|
|
| 155 |
|
| 156 |
# stringify public_score column
|
| 157 |
submissions_df["public_score"] = submissions_df["public_score"].apply(json.dumps)
|
| 158 |
-
submissions_df["score"] = submissions_df["score"].apply(json.dumps)
|
| 159 |
|
| 160 |
if private:
|
| 161 |
submissions_df["private_score"] = submissions_df["private_score"].apply(json.dumps)
|
|
@@ -220,33 +214,8 @@ class Submissions:
|
|
| 220 |
if self._is_submission_allowed(team_id) is False:
|
| 221 |
raise SubmissionLimitError("Submission limit reached")
|
| 222 |
|
| 223 |
-
if self.competition_type == "generic":
|
| 224 |
-
bytes_data = uploaded_file.file.read()
|
| 225 |
-
# verify file is valid
|
| 226 |
-
if not self._verify_submission(bytes_data):
|
| 227 |
-
raise SubmissionError("Invalid submission file")
|
| 228 |
-
|
| 229 |
-
file_extension = uploaded_file.filename.split(".")[-1]
|
| 230 |
-
# upload file to hf hub
|
| 231 |
-
api = HfApi(token=self.token)
|
| 232 |
-
api.upload_file(
|
| 233 |
-
path_or_fileobj=bytes_data,
|
| 234 |
-
path_in_repo=f"submissions/{team_id}-{submission_id}.{file_extension}",
|
| 235 |
-
repo_id=self.competition_id,
|
| 236 |
-
repo_type="dataset",
|
| 237 |
-
)
|
| 238 |
-
submissions_made = self._increment_submissions(
|
| 239 |
-
team_id=team_id,
|
| 240 |
-
user_id=user_id,
|
| 241 |
-
submission_id=submission_id,
|
| 242 |
-
submission_comment=submission_comment,
|
| 243 |
-
)
|
| 244 |
-
return self.submission_limit - submissions_made
|
| 245 |
-
|
| 246 |
user_api = HfApi(token=user_token)
|
| 247 |
submission_id = user_api.model_info(repo_id=uploaded_file).sha + "__" + submission_id
|
| 248 |
-
competition_organizer = self.competition_id.split("/")[0]
|
| 249 |
-
space_id = f"{competition_organizer}/comp-{submission_id}"
|
| 250 |
|
| 251 |
user_token_api.put(team_id, user_token)
|
| 252 |
submissions_made = self._increment_submissions(
|
|
@@ -255,7 +224,6 @@ class Submissions:
|
|
| 255 |
submission_id=submission_id,
|
| 256 |
submission_comment=submission_comment,
|
| 257 |
submission_repo=uploaded_file,
|
| 258 |
-
space_id=space_id,
|
| 259 |
)
|
| 260 |
remaining_submissions = self.submission_limit - submissions_made
|
| 261 |
return remaining_submissions
|
|
|
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
import pandas as pd
|
| 8 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 9 |
from huggingface_hub.utils._errors import EntryNotFoundError
|
| 10 |
|
| 11 |
from competitions.enums import SubmissionStatus
|
| 12 |
from competitions.errors import AuthenticationError, PastDeadlineError, SubmissionError, SubmissionLimitError
|
| 13 |
+
from competitions.utils import token_information, team_file_api, user_token_api
|
| 14 |
|
| 15 |
|
| 16 |
@dataclass
|
|
|
|
| 57 |
submission_id,
|
| 58 |
submission_comment,
|
| 59 |
submission_repo=None,
|
|
|
|
| 60 |
):
|
| 61 |
if submission_repo is None:
|
| 62 |
submission_repo = ""
|
|
|
|
|
|
|
| 63 |
team_fname = hf_hub_download(
|
| 64 |
repo_id=self.competition_id,
|
| 65 |
filename=f"submission_info/{team_id}.json",
|
|
|
|
| 77 |
"submission_id": submission_id,
|
| 78 |
"submission_comment": submission_comment,
|
| 79 |
"submission_repo": submission_repo,
|
|
|
|
| 80 |
"submitted_by": user_id,
|
| 81 |
"status": SubmissionStatus.PENDING.value,
|
| 82 |
"selected": False,
|
| 83 |
"public_score": {},
|
| 84 |
"private_score": {},
|
| 85 |
+
"score": 0,
|
| 86 |
"error_message": "",
|
|
|
|
| 87 |
"hardware": self.hardware,
|
| 88 |
}
|
| 89 |
)
|
|
|
|
| 150 |
|
| 151 |
# stringify public_score column
|
| 152 |
submissions_df["public_score"] = submissions_df["public_score"].apply(json.dumps)
|
|
|
|
| 153 |
|
| 154 |
if private:
|
| 155 |
submissions_df["private_score"] = submissions_df["private_score"].apply(json.dumps)
|
|
|
|
| 214 |
if self._is_submission_allowed(team_id) is False:
|
| 215 |
raise SubmissionLimitError("Submission limit reached")
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
user_api = HfApi(token=user_token)
|
| 218 |
submission_id = user_api.model_info(repo_id=uploaded_file).sha + "__" + submission_id
|
|
|
|
|
|
|
| 219 |
|
| 220 |
user_token_api.put(team_id, user_token)
|
| 221 |
submissions_made = self._increment_submissions(
|
|
|
|
| 224 |
submission_id=submission_id,
|
| 225 |
submission_comment=submission_comment,
|
| 226 |
submission_repo=uploaded_file,
|
|
|
|
| 227 |
)
|
| 228 |
remaining_submissions = self.submission_limit - submissions_made
|
| 229 |
return remaining_submissions
|
competitions/templates/index.html
CHANGED
|
@@ -150,17 +150,16 @@
|
|
| 150 |
if (data.response.submissions && data.response.submissions.length > 0 && data.response.error.length == 0) {
|
| 151 |
// Start building the table HTML
|
| 152 |
let tableHTML = teamNameDiv;
|
| 153 |
-
tableHTML += '<table border="1"><tr><th width: 17%;>Datetime</th><th style="width: 40%;">Submission ID</th><th style="width: 20%;">Score</th><th style="width: 8%;">Status</th><th style="width: 15%;">Error
|
| 154 |
|
| 155 |
// Iterate over each submission and add it to the table
|
| 156 |
data.response.submissions.forEach(submission => {
|
| 157 |
-
logFileLink = submission.log_file_url === "" ? "" : `<a href="${submission.log_file_url}" target="_blank">log_file.txt</a>`;
|
| 158 |
tableHTML += `<tr>
|
| 159 |
<td>${submission.datetime}</td>
|
| 160 |
<td>${submission.submission_id}</td>
|
| 161 |
<td>${submission.score}</td>
|
| 162 |
<td>${submission.status}</td>
|
| 163 |
-
<td>${submission.error_message}
|
| 164 |
</tr>`;
|
| 165 |
});
|
| 166 |
|
|
@@ -580,7 +579,7 @@
|
|
| 580 |
{% endif %}
|
| 581 |
{% if competition_type == 'script' %}
|
| 582 |
<div class="form-group">
|
| 583 |
-
<label for="hub_model" class="text-sm font-medium text-gray-700">Hub
|
| 584 |
</label>
|
| 585 |
<input type="text" name="hub_model" id="hub_model"
|
| 586 |
class="mt-1 block w-full border border-gray-300 px-3 py-1.5 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
|
|
@@ -840,7 +839,7 @@
|
|
| 840 |
} else if (competitionType === 'script') {
|
| 841 |
var hubModel = document.getElementById('hub_model').value;
|
| 842 |
if (!hubModel) {
|
| 843 |
-
alert('Hub
|
| 844 |
return;
|
| 845 |
}
|
| 846 |
formData.append('hub_model', hubModel);
|
|
|
|
| 150 |
if (data.response.submissions && data.response.submissions.length > 0 && data.response.error.length == 0) {
|
| 151 |
// Start building the table HTML
|
| 152 |
let tableHTML = teamNameDiv;
|
| 153 |
+
tableHTML += '<table border="1"><tr><th width: 17%;>Datetime</th><th style="width: 40%;">Submission ID</th><th style="width: 20%;">Score</th><th style="width: 8%;">Status</th><th style="width: 15%;">Error</th></tr>';
|
| 154 |
|
| 155 |
// Iterate over each submission and add it to the table
|
| 156 |
data.response.submissions.forEach(submission => {
|
|
|
|
| 157 |
tableHTML += `<tr>
|
| 158 |
<td>${submission.datetime}</td>
|
| 159 |
<td>${submission.submission_id}</td>
|
| 160 |
<td>${submission.score}</td>
|
| 161 |
<td>${submission.status}</td>
|
| 162 |
+
<td>${submission.error_message}</td>
|
| 163 |
</tr>`;
|
| 164 |
});
|
| 165 |
|
|
|
|
| 579 |
{% endif %}
|
| 580 |
{% if competition_type == 'script' %}
|
| 581 |
<div class="form-group">
|
| 582 |
+
<label for="hub_model" class="text-sm font-medium text-gray-700">Hub Dataset
|
| 583 |
</label>
|
| 584 |
<input type="text" name="hub_model" id="hub_model"
|
| 585 |
class="mt-1 block w-full border border-gray-300 px-3 py-1.5 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
|
|
|
|
| 839 |
} else if (competitionType === 'script') {
|
| 840 |
var hubModel = document.getElementById('hub_model').value;
|
| 841 |
if (!hubModel) {
|
| 842 |
+
alert('Hub Dataset is required.');
|
| 843 |
return;
|
| 844 |
}
|
| 845 |
formData.append('hub_model', hubModel);
|
competitions/utils.py
CHANGED
|
@@ -3,7 +3,6 @@ import json
|
|
| 3 |
import os
|
| 4 |
import shlex
|
| 5 |
import subprocess
|
| 6 |
-
import re
|
| 7 |
import threading
|
| 8 |
import uuid
|
| 9 |
import base64
|
|
@@ -14,6 +13,7 @@ from datetime import datetime, timezone, timedelta
|
|
| 14 |
|
| 15 |
import requests
|
| 16 |
import pandas as pd
|
|
|
|
| 17 |
import jwt
|
| 18 |
from fastapi import Request
|
| 19 |
from huggingface_hub import HfApi, hf_hub_download
|
|
@@ -470,22 +470,6 @@ user_token_api = UserTokenApi(
|
|
| 470 |
)
|
| 471 |
|
| 472 |
|
| 473 |
-
class ServerManager:
|
| 474 |
-
def __init__(self, server_url_list: List[str]):
|
| 475 |
-
self.server_url_list = server_url_list
|
| 476 |
-
self._cur_index = 0
|
| 477 |
-
self._lock = threading.Lock()
|
| 478 |
-
|
| 479 |
-
def get_next_server(self) -> str:
|
| 480 |
-
with self._lock:
|
| 481 |
-
server_url = self.server_url_list[self._cur_index]
|
| 482 |
-
self._cur_index = (self._cur_index + 1) % len(self.server_url_list)
|
| 483 |
-
return server_url
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
server_manager = ServerManager(["https://xdimlab-hugsim-web-server-0.hf.space"])
|
| 487 |
-
|
| 488 |
-
|
| 489 |
class SubmissionApi:
|
| 490 |
def __init__(self, hf_token: str, competition_id: str):
|
| 491 |
self.hf_token = hf_token
|
|
@@ -558,141 +542,6 @@ submission_api = SubmissionApi(
|
|
| 558 |
)
|
| 559 |
|
| 560 |
|
| 561 |
-
class ErrorLogApi:
|
| 562 |
-
def __init__(self, hf_token: str, competition_id: str, encode_key: str):
|
| 563 |
-
self.hf_token = hf_token
|
| 564 |
-
self.competition_id = competition_id
|
| 565 |
-
self.api = HfApi(token=hf_token)
|
| 566 |
-
self.encode_key = encode_key
|
| 567 |
-
|
| 568 |
-
def save_error_log(self, submission_id: str, content: str):
|
| 569 |
-
"""Save the error log of a space to the submission."""
|
| 570 |
-
content_buffer = io.BytesIO(content.encode())
|
| 571 |
-
self.api.upload_file(
|
| 572 |
-
path_or_fileobj=content_buffer,
|
| 573 |
-
path_in_repo=f"error_logs/{submission_id}.txt",
|
| 574 |
-
repo_id=self.competition_id,
|
| 575 |
-
repo_type="dataset",
|
| 576 |
-
)
|
| 577 |
-
|
| 578 |
-
def get_log(self, space_id: str, kind: Literal["run", "build"], tail: int = -1) -> str:
|
| 579 |
-
"""Get the build log of a space."""
|
| 580 |
-
url = f"https://huggingface.co/api/spaces/{space_id}/logs/{kind}"
|
| 581 |
-
headers = {
|
| 582 |
-
"Authorization": f"Bearer {self.hf_token}"
|
| 583 |
-
}
|
| 584 |
-
response = requests.get(url, headers=headers)
|
| 585 |
-
if response.status_code != 200:
|
| 586 |
-
raise RuntimeError(f"Failed to get logs: {response.status_code}\n{response.text}")
|
| 587 |
-
content = response.text
|
| 588 |
-
line_str_list = []
|
| 589 |
-
start_index = 0 if tail == -1 else max(0, len(content.split('\n')) - tail)
|
| 590 |
-
for line in content.split('\n')[start_index:]:
|
| 591 |
-
if line.startswith("data:"):
|
| 592 |
-
line_json = json.loads(line[5:].strip())
|
| 593 |
-
line_str_list.append(f"{line_json['timestamp']}: {line_json['data']}")
|
| 594 |
-
return "\n".join(line_str_list)
|
| 595 |
-
|
| 596 |
-
def generate_log_token(self, submission_id: str) -> str:
|
| 597 |
-
payload = {
|
| 598 |
-
"submission_id": submission_id,
|
| 599 |
-
"exp": datetime.now(timezone.utc) + timedelta(hours=1)
|
| 600 |
-
}
|
| 601 |
-
token = jwt.encode(payload, self.encode_key, algorithm="HS256")
|
| 602 |
-
return token
|
| 603 |
-
|
| 604 |
-
def get_log_by_token(self, token: str) -> str:
|
| 605 |
-
try:
|
| 606 |
-
payload = jwt.decode(token, self.encode_key, algorithms=["HS256"])
|
| 607 |
-
submission_id = payload["submission_id"]
|
| 608 |
-
except jwt.ExpiredSignatureError:
|
| 609 |
-
raise RuntimeError("Token has expired.")
|
| 610 |
-
except jwt.InvalidTokenError as e:
|
| 611 |
-
raise RuntimeError(f"Invalid token: {e}")
|
| 612 |
-
|
| 613 |
-
log_file_path = self.api.hf_hub_download(
|
| 614 |
-
repo_id=self.competition_id,
|
| 615 |
-
filename=f"error_logs/{submission_id}.txt",
|
| 616 |
-
repo_type="dataset",
|
| 617 |
-
)
|
| 618 |
-
with open(log_file_path, 'r') as f:
|
| 619 |
-
file_content = f.read()
|
| 620 |
-
|
| 621 |
-
return file_content
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
error_log_api = ErrorLogApi(
|
| 625 |
-
hf_token=os.environ.get("HF_TOKEN", None),
|
| 626 |
-
competition_id=os.environ.get("COMPETITION_ID"),
|
| 627 |
-
encode_key=os.environ.get("ERROR_LOG_ENCODE_KEY", "key")
|
| 628 |
-
)
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
class SpaceCleaner:
|
| 632 |
-
def __init__(self, hf_token: str, competition_id: str):
|
| 633 |
-
self.hf_token = hf_token
|
| 634 |
-
self.competition_id = competition_id
|
| 635 |
-
self.api = HfApi(token=hf_token)
|
| 636 |
-
self.space_build_error_count = defaultdict(int)
|
| 637 |
-
|
| 638 |
-
def delete_space(self, space_id: str):
|
| 639 |
-
"""Delete a space by its ID."""
|
| 640 |
-
self.api.delete_repo(repo_id=space_id, repo_type="space")
|
| 641 |
-
|
| 642 |
-
def clean_space(self, space_id: str, team_id: str, submission_id: str):
|
| 643 |
-
try:
|
| 644 |
-
space_info = self.api.space_info(repo_id=space_id)
|
| 645 |
-
except RepositoryNotFoundError:
|
| 646 |
-
submission_api.update_submission_data(
|
| 647 |
-
team_id=team_id,
|
| 648 |
-
submission_id=submission_id,
|
| 649 |
-
data={"status": SubmissionStatus.FAILED.value, "error_message": ErrorMessage.START_SPACE_FAILED.value},
|
| 650 |
-
)
|
| 651 |
-
return
|
| 652 |
-
|
| 653 |
-
if (datetime.now(timezone.utc) - space_info.created_at).total_seconds() > 60 * 60 * 1.5:
|
| 654 |
-
# If the space is older than 1.5 hours, delete it
|
| 655 |
-
self.delete_space(space_id)
|
| 656 |
-
submission_api.update_submission_data(
|
| 657 |
-
team_id=team_id,
|
| 658 |
-
submission_id=submission_id,
|
| 659 |
-
data={"status": SubmissionStatus.FAILED.value, "error_message": ErrorMessage.SPACE_TIMEOUT.value},
|
| 660 |
-
)
|
| 661 |
-
return
|
| 662 |
-
|
| 663 |
-
if space_info.runtime.stage == SpaceStage.BUILD_ERROR:
|
| 664 |
-
self.space_build_error_count[space_id] += 1
|
| 665 |
-
if self.space_build_error_count[space_id] >= 3:
|
| 666 |
-
log_content = error_log_api.get_log(space_id, kind="build")
|
| 667 |
-
error_log_api.save_error_log(submission_id, log_content)
|
| 668 |
-
self.delete_space(space_id)
|
| 669 |
-
submission_api.update_submission_data(
|
| 670 |
-
team_id=team_id,
|
| 671 |
-
submission_id=submission_id,
|
| 672 |
-
data={"status": SubmissionStatus.FAILED.value, "error_message": ErrorMessage.BUILD_SPACE_FAILED.value},
|
| 673 |
-
)
|
| 674 |
-
else:
|
| 675 |
-
self.api.restart_space(repo_id=space_id)
|
| 676 |
-
return
|
| 677 |
-
|
| 678 |
-
if space_info.runtime.stage == SpaceStage.RUNTIME_ERROR:
|
| 679 |
-
log_content = error_log_api.get_log(space_id, kind="run")
|
| 680 |
-
error_log_api.save_error_log(submission_id, log_content)
|
| 681 |
-
self.delete_space(space_id)
|
| 682 |
-
submission_api.update_submission_data(
|
| 683 |
-
team_id=team_id,
|
| 684 |
-
submission_id=submission_id,
|
| 685 |
-
data={"status": SubmissionStatus.FAILED.value, "error_message": ErrorMessage.RUNTIME_ERROR.value},
|
| 686 |
-
)
|
| 687 |
-
return
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
space_cleaner = SpaceCleaner(
|
| 691 |
-
os.environ.get("HF_TOKEN", None),
|
| 692 |
-
os.environ.get("COMPETITION_ID")
|
| 693 |
-
)
|
| 694 |
-
|
| 695 |
-
|
| 696 |
class LeaderboardApi:
|
| 697 |
def __init__(self, hf_token: str, competition_id: str):
|
| 698 |
self.hf_token = hf_token
|
|
@@ -708,12 +557,12 @@ class LeaderboardApi:
|
|
| 708 |
"""
|
| 709 |
all_scores = self._get_all_scores()
|
| 710 |
if not all_scores:
|
| 711 |
-
return pd.DataFrame(columns=["team_id", "team_name", "
|
| 712 |
|
| 713 |
df = pd.DataFrame(all_scores)
|
| 714 |
-
df = df.sort_values(by=["
|
| 715 |
df = df.groupby("team_id").first()
|
| 716 |
-
df = df.sort_values(by=["
|
| 717 |
df['rank'] = range(1, len(df) + 1)
|
| 718 |
df.insert(0, 'rank', df.pop('rank'))
|
| 719 |
df.reset_index(drop=True, inplace=True)
|
|
@@ -745,8 +594,7 @@ class LeaderboardApi:
|
|
| 745 |
all_scores.append({
|
| 746 |
"team_id": team_id,
|
| 747 |
"team_name": team_metadata[team_id]["name"],
|
| 748 |
-
"
|
| 749 |
-
"hdscore": sub["score"]["hdscore"],
|
| 750 |
})
|
| 751 |
return all_scores
|
| 752 |
|
|
@@ -755,163 +603,3 @@ leaderboard_api = LeaderboardApi(
|
|
| 755 |
hf_token=os.environ.get("HF_TOKEN", None),
|
| 756 |
competition_id=os.environ.get("COMPETITION_ID")
|
| 757 |
)
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
class DockerfileModifier:
|
| 762 |
-
def __init__(self, allowed_hosts: str, source_so_path: str = "./network_filter.so"):
|
| 763 |
-
self.allowed_hosts = allowed_hosts
|
| 764 |
-
self.source_so_path = source_so_path
|
| 765 |
-
self.tatget_so_dir = "/_app_extensions"
|
| 766 |
-
self.tatget_so_path = os.path.join(self.tatget_so_dir, "network_filter.so")
|
| 767 |
-
self.preload_prefix = f'LD_PRELOAD={self.tatget_so_path} ALLOWED_HOSTS="{allowed_hosts}"'
|
| 768 |
-
|
| 769 |
-
def parse_dockerfile_line(self, line: str) -> Tuple[str, str, str]:
|
| 770 |
-
"""
|
| 771 |
-
解析 Dockerfile 行,返回 (指令名, 原始命令, 格式类型)
|
| 772 |
-
格式类型: 'exec' (JSON数组) 或 'shell' (shell命令)
|
| 773 |
-
"""
|
| 774 |
-
line = line.strip()
|
| 775 |
-
|
| 776 |
-
# 匹配 CMD 或 ENTRYPOINT
|
| 777 |
-
cmd_match = re.match(r'^(CMD|ENTRYPOINT)\s+(.+)$', line, re.IGNORECASE)
|
| 778 |
-
if not cmd_match:
|
| 779 |
-
return "", "", ""
|
| 780 |
-
|
| 781 |
-
instruction = cmd_match.group(1).upper()
|
| 782 |
-
command_part = cmd_match.group(2).strip()
|
| 783 |
-
|
| 784 |
-
# 判断是 exec 格式 (JSON数组) 还是 shell 格式
|
| 785 |
-
if command_part.startswith('[') and command_part.endswith(']'):
|
| 786 |
-
return instruction, command_part, "exec"
|
| 787 |
-
else:
|
| 788 |
-
return instruction, command_part, "shell"
|
| 789 |
-
|
| 790 |
-
def modify_shell_format(self, command: str) -> str:
|
| 791 |
-
"""修改 shell 格式的命令"""
|
| 792 |
-
# 在原命令前添加环境变量
|
| 793 |
-
return f'{self.preload_prefix} {command}'
|
| 794 |
-
|
| 795 |
-
def modify_exec_format(self, command: str) -> str:
|
| 796 |
-
"""修改 exec 格式 (JSON数组) 的命令"""
|
| 797 |
-
try:
|
| 798 |
-
# 解析 JSON 数组格式
|
| 799 |
-
# 移除外层的方括号
|
| 800 |
-
inner = command[1:-1].strip()
|
| 801 |
-
|
| 802 |
-
# 简单的 JSON 数组解析
|
| 803 |
-
parts = []
|
| 804 |
-
current = ""
|
| 805 |
-
in_quotes = False
|
| 806 |
-
escape_next = False
|
| 807 |
-
|
| 808 |
-
for char in inner:
|
| 809 |
-
if escape_next:
|
| 810 |
-
current += char
|
| 811 |
-
escape_next = False
|
| 812 |
-
elif char == '\\':
|
| 813 |
-
current += char
|
| 814 |
-
escape_next = True
|
| 815 |
-
elif char == '"' and not escape_next:
|
| 816 |
-
in_quotes = not in_quotes
|
| 817 |
-
current += char
|
| 818 |
-
elif char == ',' and not in_quotes:
|
| 819 |
-
parts.append(current.strip())
|
| 820 |
-
current = ""
|
| 821 |
-
else:
|
| 822 |
-
current += char
|
| 823 |
-
|
| 824 |
-
if current.strip():
|
| 825 |
-
parts.append(current.strip())
|
| 826 |
-
|
| 827 |
-
# 移除引号并处理转义
|
| 828 |
-
cleaned_parts = []
|
| 829 |
-
for part in parts:
|
| 830 |
-
part = part.strip()
|
| 831 |
-
if part.startswith('"') and part.endswith('"'):
|
| 832 |
-
part = part[1:-1]
|
| 833 |
-
# 处理基本的转义字符
|
| 834 |
-
part = part.replace('\\"', '"').replace('\\\\', '\\')
|
| 835 |
-
cleaned_parts.append(part)
|
| 836 |
-
|
| 837 |
-
if not cleaned_parts:
|
| 838 |
-
return command
|
| 839 |
-
|
| 840 |
-
# 构建新的命令
|
| 841 |
-
# 第一个元素通常是 shell (/bin/sh, /bin/bash 等)
|
| 842 |
-
# 如果第一个元素是 shell,修改执行的命令
|
| 843 |
-
if len(cleaned_parts) >= 3 and cleaned_parts[0] in ['/bin/sh', '/bin/bash', 'sh', 'bash']:
|
| 844 |
-
if cleaned_parts[1] == '-c':
|
| 845 |
-
# 格式: ["/bin/sh", "-c", "command"]
|
| 846 |
-
original_cmd = cleaned_parts[2]
|
| 847 |
-
new_cmd = f'{self.preload_prefix} {original_cmd}'
|
| 848 |
-
new_parts = [cleaned_parts[0], cleaned_parts[1], new_cmd] + cleaned_parts[3:]
|
| 849 |
-
else:
|
| 850 |
-
# 直接在现有命令前添加环境变量,通过 shell 执行
|
| 851 |
-
original_cmd = ' '.join(cleaned_parts[1:])
|
| 852 |
-
new_cmd = f'{self.preload_prefix} {original_cmd}'
|
| 853 |
-
new_parts = [cleaned_parts[0], '-c', new_cmd]
|
| 854 |
-
else:
|
| 855 |
-
# 直接执行的命令,需要通过 shell 包装
|
| 856 |
-
original_cmd = ' '.join(cleaned_parts)
|
| 857 |
-
new_parts = ['/bin/sh', '-c', f'{self.preload_prefix} {original_cmd}']
|
| 858 |
-
|
| 859 |
-
# 重新构建 JSON 数组
|
| 860 |
-
escaped_parts = []
|
| 861 |
-
for part in new_parts:
|
| 862 |
-
# 转义引号和反斜杠
|
| 863 |
-
escaped = part.replace('\\', '\\\\').replace('"', '\\"')
|
| 864 |
-
escaped_parts.append(f'"{escaped}"')
|
| 865 |
-
|
| 866 |
-
return '[' + ', '.join(escaped_parts) + ']'
|
| 867 |
-
|
| 868 |
-
except Exception as e:
|
| 869 |
-
print(f"警告: 解析 exec 格式失败: {e}")
|
| 870 |
-
print(f"原始命令: {command}")
|
| 871 |
-
# 如果解析失败,转换为 shell 格式
|
| 872 |
-
return f'{self.preload_prefix} {command}'
|
| 873 |
-
|
| 874 |
-
def modify_dockerfile_content(self, content: str) -> Tuple[str, List[str]]:
|
| 875 |
-
"""
|
| 876 |
-
修改 Dockerfile 内容
|
| 877 |
-
返回: (修改后的内容, 修改日志)
|
| 878 |
-
"""
|
| 879 |
-
lines = content.splitlines()
|
| 880 |
-
modified_lines = []
|
| 881 |
-
changes = []
|
| 882 |
-
|
| 883 |
-
for i, line in enumerate(lines, 1):
|
| 884 |
-
instruction, command, format_type = self.parse_dockerfile_line(line)
|
| 885 |
-
|
| 886 |
-
if instruction in ['CMD', 'ENTRYPOINT'] and command:
|
| 887 |
-
if format_type == "shell":
|
| 888 |
-
new_command = self.modify_shell_format(command)
|
| 889 |
-
new_line = f'{instruction} {new_command}'
|
| 890 |
-
elif format_type == "exec":
|
| 891 |
-
new_command = self.modify_exec_format(command)
|
| 892 |
-
new_line = f'{instruction} {new_command}'
|
| 893 |
-
else:
|
| 894 |
-
new_line = line
|
| 895 |
-
|
| 896 |
-
changes.append(f"第 {i} 行: {instruction} 指令已修改")
|
| 897 |
-
changes.append(f" 原始: {line}")
|
| 898 |
-
changes.append(f" 修改: {new_line}")
|
| 899 |
-
modified_lines.append(new_line)
|
| 900 |
-
else:
|
| 901 |
-
modified_lines.append(line)
|
| 902 |
-
|
| 903 |
-
last_user = None
|
| 904 |
-
for line in modified_lines[::-1]:
|
| 905 |
-
if line.startswith("USER"):
|
| 906 |
-
last_user = line.split()[1].strip()
|
| 907 |
-
|
| 908 |
-
if last_user is None:
|
| 909 |
-
modified_lines.insert(-1, f"COPY {self.source_so_path}" + f" {self.tatget_so_path}")
|
| 910 |
-
else:
|
| 911 |
-
modified_lines.insert(-1, f"COPY --chown={last_user}:{last_user} {self.source_so_path} {self.tatget_so_path}")
|
| 912 |
-
modified_lines.insert(-1, f"RUN chown -R {last_user}:{last_user} {self.tatget_so_dir}")
|
| 913 |
-
|
| 914 |
-
return '\n'.join(modified_lines), changes
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
dockerfile_modifier = DockerfileModifier("127.0.0.1,xdimlab-hugsim-web-server-0.hf.space")
|
|
|
|
| 3 |
import os
|
| 4 |
import shlex
|
| 5 |
import subprocess
|
|
|
|
| 6 |
import threading
|
| 7 |
import uuid
|
| 8 |
import base64
|
|
|
|
| 13 |
|
| 14 |
import requests
|
| 15 |
import pandas as pd
|
| 16 |
+
import numpy as np
|
| 17 |
import jwt
|
| 18 |
from fastapi import Request
|
| 19 |
from huggingface_hub import HfApi, hf_hub_download
|
|
|
|
| 470 |
)
|
| 471 |
|
| 472 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
class SubmissionApi:
|
| 474 |
def __init__(self, hf_token: str, competition_id: str):
|
| 475 |
self.hf_token = hf_token
|
|
|
|
| 542 |
)
|
| 543 |
|
| 544 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
class LeaderboardApi:
|
| 546 |
def __init__(self, hf_token: str, competition_id: str):
|
| 547 |
self.hf_token = hf_token
|
|
|
|
| 557 |
"""
|
| 558 |
all_scores = self._get_all_scores()
|
| 559 |
if not all_scores:
|
| 560 |
+
return pd.DataFrame(columns=["team_id", "team_name", "score"])
|
| 561 |
|
| 562 |
df = pd.DataFrame(all_scores)
|
| 563 |
+
df = df.sort_values(by=["score"], ascending=[False])
|
| 564 |
df = df.groupby("team_id").first()
|
| 565 |
+
df = df.sort_values(by=["score"], ascending=[False])
|
| 566 |
df['rank'] = range(1, len(df) + 1)
|
| 567 |
df.insert(0, 'rank', df.pop('rank'))
|
| 568 |
df.reset_index(drop=True, inplace=True)
|
|
|
|
| 594 |
all_scores.append({
|
| 595 |
"team_id": team_id,
|
| 596 |
"team_name": team_metadata[team_id]["name"],
|
| 597 |
+
"score": sub["score"],
|
|
|
|
| 598 |
})
|
| 599 |
return all_scores
|
| 600 |
|
|
|
|
| 603 |
hf_token=os.environ.get("HF_TOKEN", None),
|
| 604 |
competition_id=os.environ.get("COMPETITION_ID")
|
| 605 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
download_pre_datas.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from huggingface_hub import snapshot_download
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
snapshot_download(
|
| 5 |
+
repo_id='XDimLab/nvs-gt-datas',
|
| 6 |
+
revision='main',
|
| 7 |
+
local_dir='./test_gt_datas',
|
| 8 |
+
repo_type='dataset',
|
| 9 |
+
token=os.getenv("HF_TOKEN", ""),
|
| 10 |
+
)
|
requirements.txt
CHANGED
|
@@ -18,3 +18,8 @@ hf-transfer>=0.1.9
|
|
| 18 |
filelock>=3.13.3
|
| 19 |
cachetools==6.0.0
|
| 20 |
PyJWT>=2.10.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
filelock>=3.13.3
|
| 19 |
cachetools==6.0.0
|
| 20 |
PyJWT>=2.10.1
|
| 21 |
+
pillow==10.4.0
|
| 22 |
+
torch==2.7.1
|
| 23 |
+
torchvision==0.22.1
|
| 24 |
+
torchmetrics==1.7.3
|
| 25 |
+
lpips==0.1.4
|