Miquel Farré commited on
Commit
942117f
·
1 Parent(s): 5fa7c4d
Files changed (1) hide show
  1. app.py +40 -57
app.py CHANGED
@@ -10,40 +10,43 @@ from typing import Optional, Tuple
10
  hf_api = HfApi(token=os.getenv("HF_TOKEN"))
11
  DATASET_REPO = "HuggingFaceTB/smolvlm2-iphone-waitlist"
12
  MAX_RETRIES = 3
13
- def commit_signup(username: str, current_data: pd.DataFrame) -> Optional[str]:
14
- """Attempt to commit new signup atomically"""
 
15
  try:
16
- # Verify current data has required columns
17
- if 'userid' not in current_data.columns or 'joined_at' not in current_data.columns:
 
 
 
 
 
 
18
  current_data = pd.DataFrame(columns=['userid', 'joined_at'])
19
-
 
 
 
 
20
  # Add new user with timestamp
21
  new_row = pd.DataFrame([{
22
  'userid': username,
23
  'joined_at': datetime.utcnow().isoformat()
24
  }])
25
 
26
- # Ensure we're not duplicating any existing users
27
- updated_data = pd.concat([
28
- current_data[~current_data['userid'].isin([username])], # Keep all except current user
29
- new_row
30
- ], ignore_index=True)
31
-
32
- # Sort by joined_at to maintain chronological order
33
- updated_data = updated_data.sort_values('joined_at').reset_index(drop=True)
34
 
35
  # Save to temp file
36
  with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as tmp:
37
  updated_data.to_csv(tmp.name, index=False)
38
 
39
- # Create commit operation
40
  operation = CommitOperationAdd(
41
  path_in_repo="waitlist.csv",
42
  path_or_fileobj=tmp.name
43
  )
44
 
45
  try:
46
- # Try to create commit
47
  create_commit(
48
  repo_id=DATASET_REPO,
49
  repo_type="dataset",
@@ -51,10 +54,10 @@ def commit_signup(username: str, current_data: pd.DataFrame) -> Optional[str]:
51
  commit_message=f"Add user {username} to waitlist"
52
  )
53
  os.unlink(tmp.name)
54
- return None # Success
55
  except Exception as e:
56
  os.unlink(tmp.name)
57
- return str(e) # Return error message
58
  except Exception as e:
59
  return str(e)
60
 
