com3dian commited on
Commit
8542abb
Β·
verified Β·
1 Parent(s): d96bd17

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +79 -38
src/streamlit_app.py CHANGED
@@ -1,57 +1,98 @@
1
- import gradio as gr
 
2
  import pandas as pd
3
  import os
4
  import datetime
 
 
5
 
6
  from google_sheet import fetch_leaderboard
7
  from google_drive import upload_to_drive
8
 
 
9
  os.makedirs("submissions", exist_ok=True)
10
 
11
- def get_leaderboard_html():
12
- try:
13
- df = fetch_leaderboard()
14
- if df.empty:
15
- return "<p>No submissions yet.</p>"
16
- df_sorted = df.sort_values(by="score", ascending=False)
17
- return df_sorted.to_html(index=False)
18
- except Exception as e:
19
- return f"<p>Could not load leaderboard: {e}</p>"
20
 
21
- def handle_submission(file):
22
- if file is None:
23
- return "❌ No file uploaded.", "<p>No leaderboard to show.</p>"
24
 
25
- timestamp = datetime.datetime.now().isoformat().replace(":", "_")
26
- submission_filename = f"{timestamp}_{file.name}"
27
- submission_path = os.path.join("submissions", submission_filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- with open(submission_path, "wb") as f:
30
- f.write(file.read())
 
 
31
 
32
- try:
33
- drive_file_id = upload_to_drive(submission_path, submission_filename)
34
- status = f"βœ… Uploaded to Google Drive [File ID: {drive_file_id}]"
35
- except Exception as e:
36
- status = f"⚠️ Failed to upload to Google Drive: {e}"
37
 
38
- leaderboard_html = get_leaderboard_html()
39
- return status, leaderboard_html
 
40
 
41
- with gr.Blocks(title="πŸ† Hackathon Leaderboard") as demo:
42
- gr.Markdown("## πŸ† Hackathon Leaderboard")
43
 
44
- with gr.Row():
45
- file_input = gr.File(label="Upload your submission (.zip)", file_types=[".zip"])
46
- submit_btn = gr.Button("Submit")
 
 
 
47
 
48
- status_output = gr.Markdown()
49
- leaderboard_output = gr.HTML(get_leaderboard_html())
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- submit_btn.click(
52
- fn=handle_submission,
53
- inputs=file_input,
54
- outputs=[status_output, leaderboard_output]
55
- )
 
 
 
 
 
 
 
 
 
 
56
 
57
- demo.launch(share=True)
 
 
1
+ import dash
2
+ from dash import dcc, html, Input, Output, State, dash_table
3
  import pandas as pd
4
  import os
5
  import datetime
6
+ import base64
7
+ import io
8
 
9
  from google_sheet import fetch_leaderboard
10
  from google_drive import upload_to_drive
11
 
12
+ # Make sure submissions folder exists
13
  os.makedirs("submissions", exist_ok=True)
14
 
15
+ app = dash.Dash(__name__)
16
+ app.title = "πŸ† Hackathon Leaderboard"
 
 
 
 
 
 
 
17
 
18
+ app.layout = html.Div([
19
+ html.H2("πŸ† Hackathon Leaderboard"),
 
20
 
21
+ dcc.Upload(
22
+ id='upload-data',
23
+ children=html.Div([
24
+ 'πŸ“ Drag and drop or click to upload a .zip file'
25
+ ]),
26
+ style={
27
+ 'width': '50%',
28
+ 'height': '60px',
29
+ 'lineHeight': '60px',
30
+ 'borderWidth': '1px',
31
+ 'borderStyle': 'dashed',
32
+ 'borderRadius': '10px',
33
+ 'textAlign': 'center',
34
+ 'margin': '20px'
35
+ },
36
+ multiple=False,
37
+ accept='.zip'
38
+ ),
39
+ html.Button('Submit', id='submit-btn', n_clicks=0),
40
 
41
+ html.Div(id='upload-status', style={'margin': '20px', 'fontWeight': 'bold'}),
42
+ html.H3("Leaderboard"),
43
+ html.Div(id='leaderboard-table', style={'margin': '20px'})
44
+ ])
45
 
46
+ def save_file_and_upload(content, filename):
47
+ timestamp = datetime.datetime.now().isoformat().replace(':', '_')
48
+ saved_filename = f"{timestamp}_{filename}"
49
+ path = os.path.join("submissions", saved_filename)
 
50
 
51
+ # Decode and save the file
52
+ content_string = content.split(',')[1]
53
+ decoded = base64.b64decode(content_string)
54
 
55
+ with open(path, 'wb') as f:
56
+ f.write(decoded)
57
 
58
+ # Upload to Google Drive
59
+ try:
60
+ drive_file_id = upload_to_drive(path, saved_filename)
61
+ return f"βœ… Uploaded to Google Drive [File ID: {drive_file_id}]"
62
+ except Exception as e:
63
+ return f"⚠️ Failed to upload to Google Drive: {e}"
64
 
65
+ def generate_leaderboard():
66
+ try:
67
+ df = fetch_leaderboard()
68
+ if df.empty:
69
+ return html.Div("No submissions yet.")
70
+ df_sorted = df.sort_values(by="score", ascending=False)
71
+ return dash_table.DataTable(
72
+ data=df_sorted.to_dict("records"),
73
+ columns=[{"name": i, "id": i} for i in df_sorted.columns],
74
+ style_table={'overflowX': 'auto'},
75
+ style_cell={'textAlign': 'left', 'padding': '5px'},
76
+ style_header={'backgroundColor': 'lightgrey', 'fontWeight': 'bold'}
77
+ )
78
+ except Exception as e:
79
+ return html.Div(f"Could not load leaderboard: {e}")
80
 
81
+ @app.callback(
82
+ Output('upload-status', 'children'),
83
+ Output('leaderboard-table', 'children'),
84
+ Input('submit-btn', 'n_clicks'),
85
+ State('upload-data', 'contents'),
86
+ State('upload-data', 'filename'),
87
+ prevent_initial_call=True
88
+ )
89
+ def handle_submission(n_clicks, contents, filename):
90
+ if contents is None:
91
+ return "❌ No file uploaded.", generate_leaderboard()
92
+
93
+ status = save_file_and_upload(contents, filename)
94
+ leaderboard = generate_leaderboard()
95
+ return status, leaderboard
96
 
97
+ if __name__ == '__main__':
98
+ app.run_server(debug=True)