lewtun HF staff commited on
Commit
6d09ca9
β€’
1 Parent(s): 2acc05f

Add success message

Browse files
Files changed (2) hide show
  1. app.py +37 -39
  2. validate.py β†’ utils.py +24 -13
app.py CHANGED
@@ -1,17 +1,14 @@
1
  import json
2
  import os
3
- import re
4
  import shutil
5
- import subprocess
6
  from datetime import datetime
7
  from pathlib import Path
8
 
9
- import requests
10
  import streamlit as st
11
  from dotenv import load_dotenv
12
  from huggingface_hub import HfApi, Repository
13
 
14
- from validate import validate_submission
15
 
16
  if Path(".env").is_file():
17
  load_dotenv(".env")
@@ -22,29 +19,6 @@ HF_AUTONLP_BACKEND_API = os.getenv("HF_AUTONLP_BACKEND_API")
22
  LOCAL_REPO = "submission_repo"
23
 
24
 
25
- def get_auth_headers(token: str, prefix: str = "autonlp"):
26
- return {"Authorization": f"{prefix} {token}"}
27
-
28
-
29
- def http_post(
30
- path: str,
31
- token: str,
32
- payload=None,
33
- domain: str = HF_AUTONLP_BACKEND_API,
34
- suppress_logs: bool = False,
35
- **kwargs,
36
- ) -> requests.Response:
37
- """HTTP POST request to the AutoNLP API, raises UnreachableAPIError if the API cannot be reached"""
38
- try:
39
- response = requests.post(
40
- url=domain + path, json=payload, headers=get_auth_headers(token=token), allow_redirects=True, **kwargs
41
- )
42
- except requests.exceptions.ConnectionError:
43
- print("❌ Failed to reach AutoNLP API, check your internet connection")
44
- response.raise_for_status()
45
- return response
46
-
47
-
48
  ###########
49
  ### APP ###
50
  ###########
@@ -59,18 +33,29 @@ GEM aims to:
59
  - audit data and models and present results via data cards and model robustness reports.
60
  - develop standards for evaluation of generated text using both automated and human metrics.
61
 
62
- Use this page to submit your predcitions to the benchmark.
63
  """
64
  )
65
 
66
  with st.form(key="form"):
67
  # Flush local repo
68
  shutil.rmtree(LOCAL_REPO, ignore_errors=True)
 
69
  uploaded_file = st.file_uploader("Upload submission.json file", type=["json"])
70
 
71
- if uploaded_file is not None:
72
- data = str(uploaded_file.read(), "utf-8")
73
- json_data = json.loads(data)
 
 
 
 
 
 
 
 
 
 
74
 
75
  with st.expander("Submission format"):
76
  st.markdown(
@@ -110,19 +95,28 @@ with st.form(key="form"):
110
  type="password",
111
  help="You can generate an access token via your πŸ€— Hub settings. See the [docs](https://huggingface.co/docs/hub/security#user-access-tokens) for more details",
112
  )
 
 
 
 
 
 
113
 
114
  submit_button = st.form_submit_button("Make Submission")
115
 
116
- if submit_button:
117
- validate_submission(json_data)
118
- user_info = HfApi().whoami(token)
119
  user_name = user_info["name"]
120
  submission_name = json_data["submission_name"]
121
 
122
  # Create submission dataset under benchmarks ORG
123
  dataset_repo_url = f"https://huggingface.co/datasets/benchmarks/gem-{user_name}"
124
  repo = Repository(
125
- local_dir=LOCAL_REPO, clone_from=dataset_repo_url, repo_type="dataset", private=True, use_auth_token=HF_TOKEN
 
 
 
 
126
  )
127
  submission_metadata = {"benchmark": "gem", "type": "prediction", "submission_name": submission_name}
128
  repo.repocard_metadata_save(submission_metadata)
@@ -151,10 +145,14 @@ if submit_button:
151
  "split": "test",
152
  "config": None,
153
  }
154
- json_resp = http_post(path="/evaluate/create", payload=payload, token=HF_TOKEN).json()
155
- st.write(json_data["submission_name"])
156
- st.write(commit_sha)
157
- st.write(json_resp)
 
 
 
 
158
 
159
  # Flush local repo
160
  shutil.rmtree(LOCAL_REPO, ignore_errors=True)
1
  import json
2
  import os
 
3
  import shutil
 
4
  from datetime import datetime
5
  from pathlib import Path
6
 
 
7
  import streamlit as st
8
  from dotenv import load_dotenv
9
  from huggingface_hub import HfApi, Repository
10
 
11
+ from utils import http_post, validate_json
12
 
13
  if Path(".env").is_file():
14
  load_dotenv(".env")
19
  LOCAL_REPO = "submission_repo"
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  ###########
23
  ### APP ###
24
  ###########
33
  - audit data and models and present results via data cards and model robustness reports.
34
  - develop standards for evaluation of generated text using both automated and human metrics.
35
 
36
+ Use this page to submit your system's predictions to the benchmark.
37
  """
38
  )
39
 
40
  with st.form(key="form"):
41
  # Flush local repo
42
  shutil.rmtree(LOCAL_REPO, ignore_errors=True)
43
+ submission_errors = 0
44
  uploaded_file = st.file_uploader("Upload submission.json file", type=["json"])
45
 
46
+ if uploaded_file:
47
+ if uploaded_file.name != "submission.json":
48
+ st.error(f"β›” Invalid filename. Please upload a submission.json file.")
49
+ submission_errors += 1
50
+ else:
51
+ data = str(uploaded_file.read(), "utf-8")
52
+ json_data = json.loads(data)
53
+ is_valid, message = validate_json(json_data)
54
+ if is_valid:
55
+ st.success(message)
56
+ else:
57
+ st.error(message)
58
+ submission_errors += 1
59
 
60
  with st.expander("Submission format"):
61
  st.markdown(
95
  type="password",
96
  help="You can generate an access token via your πŸ€— Hub settings. See the [docs](https://huggingface.co/docs/hub/security#user-access-tokens) for more details",
97
  )
98
+ if token:
99
+ try:
100
+ user_info = HfApi().whoami(token)
101
+ except Exception as e:
102
+ st.error("β›” Invalid access token")
103
+ submission_errors += 1
104
 
105
  submit_button = st.form_submit_button("Make Submission")
106
 
107
+ if submit_button and submission_errors == 0:
108
+ st.write("⏳ Preparing submission for evaluation ...")
 
109
  user_name = user_info["name"]
110
  submission_name = json_data["submission_name"]
111
 
112
  # Create submission dataset under benchmarks ORG
113
  dataset_repo_url = f"https://huggingface.co/datasets/benchmarks/gem-{user_name}"
114
  repo = Repository(
115
+ local_dir=LOCAL_REPO,
116
+ clone_from=dataset_repo_url,
117
+ repo_type="dataset",
118
+ private=True,
119
+ use_auth_token=HF_TOKEN,
120
  )
121
  submission_metadata = {"benchmark": "gem", "type": "prediction", "submission_name": submission_name}
122
  repo.repocard_metadata_save(submission_metadata)
145
  "split": "test",
146
  "config": None,
147
  }
148
+ json_resp = http_post(
149
+ path="/evaluate/create", payload=payload, token=HF_TOKEN, domain=HF_AUTONLP_BACKEND_API
150
+ ).json()
151
+
152
+ if json_resp["status"] == 1:
153
+ st.success(f"βœ… Submission {submission_name} was successfully submitted to the evaluation queue!")
154
+ else:
155
+ st.error("πŸ™ˆ Oh noes! There was an error submitting your submission. Please contact the organisers")
156
 
157
  # Flush local repo
158
  shutil.rmtree(LOCAL_REPO, ignore_errors=True)
validate.py β†’ utils.py RENAMED
@@ -1,34 +1,45 @@
1
  import json
2
 
3
  import jsonschema
 
4
  import streamlit as st
5
 
6
 
7
- def get_schema():
8
- """This function loads the given schema available"""
9
  with open("schema.json", "r", encoding="utf8") as file:
10
  schema = json.load(file)
11
  return schema
12
 
13
 
14
  def validate_json(json_data):
15
- execute_api_schema = get_schema()
16
  try:
17
  jsonschema.validate(instance=json_data, schema=execute_api_schema)
18
  except jsonschema.exceptions.ValidationError as err:
19
- err = "Submission does not match GEM schema!"
20
  return False, err
21
 
22
- message = "Submission matches GEM schema!"
23
  return True, message
24
 
25
 
26
- def validate_submission(submission_data):
27
- is_valid, message = validate_json(submission_data)
28
 
29
- if is_valid:
30
- st.write("All submission files validated! ✨ πŸš€ ✨")
31
- st.write("Now you can make a submission πŸ€—")
32
- else:
33
- st.write(message)
34
- st.write("Please fix the submission files πŸ™ˆ")
 
 
 
 
 
 
 
 
 
 
1
  import json
2
 
3
  import jsonschema
4
+ import requests
5
  import streamlit as st
6
 
7
 
8
+ def load_schema():
9
+ """Load the GEM schema"""
10
  with open("schema.json", "r", encoding="utf8") as file:
11
  schema = json.load(file)
12
  return schema
13
 
14
 
15
  def validate_json(json_data):
16
+ execute_api_schema = load_schema()
17
  try:
18
  jsonschema.validate(instance=json_data, schema=execute_api_schema)
19
  except jsonschema.exceptions.ValidationError as err:
20
+ err = "❌ Submission does not match GEM schema. Please fix the submission file πŸ™ˆ"
21
  return False, err
22
 
23
+ message = "βœ… Submission matches GEM schema!"
24
  return True, message
25
 
26
 
27
+ def get_auth_headers(token: str, prefix: str = "autonlp"):
28
+ return {"Authorization": f"{prefix} {token}"}
29
 
30
+
31
+ def http_post(
32
+ path: str,
33
+ token: str,
34
+ payload=None,
35
+ domain: str = None,
36
+ ) -> requests.Response:
37
+ """HTTP POST request to the AutoNLP API, raises UnreachableAPIError if the API cannot be reached"""
38
+ try:
39
+ response = requests.post(
40
+ url=domain + path, json=payload, headers=get_auth_headers(token=token), allow_redirects=True
41
+ )
42
+ except requests.exceptions.ConnectionError:
43
+ print("❌ Failed to reach AutoNLP API, check your internet connection")
44
+ response.raise_for_status()
45
+ return response