lunarflu HF staff commited on
Commit
4d6295e
β€’
1 Parent(s): ddad26b
Files changed (1) hide show
  1. app.py +144 -3
app.py CHANGED
@@ -17,6 +17,7 @@ import gspread
17
  import numpy as np
18
  import pandas as pd
19
  import requests
 
20
 
21
  from requests import HTTPError
22
  from apscheduler.executors.pool import ThreadPoolExecutor
@@ -28,7 +29,7 @@ from gspread_dataframe import get_as_dataframe, set_with_dataframe
28
  from gspread_formatting.dataframe import format_with_dataframe
29
  from huggingface_hub import HfApi, list_liked_repos, list_metrics, list_models
30
  from tabulate import tabulate
31
- from datetime import datetime
32
 
33
 
34
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
@@ -701,7 +702,133 @@ def get_data2():
701
  display_df = pd.DataFrame(display_data)
702
  return display_df
703
  except Exception as e:
704
- print(f"get_data2 Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
705
 
706
 
707
  demo = gr.Blocks()
@@ -740,7 +867,21 @@ with demo:
740
  gr.Markdown("# πŸ“ˆ How to earn Experience!")
741
  with gr.Row():
742
  gr.DataFrame(get_data2, every=5, interactive=False)
743
- #with gr.TabItem("πŸ“ˆ Members of the Week", elem_id="week-table", id=1):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
744
 
745
  #with gr.TabItem("πŸ“ˆ Hub-only leaderboard", elem_id="hub-table", id=2):
746
  except Exception as e:
 
17
  import numpy as np
18
  import pandas as pd
19
  import requests
20
+ import plotly.graph_objects as go
21
 
22
  from requests import HTTPError
23
  from apscheduler.executors.pool import ThreadPoolExecutor
 
29
  from gspread_formatting.dataframe import format_with_dataframe
30
  from huggingface_hub import HfApi, list_liked_repos, list_metrics, list_models
31
  from tabulate import tabulate
32
+ from datetime import datetime, timedelta
33
 
34
 
35
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
 
702
  display_df = pd.DataFrame(display_data)
703
  return display_df
704
  except Exception as e:
705
+ print(f"get_data2 Error: {e}")
706
+
707
+
708
+ #-------------------------------------------------------------------------------------------------------------------------------
709
+ colors = ['white', 'lightgreen', 'green', 'darkgreen']
710
+
711
+ # year->get all dates
712
+ def get_dates_in_year(year):
713
+ start_date = datetime(year, 1, 1)
714
+ end_date = datetime(year + 1, 1, 1)
715
+ delta = end_date - start_date
716
+ return [start_date + timedelta(days=i) for i in range(delta.days)]
717
+
718
+ # HF API->get activity
719
+ def get_user_likes(username):
720
+ url = f"https://huggingface.co/api/users/{username}/likes"
721
+ response = requests.get(url)
722
+ if response.status_code == 200:
723
+ return response.json()
724
+ else:
725
+ print(f"Failed to fetch data: {response.status_code}")
726
+ return []
727
+
728
+ # data->get dates
729
+ def parse_activity_dates(activity_data):
730
+ activity_dates = []
731
+ for item in activity_data:
732
+ timestamp = item.get('createdAt')
733
+ if timestamp:
734
+ date = datetime.fromisoformat(timestamp[:-1]).date()
735
+ activity_dates.append(date)
736
+ return activity_dates
737
+
738
+ def create_plot(username, year):
739
+ dates_in_year = get_dates_in_year(year)
740
+
741
+ dates_in_year = [d.date() for d in dates_in_year]
742
+
743
+ activity_data = get_user_likes(username)
744
+ activity_dates = parse_activity_dates(activity_data)
745
+
746
+ activity_count = {date: 0 for date in dates_in_year}
747
+ for date in activity_dates:
748
+ if date in activity_count:
749
+ activity_count[date] += 1
750
+
751
+ # activity->color
752
+ def get_color(activity_count):
753
+ if activity_count == 0:
754
+ return 'white'
755
+ elif activity_count < 5:
756
+ return 'lightgreen'
757
+ elif activity_count < 10:
758
+ return 'green'
759
+ else:
760
+ return 'darkgreen'
761
+
762
+ # data->Plotly
763
+ num_weeks = len(dates_in_year) // 7 + (1 if len(dates_in_year) % 7 != 0 else 0)
764
+
765
+ z = [[None for _ in range(num_weeks)] for _ in range(7)] # Was 0
766
+ hover_texts = [["" for _ in range(num_weeks)] for _ in range(7)]
767
+
768
+ for idx, date in enumerate(dates_in_year):
769
+ week = idx // 7
770
+ day = idx % 7
771
+ z[day][week] = activity_count[date]
772
+ hover_texts[day][week] = f"{date}: {activity_count[date]} activities"
773
+
774
+ # heatmap
775
+ fig = go.Figure(data=go.Heatmap(
776
+ z=z,
777
+ x=list(range(num_weeks)),
778
+ y=list(range(7)),
779
+ hoverinfo='text',
780
+ text=hover_texts,
781
+ showscale=False,
782
+ colorscale=[
783
+ [0, 'white'],
784
+ [0.25, 'lightgreen'],
785
+ [0.5, 'green'],
786
+ [1, 'darkgreen']
787
+ ],
788
+ zmin=0,
789
+ zmax=20
790
+ ))
791
+
792
+ # lock the plot size and ensure cells are square
793
+ cell_size = 20
794
+ fig.update_layout(
795
+ title=f'{username} Activity in {year}',
796
+ xaxis_nticks=52,
797
+ yaxis_nticks=7,
798
+ xaxis_title=' ',
799
+ yaxis_title=' ',
800
+ yaxis=dict(
801
+ tickmode='array',
802
+ tickvals=list(range(7)),
803
+ ticktext=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
804
+ scaleanchor="x", # This ensures that the cells are square
805
+ scaleratio=1
806
+ ),
807
+ xaxis=dict(
808
+ scaleanchor="y",
809
+ scaleratio=1,
810
+ fixedrange=True, # disable zoom and pan
811
+ showticklabels=False # hide the x-axis labels
812
+ ),
813
+ autosize=False,
814
+ width=num_weeks * cell_size,
815
+ height=14 * cell_size, # halve height of each cell
816
+ margin=dict(
817
+ l=20,
818
+ r=20,
819
+ b=20,
820
+ t=50,
821
+ pad=2
822
+ )
823
+ )
824
+
825
+ fig.update_layout(
826
+ xaxis=dict(fixedrange=True), # disable zoom and pan
827
+ yaxis=dict(fixedrange=True) # disable zoom and pan
828
+ )
829
+
830
+ return fig
831
+ #-------------------------------------------------------------------------------------------------------------------------------
832
 
833
 
834
  demo = gr.Blocks()
 
867
  gr.Markdown("# πŸ“ˆ How to earn Experience!")
868
  with gr.Row():
869
  gr.DataFrame(get_data2, every=5, interactive=False)
870
+ #with gr.TabItem("πŸ“ˆ Activity Heatmap", elem_id="activity-heatmap", id=1):
871
+ with gr.Row():
872
+ username_input = gr.Textbox(label="Enter Username")
873
+ with gr.Row():
874
+ year_buttons = [gr.Button(str(year)) for year in range(2021, 2025)]
875
+ with gr.Row():
876
+ plot = gr.Plot(label="Activity Heatmap")
877
+
878
+ # buttons for updating the plot
879
+ for button in year_buttons:
880
+ button.click(
881
+ fn=create_plot,
882
+ inputs=[username_input, gr.State(int(button.value))],
883
+ outputs=plot
884
+ )
885
 
886
  #with gr.TabItem("πŸ“ˆ Hub-only leaderboard", elem_id="hub-table", id=2):
887
  except Exception as e: