burtenshaw commited on
Commit
165c76d
·
1 Parent(s): 7a0686a

simplify datastream to deal with load

Browse files
Files changed (2) hide show
  1. app.py +32 -47
  2. criteria.py +11 -7
app.py CHANGED
@@ -6,7 +6,6 @@ import tempfile
6
 
7
  import gradio as gr
8
  from PIL import Image, ImageDraw, ImageFont
9
- from huggingface_hub import whoami, upload_file
10
 
11
  from criteria import check_certification as check_certification_criteria
12
  from org import join_finishers_org
@@ -53,23 +52,6 @@ def generate_certificate(
53
 
54
  return im, "certificate.pdf"
55
 
56
-
57
- def get_user_info(oauth_token):
58
- """Get user info from HF token."""
59
- if oauth_token is None:
60
- return None, None, None, None
61
- try:
62
- user_info = whoami(oauth_token.token)
63
- username = user_info["name"]
64
- name_parts = user_info["fullname"].split(" ", 1)
65
- first_name = name_parts[0]
66
- last_name = name_parts[1] if len(name_parts) > 1 else ""
67
- profile_url = user_info["avatarUrl"]
68
- return username, first_name, last_name, profile_url
69
- except:
70
- return None, None, None, None
71
-
72
-
73
  def create_linkedin_button(username: str, cert_url: str | None) -> str:
74
  """Create LinkedIn 'Add to Profile' button HTML."""
75
  current_year = date.today().year
@@ -149,13 +131,20 @@ def upload_certificate_to_hub(username: str, certificate_img) -> str:
149
  return None
150
 
151
 
152
- def check_certification(token: gr.OAuthToken | None):
153
  """Check certification status for logged-in user."""
154
- if token is None:
155
  gr.Warning("Please log in to Hugging Face before checking certification!")
156
  return None, None, None, gr.Row.update(visible=False)
157
 
158
- username, first_name, last_name, profile_url = get_user_info(token)
 
 
 
 
 
 
 
159
  if not username:
160
  return (
161
  "Please login with your Hugging Face account to check certification status",
@@ -194,39 +183,35 @@ def check_certification(token: gr.OAuthToken | None):
194
  )
195
 
196
 
197
- def create_gradio_interface():
198
- """Create Gradio web interface with OAuth login."""
199
- with gr.Blocks() as demo:
200
- gr.Markdown("""
201
- # Get your Hugging Face Course Certificate 🎓
202
- The certification process is completely free.
203
-
204
- To receive your certificate, you need to **pass 80% of the quiz**.
205
-
206
- There's **no deadlines, the course is self-paced**.
207
 
208
- Don't hesitate to share your certificate on Twitter
209
- (tag @huggingface) and on Linkedin.
210
- """)
211
 
212
- # Add login button
213
- gr.LoginButton()
 
214
 
215
- check_progress_button = gr.Button(value="Check My Progress")
 
216
 
217
- output_text = gr.Markdown(visible=False, sanitize_html=False)
218
- output_img = gr.Image(type="pil", visible=False)
219
 
220
- check_progress_button.click(
221
- fn=check_certification,
222
- outputs=[output_text, output_img],
223
- ).then(
224
- fn=join_finishers_org,
225
- )
 
 
 
226
 
227
- return demo
228
 
229
 
230
  if __name__ == "__main__":
231
- demo = create_gradio_interface()
232
  demo.launch(debug=True)
 
6
 
7
  import gradio as gr
8
  from PIL import Image, ImageDraw, ImageFont
 
9
 
10
  from criteria import check_certification as check_certification_criteria
11
  from org import join_finishers_org
 
52
 
53
  return im, "certificate.pdf"
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def create_linkedin_button(username: str, cert_url: str | None) -> str:
56
  """Create LinkedIn 'Add to Profile' button HTML."""
57
  current_year = date.today().year
 
131
  return None
132
 
133
 
134
+ def check_certification(token: gr.OAuthToken | None, profile: gr.OAuthProfile | None):
135
  """Check certification status for logged-in user."""
136
+ if token is None or profile is None:
137
  gr.Warning("Please log in to Hugging Face before checking certification!")
138
  return None, None, None, gr.Row.update(visible=False)
139
 
140
+ username = profile.username
141
+ first_name = profile.name.split(sep=" ")[0]
142
+ try:
143
+ last_name = " ".join(profile.name.split(sep=" ")[1:])
144
+ except IndexError:
145
+ last_name = ""
146
+ profile_url = profile.picture
147
+
148
  if not username:
149
  return (
150
  "Please login with your Hugging Face account to check certification status",
 
183
  )
184
 
185
 
186
+ with gr.Blocks() as demo:
187
+ gr.Markdown("""
188
+ # Get your Hugging Face Course Certificate 🎓
189
+ The certification process is completely free.
190
+
191
+ To receive your certificate, you need to **pass 80% of the quiz**.
 
 
 
 
192
 
193
+ There's **no deadlines, the course is self-paced**.
 
 
194
 
195
+ Don't hesitate to share your certificate on Twitter
196
+ (tag @huggingface) and on Linkedin.
197
+ """)
198
 
199
+ # Add login button
200
+ gr.LoginButton()
201
 
202
+ check_progress_button = gr.Button(value="Check My Progress")
 
203
 
204
+ output_text = gr.Markdown(visible=False, sanitize_html=False)
205
+ output_img = gr.Image(type="pil", visible=False)
206
+
207
+ check_progress_button.click(
208
+ fn=check_certification,
209
+ outputs=[output_text, output_img],
210
+ ).then(
211
+ fn=join_finishers_org,
212
+ )
213
 
 
214
 
215
 
216
  if __name__ == "__main__":
 
217
  demo.launch(debug=True)
criteria.py CHANGED
@@ -3,7 +3,6 @@ from typing import Dict, List, Optional, NamedTuple, Tuple
3
  from datetime import datetime
4
 
5
  from datasets import load_dataset
6
- from huggingface_hub import HfApi
7
 
8
  # Environment variables and constants
9
  EXAM_DATASET_ID = os.getenv(
@@ -37,9 +36,12 @@ def get_user_results(username: str) -> List[Dict]:
37
  List of user's quiz results
38
  """
39
  try:
40
- user_results = load_dataset(path=EXAM_DATASET_ID, split=username)
41
-
42
- results = user_results.to_list()
 
 
 
43
  print(f"Found {len(results)} results for user {username}")
44
  return results
45
 
@@ -85,9 +87,11 @@ def calculate_pass_percentage(results: List[Dict]) -> Tuple[float, int]:
85
  # Find the best attempt
86
  best_attempt = max(
87
  attempts.values(),
88
- key=lambda x: x["grade"]
89
- if x["grade"] is not None
90
- else (x["correct"] / x["total"] if x["total"] > 0 else 0),
 
 
91
  )
92
 
93
  # If grade is available, use it; otherwise calculate from correct/total
 
3
  from datetime import datetime
4
 
5
  from datasets import load_dataset
 
6
 
7
  # Environment variables and constants
8
  EXAM_DATASET_ID = os.getenv(
 
36
  List of user's quiz results
37
  """
38
  try:
39
+ user_results = load_dataset(
40
+ path=EXAM_DATASET_ID,
41
+ streaming=True,
42
+ data_files=f"data/{username}-00000-of-00001.parquet",
43
+ )
44
+ results = list(user_results["train"])
45
  print(f"Found {len(results)} results for user {username}")
46
  return results
47
 
 
87
  # Find the best attempt
88
  best_attempt = max(
89
  attempts.values(),
90
+ key=lambda x: (
91
+ x["grade"]
92
+ if x["grade"] is not None
93
+ else (x["correct"] / x["total"] if x["total"] > 0 else 0)
94
+ ),
95
  )
96
 
97
  # If grade is available, use it; otherwise calculate from correct/total