fffiloni commited on
Commit
f139b6c
·
verified ·
1 Parent(s): 412ec3b

fix(app): restore resolve_display_name and fix activity title rendering

Browse files
Files changed (1) hide show
  1. app.py +21 -467
app.py CHANGED
@@ -98,7 +98,6 @@ def validate_username(username: str, profile: gr.OAuthProfile | None):
98
  profile_username = getattr(profile, "username", None) if profile is not None else None
99
  profile_name = getattr(profile, "name", None) if profile is not None else None
100
 
101
- # Logged-in user is the safest source of truth for their own handle/name.
102
  if profile_username and profile_username.lower() == username.lower():
103
  result = {
104
  "exists": True,
@@ -125,7 +124,6 @@ def validate_username(username: str, profile: gr.OAuthProfile | None):
125
  )
126
 
127
  try:
128
- # Reliable enough for existence checks without depending on an undocumented API shape.
129
  response = session.get(
130
  f"https://huggingface.co/{username}",
131
  timeout=15,
@@ -152,7 +150,6 @@ def validate_username(username: str, profile: gr.OAuthProfile | None):
152
  return result
153
 
154
  except Exception:
155
- # Be permissive on transient failures to avoid false negatives.
156
  result = {
157
  "exists": True,
158
  "username": username,
@@ -659,478 +656,39 @@ def fetch_all_community_activity(username: str, selected_year: int):
659
 
660
 
661
  # ============================================================
662
- # Contribution grid helpers
663
  # ============================================================
664
- PALETTES = {
665
- "green": ["#0e4429", "#006d32", "#26a641", "#39d353"],
666
- "blue": ["#0a3069", "#0969da", "#54aeff", "#79c0ff"],
667
- "pink": ["#6e1f4d", "#bf3989", "#db61a2", "#f778ba"],
668
- "orange": ["#5f370e", "#a14d00", "#d97706", "#f59e0b"],
669
- "purple": ["#4c1d95", "#6d28d9", "#8b5cf6", "#c4b5fd"],
670
- "teal": ["#0f766e", "#0d9488", "#14b8a6", "#5eead4"],
671
- }
672
-
673
- TOOLTIP_SAFE_COLUMNS = 2
674
-
675
-
676
- def level_from_count(count: int) -> int:
677
- if count <= 0:
678
- return 0
679
- if count == 1:
680
- return 1
681
- if count <= 3:
682
- return 2
683
- if count <= 7:
684
- return 3
685
- return 4
686
-
687
-
688
- def level_color(palette_name: str, level: int) -> str:
689
- if level <= 0:
690
- return "var(--gh-empty-cell)"
691
- palette = PALETTES[palette_name]
692
- return palette[min(level - 1, len(palette) - 1)]
693
-
694
-
695
- def build_daily_count_map(df: pd.DataFrame):
696
- if df.empty:
697
- return {}
698
-
699
- counts = (
700
- df.copy()
701
- .assign(date=pd.to_datetime(df["date"]).dt.date, count=1)
702
- .groupby("date", as_index=False)["count"]
703
- .sum()
704
- )
705
- return {row["date"]: int(row["count"]) for _, row in counts.iterrows()}
706
-
707
-
708
- def get_calendar_bounds(year: int):
709
- start = pd.Timestamp(f"{year}-01-01")
710
- end = pd.Timestamp(f"{year}-12-31")
711
-
712
- grid_start = start - pd.Timedelta(days=start.dayofweek)
713
- grid_end = end + pd.Timedelta(days=(6 - end.dayofweek))
714
-
715
- all_days = pd.date_range(grid_start, grid_end, freq="D")
716
- num_weeks = len(all_days) // 7
717
- return start, end, grid_start, grid_end, all_days, num_weeks
718
-
719
-
720
- def month_positions_for_year(year: int, grid_start: pd.Timestamp):
721
- month_starts = pd.date_range(f"{year}-01-01", f"{year}-12-31", freq="MS")
722
- return [(d.strftime("%b"), int((d - grid_start).days // 7)) for d in month_starts]
723
-
724
-
725
- # ============================================================
726
- # HTML render helpers
727
- # ============================================================
728
- def render_metric_cards(
729
- total_activity: int,
730
- created_by_type: dict,
731
- repo_commit_counts_by_type: dict,
732
- selected_year: int,
733
- ):
734
- return f"""
735
- <div class="stats-grid">
736
- <div class="gh-card">
737
- <div class="gh-card-label">Total activity</div>
738
- <div class="gh-card-value">{total_activity}</div>
739
- <div class="gh-card-sub">Creations + repo contributions in {selected_year}</div>
740
- </div>
741
-
742
- <div class="gh-card">
743
- <div class="gh-card-label">🧠 Models created</div>
744
- <div class="gh-card-value">{created_by_type["model"]}</div>
745
- <div class="gh-card-sub">{repo_commit_counts_by_type["model"]} contributions on model repos</div>
746
- </div>
747
-
748
- <div class="gh-card">
749
- <div class="gh-card-label">📦 Datasets created</div>
750
- <div class="gh-card-value">{created_by_type["dataset"]}</div>
751
- <div class="gh-card-sub">{repo_commit_counts_by_type["dataset"]} contributions on dataset repos</div>
752
- </div>
753
-
754
- <div class="gh-card">
755
- <div class="gh-card-label">🚀 Spaces created</div>
756
- <div class="gh-card-value">{created_by_type["space"]}</div>
757
- <div class="gh-card-sub">{repo_commit_counts_by_type["space"]} contributions on space repos</div>
758
- </div>
759
- </div>
760
- """
761
-
762
-
763
- def render_status_badge(text: str):
764
- return f'<div class="gh-status">{text}</div>'
765
-
766
-
767
- def render_idle_context_banner(
768
  username: str,
769
  profile: gr.OAuthProfile | None,
 
770
  ):
771
  username = (username or "").strip()
772
- viewer = getattr(profile, "username", None) if profile else None
773
-
774
- if viewer:
775
- if not username or username.lower() == viewer.lower():
776
- return render_status_badge(
777
- f"Logged in as <b>{html.escape(viewer)}</b> · Fetch your activity or enter another username"
778
- )
779
- return render_status_badge(
780
- f"Logged in as <b>{html.escape(viewer)}</b> · Ready to fetch <b>{html.escape(username)}</b> · Public repos only"
781
- )
782
-
783
- if username:
784
- return render_status_badge(
785
- f"Not logged in · Ready to fetch <b>{html.escape(username)}</b> · Public repos only"
786
- )
787
-
788
- return render_status_badge("Not logged in · Enter a username to get started")
789
-
790
-
791
- def render_invalid_username_banner(username: str, error_text: str | None = None):
792
- username = (username or "").strip()
793
- message = error_text or f"Username or org '{username}' was not found."
794
- return render_status_badge(html.escape(message))
795
-
796
-
797
- def render_context_banner(app_state: dict | None, profile: gr.OAuthProfile | None):
798
- if not app_state or not app_state.get("username"):
799
- return render_idle_context_banner("", profile)
800
-
801
- username = app_state["username"]
802
- selected_year = int(app_state["selected_year"])
803
- is_own = bool(app_state.get("is_own_profile", False))
804
- can_toggle = bool(app_state.get("can_toggle_visibility", False))
805
- viewer = getattr(profile, "username", None) if profile else None
806
-
807
- parts = []
808
-
809
- if viewer:
810
- parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
811
- else:
812
- parts.append("Not logged in")
813
-
814
- if viewer and username.lower() == viewer.lower():
815
- parts.append("Viewing <b>your activity</b>")
816
- else:
817
- parts.append(f"Viewing <b>{html.escape(username)}</b>")
818
-
819
- parts.append(str(selected_year))
820
-
821
- if is_own and can_toggle:
822
- parts.append("Private repos available")
823
- else:
824
- parts.append("Public repos only")
825
-
826
- return render_status_badge(" · ".join(parts))
827
-
828
-
829
- def render_fetching_context_banner(
830
- username,
831
- selected_year,
832
- profile: gr.OAuthProfile | None,
833
- ):
834
- username = (username or "").strip()
835
- selected_year = int(selected_year)
836
- viewer = getattr(profile, "username", None) if profile else None
837
-
838
- if not username:
839
- return render_idle_context_banner("", profile)
840
-
841
- parts = []
842
-
843
- if viewer:
844
- parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
845
- else:
846
- parts.append("Not logged in")
847
-
848
- if viewer and username.lower() == viewer.lower():
849
- parts.append("Fetching <b>your activity</b>")
850
- parts.append(str(selected_year))
851
- parts.append("Checking public and private repos")
852
- else:
853
- parts.append(f"Fetching <b>{html.escape(username)}</b>")
854
- parts.append(str(selected_year))
855
- parts.append("Checking public repos")
856
-
857
- return render_status_badge(" · ".join(parts))
858
-
859
-
860
- def render_community_idle_banner(
861
- username,
862
- selected_year,
863
- profile: gr.OAuthProfile | None,
864
- ):
865
- username = (username or "").strip()
866
- selected_year = int(selected_year)
867
- viewer = getattr(profile, "username", None) if profile else None
868
-
869
- parts = []
870
- if viewer:
871
- parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
872
- else:
873
- parts.append("Not logged in")
874
-
875
- if not username:
876
- parts.append("Enter a username to fetch community activity")
877
- return render_status_badge(" · ".join(parts))
878
-
879
- if viewer and username.lower() == viewer.lower():
880
- parts.append("Fetch your community activity or enter another username")
881
- parts.append(str(selected_year))
882
- else:
883
- parts.append(f"Ready to fetch community activity for <b>{html.escape(username)}</b>")
884
- parts.append(str(selected_year))
885
-
886
- return render_status_badge(" · ".join(parts))
887
-
888
-
889
- def render_community_invalid_banner(username: str, error_text: str | None = None):
890
- username = (username or "").strip()
891
- message = error_text or f"Username or org '{username}' was not found."
892
- return render_status_badge(html.escape(message))
893
-
894
-
895
- def render_community_fetching_banner(
896
- username,
897
- selected_year,
898
- profile: gr.OAuthProfile | None,
899
- ):
900
- username = (username or "").strip()
901
- selected_year = int(selected_year)
902
- viewer = getattr(profile, "username", None) if profile else None
903
-
904
  if not username:
905
- return render_community_idle_banner("", selected_year, profile)
906
-
907
- parts = []
908
- if viewer:
909
- parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
910
- else:
911
- parts.append("Not logged in")
912
-
913
- if viewer and username.lower() == viewer.lower():
914
- parts.append("Fetching <b>your community activity</b>")
915
- else:
916
- parts.append(f"Fetching community activity for <b>{html.escape(username)}</b>")
917
-
918
- parts.append(str(selected_year))
919
- return render_status_badge(" · ".join(parts))
920
-
921
 
922
- def render_community_loaded_banner(
923
- community_state: dict | None,
924
- profile: gr.OAuthProfile | None,
925
- ):
926
- if not community_state or not community_state.get("username"):
927
- year = community_state.get("selected_year", datetime.now().year) if community_state else datetime.now().year
928
- return render_community_idle_banner("", year, profile)
929
-
930
- username = community_state["username"]
931
- selected_year = int(community_state["selected_year"])
932
- viewer = getattr(profile, "username", None) if profile else None
933
-
934
- parts = []
935
- if viewer:
936
- parts.append(f"Logged in as <b>{html.escape(viewer)}</b>")
937
- else:
938
- parts.append("Not logged in")
939
-
940
- if viewer and username.lower() == viewer.lower():
941
- parts.append("Viewing <b>your community activity</b>")
942
- else:
943
- parts.append(f"Viewing community activity for <b>{html.escape(username)}</b>")
944
-
945
- parts.append(str(selected_year))
946
- return render_status_badge(" · ".join(parts))
947
-
948
-
949
- def render_empty_chart(title: str):
950
- safe_title = html.escape(title)
951
- return f"""
952
- <div class="gh-chart-card">
953
- <div class="gh-chart-header">
954
- <div class="gh-chart-title">{safe_title}</div>
955
- </div>
956
- <div class="gh-empty">No activity found.</div>
957
- </div>
958
- """
959
-
960
-
961
- def render_contrib_chart(
962
- df: pd.DataFrame,
963
- year: int,
964
- title: str,
965
- palette_name: str = "green",
966
- subtitle: str | None = None,
967
- ):
968
- safe_title = html.escape(title)
969
- safe_subtitle = html.escape(subtitle) if subtitle else ""
970
-
971
- counts_map = build_daily_count_map(df)
972
- year_start, year_end, grid_start, _, all_days, num_weeks = get_calendar_bounds(year)
973
- months = month_positions_for_year(year, grid_start)
974
-
975
- padded_weeks = num_weeks + (2 * TOOLTIP_SAFE_COLUMNS)
976
-
977
- cells_html = []
978
- total = 0
979
-
980
- for day in all_days:
981
- day_date = day.date()
982
- in_year = year_start.date() <= day_date <= year_end.date()
983
- count = counts_map.get(day_date, 0) if in_year else 0
984
- total += count
985
-
986
- week = int((day - grid_start).days // 7)
987
- display_week = week + TOOLTIP_SAFE_COLUMNS
988
- dow = int(day.dayofweek)
989
- level = level_from_count(count)
990
- color = level_color(palette_name, level) if in_year else "transparent"
991
- label = f"{count} contribution{'s' if count != 1 else ''} on {day.strftime('%b %d, %Y')}"
992
-
993
- if in_year:
994
- classes = ["gh-cell"]
995
- if dow == 0:
996
- classes.append("gh-tooltip-bottom")
997
- if week <= 1:
998
- classes.append("gh-tooltip-right")
999
- elif week >= num_weeks - 2:
1000
- classes.append("gh-tooltip-left")
1001
-
1002
- class_attr = " ".join(classes)
1003
- safe_label = html.escape(label)
1004
-
1005
- cells_html.append(
1006
- f"""
1007
- <button
1008
- type="button"
1009
- class="{class_attr}"
1010
- style="grid-column:{display_week + 1}; grid-row:{dow + 1}; background:{color};"
1011
- aria-label="{safe_label}"
1012
- title="{safe_label}"
1013
- >
1014
- <span class="gh-tooltip">{safe_label}</span>
1015
- </button>
1016
- """
1017
- )
1018
- else:
1019
- cells_html.append(
1020
- f"""
1021
- <div
1022
- class="gh-cell gh-cell-outside"
1023
- style="grid-column:{display_week + 1}; grid-row:{dow + 1}; background:{color};"
1024
- aria-hidden="true"
1025
- ></div>
1026
- """
1027
- )
1028
-
1029
- month_labels = []
1030
- for label, pos in months:
1031
- display_pos = pos + TOOLTIP_SAFE_COLUMNS
1032
- month_labels.append(
1033
- f'<div class="gh-month-label" style="grid-column:{display_pos + 1};">{html.escape(label)}</div>'
1034
- )
1035
-
1036
- legend_colors = ["var(--gh-empty-cell)"] + PALETTES[palette_name]
1037
- legend_html = "".join(
1038
- f'<span class="gh-legend-cell" style="background:{c};"></span>' for c in legend_colors
1039
- )
1040
 
1041
- subtitle_html = f'<div class="gh-chart-subtitle">{safe_subtitle}</div>' if subtitle else ""
1042
-
1043
- return f"""
1044
- <div class="gh-chart-card">
1045
- <div class="gh-chart-header">
1046
- <div>
1047
- <div class="gh-chart-title">{safe_title}</div>
1048
- {subtitle_html}
1049
- </div>
1050
- <div class="gh-chart-total">{total} contributions</div>
1051
- </div>
1052
-
1053
- <div class="gh-chart-wrap">
1054
- <div class="gh-chart-inner">
1055
- <div class="gh-months" style="grid-template-columns: repeat({int(padded_weeks - 2)}, minmax(0, 1fr));">
1056
- {''.join(month_labels)}
1057
- </div>
1058
-
1059
- <div class="gh-grid-area">
1060
- <div class="gh-weekday weekday-mon">Mon</div>
1061
- <div class="gh-weekday weekday-wed">Wed</div>
1062
- <div class="gh-weekday weekday-fri">Fri</div>
1063
-
1064
- <div class="gh-grid" style="grid-template-columns: repeat({int(padded_weeks - 2)}, minmax(0, 1fr));">
1065
- {''.join(cells_html)}
1066
- </div>
1067
- </div>
1068
- </div>
1069
- </div>
1070
-
1071
- <div class="gh-legend">
1072
- <span class="gh-legend-text">Less</span>
1073
- {legend_html}
1074
- <span class="gh-legend-text">More</span>
1075
- </div>
1076
- </div>
1077
- """
1078
-
1079
-
1080
- def merge_dates(opened_dates: list, activity_dates: list, mode: str):
1081
- if mode == "opened":
1082
- return list(opened_dates)
1083
- if mode == "activity":
1084
- return list(activity_dates)
1085
- return list(opened_dates) + list(activity_dates)
1086
-
1087
-
1088
- def render_pr_combined_chart(community_state: dict | None, mode: str, username: str, year: int):
1089
- if not community_state or not community_state.get("fetched"):
1090
- return render_empty_chart("Pull Requests")
1091
 
1092
- opened = community_state["pr_opened"]["dates"]
1093
- activity = community_state["pr_activity"]["dates"]
1094
- merged = merge_dates(opened, activity, mode)
1095
- df = pd.DataFrame(merged, columns=["date"])
1096
-
1097
- subtitle = {
1098
- "opened": f"{len(opened)} PRs opened by {username} in {year}",
1099
- "activity": f"{len(activity)} PR follow-up events for {username} in {year}",
1100
- "both": f"{len(opened) + len(activity)} total PR events for {username} in {year}",
1101
- }[mode]
1102
-
1103
- return render_contrib_chart(
1104
- df,
1105
- year,
1106
- "Pull Requests",
1107
- palette_name="purple",
1108
- subtitle=subtitle,
1109
- )
1110
 
 
 
 
 
1111
 
1112
- def render_discussion_combined_chart(community_state: dict | None, mode: str, username: str, year: int):
1113
- if not community_state or not community_state.get("fetched"):
1114
- return render_empty_chart("Community Discussions")
1115
 
1116
- opened = community_state["thread_opened"]["dates"]
1117
- activity = community_state["discussion_activity"]["dates"]
1118
- merged = merge_dates(opened, activity, mode)
1119
- df = pd.DataFrame(merged, columns=["date"])
1120
-
1121
- subtitle = {
1122
- "opened": f"{len(opened)} threads opened by {username} in {year}",
1123
- "activity": f"{len(activity)} discussion follow-up events for {username} in {year}",
1124
- "both": f"{len(opened) + len(activity)} total discussion events for {username} in {year}",
1125
- }[mode]
1126
-
1127
- return render_contrib_chart(
1128
- df,
1129
- year,
1130
- "Community Discussions",
1131
- palette_name="teal",
1132
- subtitle=subtitle,
1133
- )
1134
 
1135
 
1136
  # ============================================================
@@ -2049,10 +1607,6 @@ button.gh-cell {
2049
  border-color: rgba(27, 31, 36, 0.06);
2050
  }
2051
 
2052
- /* =========================
2053
- Toggle radios (clean pills)
2054
- ========================= */
2055
-
2056
  #repo-visibility-toggle,
2057
  #pr-view-toggle,
2058
  #discussion-view-toggle {
 
98
  profile_username = getattr(profile, "username", None) if profile is not None else None
99
  profile_name = getattr(profile, "name", None) if profile is not None else None
100
 
 
101
  if profile_username and profile_username.lower() == username.lower():
102
  result = {
103
  "exists": True,
 
124
  )
125
 
126
  try:
 
127
  response = session.get(
128
  f"https://huggingface.co/{username}",
129
  timeout=15,
 
150
  return result
151
 
152
  except Exception:
 
153
  result = {
154
  "exists": True,
155
  "username": username,
 
656
 
657
 
658
  # ============================================================
659
+ # Name helpers
660
  # ============================================================
661
+ def resolve_display_name(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662
  username: str,
663
  profile: gr.OAuthProfile | None,
664
+ identity: dict | None = None,
665
  ):
666
  username = (username or "").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
667
  if not username:
668
+ return ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
669
 
670
+ profile_username = getattr(profile, "username", None) if profile is not None else None
671
+ profile_name = getattr(profile, "name", None) if profile is not None else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672
 
673
+ if profile_username and profile_username.lower() == username.lower():
674
+ if isinstance(profile_name, str) and profile_name.strip():
675
+ return f"{profile_name.strip()} (@{profile_username})"
676
+ return f"@{profile_username}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
677
 
678
+ if identity:
679
+ display_name = identity.get("display_name")
680
+ if isinstance(display_name, str) and display_name.strip():
681
+ return display_name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682
 
683
+ fullname = identity.get("fullname")
684
+ identity_username = identity.get("username") or username
685
+ if isinstance(fullname, str) and fullname.strip():
686
+ return f"{fullname.strip()} (@{identity_username})"
687
 
688
+ if isinstance(identity_username, str) and identity_username.strip():
689
+ return f"@{identity_username.strip()}"
 
690
 
691
+ return f"@{username}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
 
693
 
694
  # ============================================================
 
1607
  border-color: rgba(27, 31, 36, 0.06);
1608
  }
1609
 
 
 
 
 
1610
  #repo-visibility-toggle,
1611
  #pr-view-toggle,
1612
  #discussion-view-toggle {