@@ -67,56 +70,35 @@ def join_waitlist(
67
  if profile is None or oauth_token is None:
68
  return gr.update(value="Please log in with your Hugging Face account first!")
69
 
 
 
70
  for attempt in range(MAX_RETRIES):
71
  try:
72
- # Get current waitlist state
73
- try:
74
- current_data = pd.read_csv(
 
 
 
75
  f"https://huggingface.co/datasets/{DATASET_REPO}/raw/main/waitlist.csv"
76
  )
77
- # Ensure data frame has required columns
78
- if 'userid' not in current_data.columns or 'joined_at' not in current_data.columns:
79
- current_data = pd.DataFrame(columns=['userid', 'joined_at'])
80
- except:
81
- current_data = pd.DataFrame(columns=['userid', 'joined_at'])
82
-
83
- # Check if user already registered
84
- if not current_data.empty and profile.username in current_data['userid'].values:
85
- return gr.update(
86
- value="## 😎 You're already on the waitlist! We'll keep you updated.",
87
- visible=True
88
- )
89
-
90
- # Try to commit the update
91
- error = commit_signup(profile.username, current_data)
92
-
93
- if error is None: # Success
94
- # Verify the commit worked by reading back the data
95
- try:
96
- verification_data = pd.read_csv(
97
- f"https://huggingface.co/datasets/{DATASET_REPO}/raw/main/waitlist.csv"
98
  )
99
- if profile.username not in verification_data['userid'].values:
100
- if attempt < MAX_RETRIES - 1:
101
- continue # Retry if verification failed
102
- else:
103
- raise Exception("Failed to verify signup")
104
- except Exception as e:
105
- if attempt < MAX_RETRIES - 1:
106
- continue
107
- raise e
108
-
109
- return gr.update(
110
- value="## 🎉 Thanks for joining the waitlist! We'll keep you updated on SmolVLM2 iPhone app.",
111
- visible=True
112
- )
113
 
114
  # If we got a conflict error, retry
115
- if "Conflict" in str(error) and attempt < MAX_RETRIES - 1:
116
  continue
117
 
118
  # Other error or last attempt
119
- gr.Error(f"An error occurred: {str(error)}")
 
120
  return gr.update(
121
  value="## 🫠 Sorry, something went wrong. Please try again later.",
122
  visible=True
@@ -129,6 +111,7 @@ def join_waitlist(
129
  value="## 🫠 Sorry, something went wrong. Please try again later.",
130
  visible=True
131
  )
 
132
  def update_ui(profile: gr.OAuthProfile | None) -> Tuple[str, bool, bool]:
133
  """Update UI elements based on login status"""
134
  if profile is None:
 
10
  hf_api = HfApi(token=os.getenv("HF_TOKEN"))
11
  DATASET_REPO = "HuggingFaceTB/smolvlm2-iphone-waitlist"
12
  MAX_RETRIES = 3
13
+
14
+ def commit_signup(username: str) -> Optional[str]:
15
+ """Attempt to commit new signup atomically, always reading latest data before commit"""
16
  try:
17
+ # Always get the latest data right before committing
18
+ try:
19
+ current_data = pd.read_csv(
20
+ f"https://huggingface.co/datasets/{DATASET_REPO}/raw/main/waitlist.csv"
21
+ )
22
+ if 'userid' not in current_data.columns or 'joined_at' not in current_data.columns:
23
+ current_data = pd.DataFrame(columns=['userid', 'joined_at'])
24
+ except:
25
  current_data = pd.DataFrame(columns=['userid', 'joined_at'])
26
+
27
+ # If user already exists in the latest data, don't add them again
28
+ if username in current_data['userid'].values:
29
+ return None
30
+
31
  # Add new user with timestamp
32
  new_row = pd.DataFrame([{
33
  'userid': username,
34
  'joined_at': datetime.utcnow().isoformat()
35
  }])
36
 
37
+ # Combine with latest data
38
+ updated_data = pd.concat([current_data, new_row], ignore_index=True)
 
 
 
 
 
 
39
 
40
  # Save to temp file
41
  with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as tmp:
42
  updated_data.to_csv(tmp.name, index=False)
43
 
 
44
  operation = CommitOperationAdd(
45
  path_in_repo="waitlist.csv",
46
  path_or_fileobj=tmp.name
47
  )
48
 
49
  try:
 
50
  create_commit(
51
  repo_id=DATASET_REPO,
52
  repo_type="dataset",
 
54
  commit_message=f"Add user {username} to waitlist"
55
  )
56
  os.unlink(tmp.name)
57
+ return None
58
  except Exception as e:
59
  os.unlink(tmp.name)
60
+ return str(e)
61
  except Exception as e:
62
  return str(e)
63
 
 
70
  if profile is None or oauth_token is None:
71
  return gr.update(value="Please log in with your Hugging Face account first!")
72
 
73
+ username = profile.username
74
+
75
  for attempt in range(MAX_RETRIES):
76
  try:
77
+ # Try to commit the update (which will get latest data internally)
78
+ error = commit_signup(username)
79
+
80
+ if error is None: # Success or already registered
81
+ # Verify user is in the list
82
+ verification_data = pd.read_csv(
83
  f"https://huggingface.co/datasets/{DATASET_REPO}/raw/main/waitlist.csv"
84
  )
85
+ if username in verification_data['userid'].values:
86
+ return gr.update(
87
+ value="## 🎉 Thanks for joining the waitlist! We'll keep you updated on SmolVLM2 iPhone app.",
88
+ visible=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  )
90
+
91
+ # If verification failed and we have retries left, try again
92
+ if attempt < MAX_RETRIES - 1:
93
+ continue
 
 
 
 
 
 
 
 
 
 
94
 
95
  # If we got a conflict error, retry
96
+ if error and "Conflict" in str(error) and attempt < MAX_RETRIES - 1:
97
  continue
98
 
99
  # Other error or last attempt
100
+ if error:
101
+ gr.Error(f"An error occurred: {str(error)}")
102
  return gr.update(
103
  value="## 🫠 Sorry, something went wrong. Please try again later.",
104
  visible=True
 
111
  value="## 🫠 Sorry, something went wrong. Please try again later.",
112
  visible=True
113
  )
114
+
115
  def update_ui(profile: gr.OAuthProfile | None) -> Tuple[str, bool, bool]:
116
  """Update UI elements based on login status"""
117
  if profile is None: