MeysamSh commited on
Commit
ec12e16
Β·
1 Parent(s): 8f5d1a0

Add application file

Browse files
Files changed (1) hide show
  1. app.py +44 -22
app.py CHANGED
@@ -9,13 +9,13 @@ from pathlib import Path
9
  DATASET_REPO_ID = "MeysamSh/ENSIMSoundDataCollection"
10
  HF_TOKEN = os.environ.get("HF_TOKEN")
11
 
12
- # Admin Credentials (Keep these secure!)
13
  ADMIN_USERNAME = "admin"
14
  ADMIN_PASSWORD = "30c8663d3ca10ededd17ac1b55f3d533ab29cf1b8470b1729af09afda3f0a516"
15
 
16
  AUTHORIZED_USERS = [
17
  "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
18
- "test@univ-lemans.fr"
19
  ]
20
 
21
  api = HfApi()
@@ -33,8 +33,8 @@ def verify_user(email):
33
  def upload_data(email, label, audio_path):
34
  if not audio_path: return "⚠️ No audio recorded."
35
  try:
36
- # email_hash = hashlib.sha256(email.strip().lower().encode()).hexdigest()
37
- email_index = AUTHORIZED_USERS.index(email.strip().lower()) if email.strip().lower() in AUTHORIZED_USERS else -1
38
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
39
  unique_filename = f"{email_index}_{timestamp}.wav"
40
 
@@ -42,7 +42,7 @@ def upload_data(email, label, audio_path):
42
  api.upload_file(path_or_fileobj=audio_path, path_in_repo=f"data/{unique_filename}",
43
  repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
44
  # Upload Metadata
45
- meta_content = f"user_id,label,file_name,timestamp\n{email.strip().lower()},{label},{unique_filename},{timestamp}"
46
  api.upload_file(path_or_fileobj=meta_content.encode(), path_in_repo=f"metadata/meta_{email_index}_{timestamp}.csv",
47
  repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
48
  return f"πŸŽ‰ Success! Audio saved as {label}."
@@ -50,30 +50,42 @@ def upload_data(email, label, audio_path):
50
 
51
  # --- ADMIN LOGIC ---
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def admin_login(user, pwd):
54
  pwd_hash = hashlib.sha256(pwd.encode()).hexdigest()
55
  if user == ADMIN_USERNAME and pwd_hash == ADMIN_PASSWORD:
56
- files = api.list_repo_files(repo_id=DATASET_REPO_ID, repo_type="dataset")
57
- audio_files = [f for f in files if f.startswith("data/")]
58
- return gr.update(visible=True), gr.update(choices=audio_files), "πŸ”“ Admin Authenticated"
59
- return gr.update(visible=False), gr.update(choices=[]), "❌ Invalid Credentials"
60
 
61
  def delete_selected_file(file_path):
62
- if not file_path: return "⚠️ Select a file."
63
  try:
64
- # Delete the audio file
65
  api.delete_file(path_in_repo=file_path, repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
66
-
67
- # Attempt to delete corresponding metadata
68
  meta_path = file_path.replace("data/", "metadata/meta_").replace(".wav", ".csv")
69
  try:
70
  api.delete_file(path_in_repo=meta_path, repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
71
  except: pass
72
 
73
- # Refresh file list
74
- files = api.list_repo_files(repo_id=DATASET_REPO_ID, repo_type="dataset")
75
- audio_files = [f for f in files if f.startswith("data/")]
76
- return f"πŸ—‘οΈ Deleted {file_path}", gr.update(choices=audio_files)
77
  except Exception as e: return f"❌ Error: {str(e)}", gr.update()
78
 
79
  # --- UI ---
@@ -85,12 +97,11 @@ with gr.Blocks() as demo:
85
  # STUDENT TAB
86
  with gr.TabItem("Student Recording"):
87
  with gr.Row():
88
- email_input = gr.Textbox(label="Email", placeholder="test@univ-lemans.fr")
89
  login_btn = gr.Button("Verify", variant="primary")
90
  login_status = gr.Markdown("Waiting for login...")
91
 
92
  with gr.Column(visible=False) as recording_zone:
93
- # gr.Separator()
94
  label_input = gr.Radio(choices=["Engine", "Environmental", "Mechanical"], label="Category")
95
  audio_input = gr.Audio(label="Record (40s)", sources=["microphone"], type="filepath")
96
  submit_btn = gr.Button("πŸš€ Submit", variant="primary")
@@ -104,9 +115,11 @@ with gr.Blocks() as demo:
104
  admin_login_btn = gr.Button("Login Admin")
105
 
106
  admin_msg = gr.Markdown("Log in to manage files.")
 
 
107
 
108
  with gr.Column(visible=False) as admin_panel:
109
- # gr.Separator()
110
  file_dropdown = gr.Dropdown(label="Select File to Remove", choices=[])
111
  delete_btn = gr.Button("πŸ—‘οΈ Delete Selected File", variant="stop")
112
  delete_status = gr.Textbox(label="Delete Progress")
@@ -115,8 +128,17 @@ with gr.Blocks() as demo:
115
  login_btn.click(verify_user, [email_input], [recording_zone, login_status])
116
  submit_btn.click(upload_data, [email_input, label_input, audio_input], final_status)
117
 
118
- admin_login_btn.click(admin_login, [admin_user, admin_pass], [admin_panel, file_dropdown, admin_msg])
119
- delete_btn.click(delete_selected_file, [file_dropdown], [delete_status, file_dropdown])
 
 
 
 
 
 
 
 
 
120
 
121
  if __name__ == "__main__":
122
  demo.launch(theme=gr.themes.Soft())
 
9
  DATASET_REPO_ID = "MeysamSh/ENSIMSoundDataCollection"
10
  HF_TOKEN = os.environ.get("HF_TOKEN")
11
 
12
+ # Admin Credentials
13
  ADMIN_USERNAME = "admin"
14
  ADMIN_PASSWORD = "30c8663d3ca10ededd17ac1b55f3d533ab29cf1b8470b1729af09afda3f0a516"
15
 
16
  AUTHORIZED_USERS = [
17
  "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
18
+ "test"
19
  ]
20
 
21
  api = HfApi()
 
33
  def upload_data(email, label, audio_path):
34
  if not audio_path: return "⚠️ No audio recorded."
35
  try:
36
+ clean_email = email.strip().lower()
37
+ email_index = AUTHORIZED_USERS.index(clean_email) if clean_email in AUTHORIZED_USERS else "unknown"
38
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
39
  unique_filename = f"{email_index}_{timestamp}.wav"
40
 
 
42
  api.upload_file(path_or_fileobj=audio_path, path_in_repo=f"data/{unique_filename}",
43
  repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
44
  # Upload Metadata
45
+ meta_content = f"user_id,label,file_name,timestamp\n{clean_email},{label},{unique_filename},{timestamp}"
46
  api.upload_file(path_or_fileobj=meta_content.encode(), path_in_repo=f"metadata/meta_{email_index}_{timestamp}.csv",
47
  repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
48
  return f"πŸŽ‰ Success! Audio saved as {label}."
 
50
 
51
  # --- ADMIN LOGIC ---
52
 
53
+ def get_stats():
54
+ """Helper to calculate stats from repository files"""
55
+ try:
56
+ files = api.list_repo_files(repo_id=DATASET_REPO_ID, repo_type="dataset")
57
+ audio_files = [f for f in files if f.startswith("data/") and f.endswith(".wav")]
58
+
59
+ # Extract user indices from filenames like 'data/0_20260511.wav'
60
+ user_indices = set()
61
+ for f in audio_files:
62
+ filename = f.split("/")[-1] # get '0_20260511.wav'
63
+ user_id = filename.split("_")[0]
64
+ user_indices.add(user_id)
65
+
66
+ stats_text = f"πŸ“Š **Stats:** {len(audio_files)} recordings from {len(user_indices)} unique contributors."
67
+ return audio_files, stats_text
68
+ except:
69
+ return [], "⚠️ Could not retrieve stats."
70
+
71
  def admin_login(user, pwd):
72
  pwd_hash = hashlib.sha256(pwd.encode()).hexdigest()
73
  if user == ADMIN_USERNAME and pwd_hash == ADMIN_PASSWORD:
74
+ audio_files, stats_text = get_stats()
75
+ return gr.update(visible=True), gr.update(choices=audio_files), "πŸ”“ Admin Authenticated", stats_text
76
+ return gr.update(visible=False), gr.update(choices=[]), "❌ Invalid Credentials", ""
 
77
 
78
  def delete_selected_file(file_path):
79
+ if not file_path: return "⚠️ Select a file.", gr.update()
80
  try:
 
81
  api.delete_file(path_in_repo=file_path, repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
 
 
82
  meta_path = file_path.replace("data/", "metadata/meta_").replace(".wav", ".csv")
83
  try:
84
  api.delete_file(path_in_repo=meta_path, repo_id=DATASET_REPO_ID, repo_type="dataset", token=HF_TOKEN)
85
  except: pass
86
 
87
+ audio_files, stats_text = get_stats()
88
+ return f"πŸ—‘οΈ Deleted {file_path}. {stats_text}", gr.update(choices=audio_files, value=None)
 
 
89
  except Exception as e: return f"❌ Error: {str(e)}", gr.update()
90
 
91
  # --- UI ---
 
97
  # STUDENT TAB
98
  with gr.TabItem("Student Recording"):
99
  with gr.Row():
100
+ email_input = gr.Textbox(label="Email", placeholder="test")
101
  login_btn = gr.Button("Verify", variant="primary")
102
  login_status = gr.Markdown("Waiting for login...")
103
 
104
  with gr.Column(visible=False) as recording_zone:
 
105
  label_input = gr.Radio(choices=["Engine", "Environmental", "Mechanical"], label="Category")
106
  audio_input = gr.Audio(label="Record (40s)", sources=["microphone"], type="filepath")
107
  submit_btn = gr.Button("πŸš€ Submit", variant="primary")
 
115
  admin_login_btn = gr.Button("Login Admin")
116
 
117
  admin_msg = gr.Markdown("Log in to manage files.")
118
+ # This will show the statistics
119
+ admin_stats_display = gr.Markdown("")
120
 
121
  with gr.Column(visible=False) as admin_panel:
122
+ gr.Separator()
123
  file_dropdown = gr.Dropdown(label="Select File to Remove", choices=[])
124
  delete_btn = gr.Button("πŸ—‘οΈ Delete Selected File", variant="stop")
125
  delete_status = gr.Textbox(label="Delete Progress")
 
128
  login_btn.click(verify_user, [email_input], [recording_zone, login_status])
129
  submit_btn.click(upload_data, [email_input, label_input, audio_input], final_status)
130
 
131
+ admin_login_btn.click(
132
+ admin_login,
133
+ [admin_user, admin_pass],
134
+ [admin_panel, file_dropdown, admin_msg, admin_stats_display]
135
+ )
136
+
137
+ delete_btn.click(
138
+ delete_selected_file,
139
+ [file_dropdown],
140
+ [delete_status, file_dropdown]
141
+ )
142
 
143
  if __name__ == "__main__":
144
  demo.launch(theme=gr.themes.Soft())