Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1899 lines (1726 loc) · 97.4 KB
/
Copy pathapp.py
File metadata and controls
1899 lines (1726 loc) · 97.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from concurrent.futures import ThreadPoolExecutor
import polars as pl
from shiny.express import input, ui, render
from shiny import reactive
from shiny import session as shiny_session
from shiny import ui as sui
from shinywidgets import render_altair
from faicons import icon_svg
import altair as alt
import matplotlib.pyplot as plt
import seaborn as sns
import io
import json
import logging
import querychat as qc
from repoexplorer.analysis.type_distribution import plot_type_distribution_altair
from repoexplorer.analysis.language_distribution_by_type import plot_language_distribution_by_type_altair
from repoexplorer.analysis.language_distribution import plot_language_distribution_altair
from repoexplorer.analysis.license_distribution_by_type import plot_license_distribution_by_type_altair
from repoexplorer.analysis.license_distribution import plot_license_distribution_altair
from repoexplorer.analysis.feature_counts_per_type import plot_feature_counts_per_type_altair
from repoexplorer.analysis.feature_counts import plot_feature_counts_altair
from repoexplorer.analysis.feature_heatmap_per_stars import plot_feature_heatmap_by_star_bucket_altair
from repoexplorer.analysis.stars_distribution_bar import plot_stars_distribution_bar_altair
from repoexplorer.analysis.forks_distribution_bar import plot_forks_distribution_bar_altair
from repoexplorer.analysis.release_downloads_distribution_bar import plot_release_downloads_distribution_bar_altair
from repoexplorer.analysis.contributors_distribution_bar import plot_contributors_distribution_bar_altair
from repoexplorer.analysis.bus_factor_distribution_bar import plot_bus_factor_distribution_bar_altair
from repoexplorer.analysis.contributor_count_bucket_bar import plot_contributor_count_bucket_bar_altair
from dotenv import load_dotenv
load_dotenv()
# Global feature flag: enable/disable the chat tab and all chat behavior.
# By default this is False; set the environment variable ENABLE_CHAT=true
# (or edit this value) to turn the chat tab back on.
ENABLE_CHAT = False
# Global flag for where to read data:
# - "local" -> use parquet files under Data/parquet (default)
# - "remote" -> download reduced combined parquet files from S3 bucket
DATA = os.getenv("DATA")
if "OPENAI_MODEL" not in os.environ:
os.environ["OPENAI_MODEL"] = "gpt-5-mini"
# Data/parquet/{acronym}/repositories.parquet (case-insensitive acronym match)
# Optional fast path: Data/parquet/repositories_combined.parquet (single pre-merged file)
PARQUET_BASE = "Data/parquet"
# COMBINED_PARQUET = os.path.join(PARQUET_BASE, "repositories_combined_clean.parquet")
# SECURITY_PARQUET = os.path.join(PARQUET_BASE, "security_combined_clean.parquet")
# COMBINED_PARQUET = os.path.join(PARQUET_BASE, "repositories_reduced_combined_stars_gt_0.parquet")
# SECURITY_PARQUET = os.path.join(PARQUET_BASE, "security_reduced_combined_stars_gt_0.parquet")
# ORGANIZATIONS_PARQUET = "../repofinder/Data/parquet/organizations.parquet"
COMBINED_PARQUET = os.path.join(PARQUET_BASE, "repositories_reduced_affiliated.parquet")
SECURITY_PARQUET = os.path.join(PARQUET_BASE, "security_reduced_affiliated.parquet")
ORGANIZATIONS_PARQUET = os.path.join(PARQUET_BASE, "organizations_reduced_affiliated.parquet")
# CONTRIBUTORS_PARQUET = os.path.join(PARQUET_BASE, "contributors_combined_clean.parquet")
# COMMITS_PARQUET = os.path.join(PARQUET_BASE, "commits_combined_clean.parquet")
# Columns to load (fewer columns = faster load). "university" is added from config.
COLUMNS_TO_LOAD = [
"university", "id", "full_name", "owner", "license", "language", "html_url", "description", "fork", "created_at",
"updated_at", "pushed_at", "homepage", "size", "stargazers_count", "readme",
"watchers_count", "forks_count", "open_issues_count", "watchers", "organization", "release_downloads", "contributors",
"contributor_count", "bus_factor", "code_of_conduct_file", "contributing", "security_policy", "issue_templates",
"pull_request_template", "subscribers_count", "affiliation_prediction_gpt_5_mini", "type_prediction_gpt_5_mini",
]
ACRONYMS = [
"UCB", "UCI", "UCD", "UCLA", "UCM", "UCR", "UCSB", "UCSC", "UCSD", "UCSF",
"Biohub", "CMU", "ETH", "GWU", "Lero", "MGB", "MSU", "OSU", "RIT", "SLU",
"Syracuse", "TCD", "UGA", "SnT", "UCL", "UMich", "UVM", "UWMadison", "JHU",
"Georgia Tech", "UT Austin", "Stanford",
]
FEATURES = [
'description', 'readme', 'license', 'code_of_conduct_file',
'contributing', 'security_policy', 'issue_templates', 'pull_request_template'
]
# OpenSSF scorecard-style columns in ``df_security`` (joined to repos on ``html_url``).
# Display label, parquet column name (same as repository detail Security tab).
SECURITY_SCORECARD_METRICS = [
("Binary artifacts", "Binary_Artifacts"),
("Branch protection", "Branch_Protection"),
("CI tests", "CI_Tests"),
("CII Best Practices", "CII_Best_Practices"),
("Code review", "Code_Review"),
("Contributors", "Contributors"),
("Dangerous workflow", "Dangerous_Workflow"),
("Dependency update tool", "Dependency_Update_Tool"),
("Fuzzing", "Fuzzing"),
("License (scorecard)", "License"),
("Maintained", "Maintained"),
("Packaging", "Packaging"),
("Pinned dependencies", "Pinned_Dependencies"),
("SAST", "SAST"),
("Security policy (scorecard)", "Security_Policy"),
("Signed releases", "Signed_Releases"),
("Token permissions", "Token_Permissions"),
("Vulnerabilities", "Vulnerabilities"),
("Total score", "Total_Score"),
]
def _is_missing_scalar(v):
"""True for None or NaN (common null representations from Polars rows)."""
if v is None:
return True
try:
return v != v # NaN != NaN is True for float('nan')
except Exception:
return False
def _safe_markdown_text(v):
"""ui.markdown / textwrap require str; float NaN from pandas breaks deploy."""
if _is_missing_scalar(v):
return ""
return str(v)
def _safe_display_str(v, default="—"):
if _is_missing_scalar(v):
return default
return str(v)
def _safe_int_metric(v):
if _is_missing_scalar(v):
return "N/A"
try:
return str(int(float(v)))
except (ValueError, TypeError):
return "N/A"
def _format_thousands_approx(n) -> str:
"""Round counts for display (e.g. 52_000 -> '52K', 900 -> '900')."""
if _is_missing_scalar(n):
return "—"
try:
x = float(n)
except (TypeError, ValueError):
return "—"
if x != x: # NaN check
return "—"
x = int(round(x))
if x == 0:
return "0"
sign = ""
if x < 0:
sign = "-"
x = abs(x)
if x < 1000:
return f"{sign}{x}"
k = int(round(x / 1000.0))
return f"{sign}{k}K"
def _has_nonempty_text(v):
if _is_missing_scalar(v):
return False
s = str(v).strip()
return len(s) > 0 and s.lower() not in ("none", "nan", "<na>")
def _truthy_feature_flag(v):
"""For 0/1 or boolean presence columns; NaN is false."""
if _is_missing_scalar(v):
return False
if isinstance(v, bool):
return v
if isinstance(v, (int, float)):
try:
return float(v) != 0.0
except Exception:
return False
s = str(v).strip().lower()
return s not in ("", "none", "nan", "false", "0", "<na>")
def _normalize_license_column(df: pl.DataFrame) -> pl.DataFrame:
"""
Returns a new DataFrame with missing / empty licenses replaced with null.
"""
if df is None or df.is_empty() or "license" not in df.columns:
return df
return df.with_columns(
pl.when(
pl.col("license").is_null()
| pl.col("license").str.strip_chars().str.to_lowercase().is_in(
["", "none", "nan", "null", "<na>"]
)
)
.then(None)
.otherwise(pl.col("license").str.strip_chars())
.alias("license")
)
# Read data from public bucket
def read_parquet_from_s3_public(bucket_name, object_key, columns=None):
url = f"https://{bucket_name}.s3.amazonaws.com/{object_key}"
return pl.read_parquet(url, columns=columns)
def optimize_dtypes(df: pl.DataFrame) -> pl.DataFrame:
int_cols = [
"stargazers_count", "forks_count", "watchers_count",
"open_issues_count", "subscribers_count", "contributor_count",
"bus_factor", "release_downloads",
]
exprs = [
pl.col(c).cast(pl.Int32, strict=False)
for c in int_cols if c in df.columns
]
if "affiliation_prediction_gpt_5_mini" in df.columns:
exprs.append(pl.col("affiliation_prediction_gpt_5_mini").cast(pl.Float32, strict=False))
if exprs:
df = df.with_columns(exprs)
return df
#------------------------------------ Styling ---------------------------------------------
# Add CSS for hover tooltip
ui.tags.style("""
.repo-data-card {
position: relative;
}
.repo-data-card::after {
content: "Click a row to see repository details";
position: absolute;
top: 10px;
right: 10px;
background-color: rgba(0, 0, 0, 0.85);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
opacity: 0;
pointer-events: none;
transition: opacity 0.3s ease;
z-index: 1000;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
.repo-data-card:hover::after {
opacity: 1;
}
""")
ui.tags.style("""
.nav-pills .nav-link,
.nav-tabs .nav-link {
font-size: 0.9rem; /* adjust smaller/larger as you like */
}
""")
ui.tags.style("""
/* Sidebar filter labels: Prediction Threshold, University, Project Type, License, Language, etc. */
.bslib-sidebar .form-label,
.bslib-sidebar .control-label,
aside .control-label,
aside .form-label,
[data-bslib-sidebar] .control-label,
[data-bslib-sidebar] .form-label {
font-size: 0.85rem !important;
}
/* By id for sidebar labels (e.g. type-label, university label, etc.) */
#slider_threshold-label,
#university-label,
#type-label,
#license-label,
#language-label,
#slider_stars-label,
#slider_forks-label,
#slider_downloads-label {
font-size: 0.85rem !important;
}
""")
ui.tags.style("""
/* DataGrid column headers: allow \n in column names to wrap to multiple lines */
.shiny-data-grid thead th {
white-space: pre-line !important;
text-align: center !important;
}
""")
ui.tags.style("""
/* Altair / Vega chart hover tooltips */
#vg-tooltip-element,
#vg-tooltip-element table,
#vg-tooltip-element td,
#vg-tooltip-element th {
font-size: 15px !important;
line-height: 1.45 !important;
}
#vg-tooltip-element {
padding: 12px 16px !important;
}
""")
ui.tags.style("""
/* Sidebar: allow manual resize by dragging the right edge */
.bslib-sidebar,
aside[data-bslib-sidebar],
[data-bslib-sidebar] {
resize: horizontal;
overflow: auto;
min-width: 200px;
max-width: 60%;
}
""")
# Remove stray "True/False" that can appear from querychat/Shiny return values (This is hacky but leaving it for now)
ui.tags.script("""
(function() {
function isStrayBooleanText(text) {
var t = (text || "").trim();
return t === "True" || t === "False";
}
function removeBooleanNodes(node) {
if (!node) return;
if (node.nodeType === Node.TEXT_NODE && isStrayBooleanText(node.textContent)) {
node.parentNode.removeChild(node);
return;
}
if (node.nodeType === Node.ELEMENT_NODE && node.childNodes.length === 1 &&
node.childNodes[0].nodeType === Node.TEXT_NODE &&
isStrayBooleanText(node.childNodes[0].textContent)) {
node.parentNode.removeChild(node);
return;
}
for (var i = node.childNodes.length - 1; i >= 0; i--) {
removeBooleanNodes(node.childNodes[i]);
}
}
function run() {
removeBooleanNodes(document.body);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", run);
} else {
run();
}
setTimeout(run, 500);
})();
// (No custom \"Viewing rows X through Y\" logic needed for universities now that we use DataGrid)
""")
#------------------------------------ Load the data ---------------------------------------------
# There is two ways to load the data:
# 1. Fast path: single pre-merged parquet
# 2. Slow path: load each parquet file individually and merge them together
# def _load_one_acronym(acronym: str, parquet_dir: str):
# """
# Load a repository parquet file and add the university name.
# Parameters
# ----------
# acronym : str
# University acronym (for example, ``"UCB"``).
# parquet_dir : str
# Subdirectory under ``PARQUET_BASE`` that contains ``repositories.parquet``.
# Returns
# -------
# pandas.DataFrame or None
# DataFrame with the requested columns and a ``"university"`` column,
# or ``None`` if the parquet file is missing or cannot be read.
# """
# repo_path = os.path.join(PARQUET_BASE, parquet_dir, "repositories.parquet")
# if not os.path.isfile(repo_path):
# return None
# try:
# # Read only needed columns for faster I/O
# df = pd.read_parquet(repo_path, columns=[c for c in COLUMNS_TO_LOAD if c != "university"])
# except Exception:
# df = pd.read_parquet(repo_path)
# df = df[[c for c in COLUMNS_TO_LOAD if c in df.columns and c != "university"]]
# config_file = f"config/config_{acronym.replace(' ', '_')}.json"
# if os.path.isfile(config_file):
# try:
# with open(config_file, encoding="utf-8") as f:
# df["university"] = json.load(f).get("UNIVERSITY_NAME", acronym)
# except Exception:
# df["university"] = acronym
# else:
# df["university"] = acronym
# return df
if DATA == "remote":
# Usage Shiny app
_df_pl = read_parquet_from_s3_public("repoexplorer-data", "repositories_reduced_affiliated.parquet", columns=COLUMNS_TO_LOAD)
_df_security_pl = read_parquet_from_s3_public("repoexplorer-data", "security_reduced_affiliated.parquet")
_df_organizations_pl = read_parquet_from_s3_public("repoexplorer-data", "organizations_reduced_affiliated.parquet")
else:
# Load main repositories table
_df_pl = pl.read_parquet(COMBINED_PARQUET, columns=COLUMNS_TO_LOAD)
if "university" not in _df_pl.columns:
_df_pl = _df_pl.with_columns(pl.lit("Unknown").alias("university"))
_df_security_pl = pl.DataFrame()
if os.path.isfile(SECURITY_PARQUET):
try:
_df_security_pl = pl.read_parquet(SECURITY_PARQUET)
except Exception:
logging.exception("Failed to load security parquet %s", SECURITY_PARQUET)
_df_security_pl = pl.DataFrame()
_df_organizations_pl = pl.DataFrame()
if os.path.isfile(ORGANIZATIONS_PARQUET):
try:
_df_organizations_pl = pl.read_parquet(ORGANIZATIONS_PARQUET)
except Exception:
logging.exception("Failed to load organizations parquet %s", ORGANIZATIONS_PARQUET)
_df_organizations_pl = pl.DataFrame()
_df_pl = optimize_dtypes(_df_pl)
df = _df_pl
df_security = _df_security_pl
df_organizations = _df_organizations_pl
del _df_pl, _df_security_pl, _df_organizations_pl
# # Load contributors table
# df_contributors = pd.DataFrame()
# if os.path.isfile(CONTRIBUTORS_PARQUET):
# try:
# df_contributors = pd.read_parquet(CONTRIBUTORS_PARQUET)
# except Exception:
# logging.exception("Failed to load contributors parquet %s", CONTRIBUTORS_PARQUET)
# df_contributors = pd.DataFrame()
# Load commits (all_combined) table
# df_commits = pd.DataFrame()
# if os.path.isfile(COMMITS_PARQUET):
# try:
# df_commits = pd.read_parquet(COMMITS_PARQUET)
# except Exception:
# logging.exception("Failed to load commits parquet %s", COMMITS_PARQUET)
# df_commits = pd.DataFrame()
df = _normalize_license_column(df)
# =============================================== App UI ==========================================
ui.page_opts(title="Open Source Repository Browser", fillable=True)
# ======================================== Filter options =========================================
licenses = df["license"].drop_nulls().unique().to_list() if "license" in df.columns else []
languages = df["language"].drop_nulls().unique().to_list() if "language" in df.columns else []
universities = df["university"].drop_nulls().unique().to_list() if "university" in df.columns else []
types = df["type_prediction_gpt_5_mini"].drop_nulls().unique().to_list() if "type_prediction_gpt_5_mini" in df.columns else []
# Organizations filter options
_org_unis = (
sorted(df_organizations["university"].drop_nulls().unique().to_list())
if not df_organizations.is_empty() and "university" in df_organizations.columns
else []
)
# Subset with default prediction threshold (>= 0.8) for sliders and for chat
_df_08 = df.filter(pl.col("affiliation_prediction_gpt_5_mini") >= 0.8)
_m = _df_08["stargazers_count"].max() if not _df_08.is_empty() else None
_slider_max_stars = int(_m) if _m is not None else 5000
_m = _df_08["forks_count"].max() if not _df_08.is_empty() else None
_slider_max_forks = int(_m) if _m is not None else 100
_m = _df_08["release_downloads"].max() if not _df_08.is_empty() else None
_slider_max_downloads = int(_m) if _m is not None else 1000
# ------------------------------------ QueryChat Config -------------------------------------------
if ENABLE_CHAT:
_greeting_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "greeting.md")
with open(_greeting_path, encoding="utf-8") as _f:
_greeting_md = _f.read()
querychat_config = qc.init(
data_source=_df_08,
table_name="Repositories",
greeting=_greeting_md,
)
else:
querychat_config = None
# Assign chat server in a function so its return value is not rendered as "True" in the main panel
chat = None
if ENABLE_CHAT:
def _init_chat_server():
global chat
chat = qc.server("chat", querychat_config)
_init_chat_server()
# Absorb any stray top-level return value so "True" does not render in main panel
ui.HTML("")
# Reset all filters when button is clicked
@reactive.effect
@reactive.event(input.reset_filters)
def reset_all_filters():
ui.update_selectize("university", selected=[])
ui.update_selectize("type", selected=[])
ui.update_selectize("license", selected=[])
ui.update_selectize("language", selected=[])
ui.update_slider("slider_stars", value=[0, _slider_max_stars])
ui.update_slider("slider_forks", value=[0, _slider_max_forks])
ui.update_slider("slider_downloads", value=[0, _slider_max_downloads])
ui.update_text("table_search", value="")
if ENABLE_CHAT:
try:
sess = shiny_session.get_current_session()
if sess is not None:
sess.send_input_message("chat-message", {"value": "reset all filters"})
except Exception:
pass
# ======================================== Constants & shared resources ============================
_OVERVIEW_TITLE_SIZE = 14
_OVERVIEW_LABEL_SIZE = 11
_OVERVIEW_TEXT_SIZE = 10
_OVERVIEW_BAR_PCT_SIZE = 11
_OVERVIEW_PIE_PCT_SIZE = 11
_TABLE_FONT_SIZE = "14px"
ICONS = {
"repos": icon_svg("code-branch"),
"contributors": icon_svg("users"),
"active": icon_svg("clock"),
"openssf": icon_svg("shield-halved"),
"busfactor": icon_svg("bus"),
"license": icon_svg("id-card"),
"stars": icon_svg("star"),
"forks": icon_svg("code-fork"),
"downloads": icon_svg("download"),
"organizations": icon_svg("building"),
"link": icon_svg("link"),
"description": icon_svg("pen-to-square"),
"email": icon_svg("envelope"),
}
_about_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "about.md")
with open(_about_path, encoding="utf-8") as _f:
_about_md = _f.read()
# ======================================== Main UI ================================================
with ui.navset_pill(id="main_tab", selected="Repositories"):
# ============================= ABOUT TAB =====================================================
with ui.nav_panel("About"):
with ui.card():
ui.markdown(_about_md)
# ============================= REPOSITORIES TAB ===============================================
with ui.nav_panel("Repositories"):
with ui.layout_sidebar(fillable=True):
with ui.sidebar(open="open", bg="#f8f8f8", width="250px"):
with ui.navset_pill(id="side_tab"):
with ui.nav_panel("Manual Filters"):
ui.input_slider("slider_threshold", "Prediction Threshold", min=0.5, max=1, value=[0.8, 1])
ui.input_selectize("university", "University:", universities, multiple=True)
ui.input_selectize("type", "Project Type:", types, multiple=True)
ui.input_selectize("license", "License:", licenses, multiple=True)
ui.input_selectize("language", "Language:", languages, multiple=True)
ui.input_slider("slider_stars", "# Stars", min=0, max=_slider_max_stars, value=[0, _slider_max_stars])
ui.input_slider("slider_forks", "# Forks", min=0, max=_slider_max_forks, value=[0, _slider_max_forks])
ui.input_slider("slider_downloads", "# Release Downloads", min=0, max=_slider_max_downloads, value=[0, _slider_max_downloads])
if ENABLE_CHAT:
with ui.nav_panel("Chat Bot"):
qc.ui("chat")
ui.br()
ui.br()
ui.input_action_button("reset_filters", "Reset All Filters", class_="btn-danger")
ui.HTML("")
# ---- Inner tabs ----
with ui.navset_tab(id="repo_tab", selected="Overview"):
# ---- Overview ----
with ui.nav_panel("Overview"):
# University table + value boxes (2x2 grid)
with ui.layout_columns(col_widths=(6, 6)):
with ui.card():
ui.markdown("**Repositories per University**")
@render.data_frame
def university_table():
data = filtered_df()
if "university" not in data.columns or data.is_empty():
return render.DataGrid(pl.DataFrame({"University": [], "Count": []}))
university_counts = (
data.group_by("university")
.agg(pl.len().alias("Count"))
.sort("Count", descending=True)
.rename({"university": "University"})
)
return render.DataGrid(
university_counts,
width="100%",
height="400px",
styles=[
{
"location": "body",
"cols": [0],
"style": {"minWidth": "70%", "width": "70%"},
},
{
"location": "body",
"cols": [1],
"style": {"minWidth": "30%", "width": "30%", "textAlign": "right"},
},
],
)
with ui.div():
with ui.layout_columns(col_widths=(6, 6)):
with ui.value_box(showcase=ICONS["repos"]):
"Total repositories"
@render.express
def total_repos():
len(filtered_df())
with ui.value_box(showcase=ICONS["contributors"]):
"Total contributors"
@render.express
def total_contributors():
data = filtered_df()
if "contributor_count" not in data.columns:
"—"
else:
s = data["contributor_count"].cast(pl.Float64, strict=False).drop_nulls()
int(s.sum()) if len(s) > 0 else 0
with ui.layout_columns(col_widths=(6, 6)):
with ui.value_box(showcase=ICONS["license"]):
"Repositories with a license"
@render.express
def pct_with_license():
data = filtered_df()
if "license" not in data.columns:
"—"
else:
total = data.height
if total == 0:
"0%"
else:
with_license = data["license"].is_not_null().sum()
pct = 100.0 * with_license / total
f"{pct:.1f}%"
with ui.value_box(showcase=ICONS["busfactor"]):
"Average bus factor"
@render.express
def avg_busfactor():
data = filtered_df()
col = "bus_factor"
if col not in data.columns:
"—"
else:
v = data[col].cast(pl.Float64, strict=False).mean()
f"{v:.1f}" if v is not None else "—"
# Type distribution + Community files presence
with ui.layout_columns(col_widths=(6, 6)):
with ui.card():
@render_altair
def plot_type():
return plot_type_distribution_altair(
filtered_df(),
acronym="",
label_size=_OVERVIEW_LABEL_SIZE,
title_size=_OVERVIEW_TITLE_SIZE,
textprops=_OVERVIEW_PIE_PCT_SIZE,
)
with ui.card():
@render_altair
def plot_files_combined():
return plot_feature_counts_altair(
filtered_df(),
FEATURES,
acronym="",
label_size=_OVERVIEW_LABEL_SIZE,
title_size=_OVERVIEW_TITLE_SIZE,
textprops=_OVERVIEW_BAR_PCT_SIZE,
)
# Language + License distributions
with ui.layout_columns(col_widths=(6, 6)):
with ui.card():
@render_altair
def plot_language_combined():
return plot_language_distribution_altair(
filtered_df(),
acronym="",
label_size=_OVERVIEW_LABEL_SIZE,
title_size=_OVERVIEW_TITLE_SIZE,
textprops=_OVERVIEW_PIE_PCT_SIZE,
top_n=8,
)
with ui.card():
@render_altair
def plot_license_combined():
return plot_license_distribution_altair(
filtered_df(),
acronym="",
label_size=_OVERVIEW_LABEL_SIZE,
title_size=_OVERVIEW_TITLE_SIZE,
textprops=_OVERVIEW_PIE_PCT_SIZE,
top_n=8,
)
with ui.layout_columns(col_widths=(6, 6)):
with ui.card():
@render_altair
def plot_language():
return plot_language_distribution_by_type_altair(
filtered_df(),
acronym="",
label_size=_OVERVIEW_LABEL_SIZE,
title_size=_OVERVIEW_TITLE_SIZE,
textprops=_OVERVIEW_BAR_PCT_SIZE,
top_n=8,
)
with ui.card():
@render_altair
def plot_license():
return plot_license_distribution_by_type_altair(
filtered_df(),
acronym="",
label_size=_OVERVIEW_LABEL_SIZE,
title_size=_OVERVIEW_TITLE_SIZE,
textprops=_OVERVIEW_BAR_PCT_SIZE,
top_n=8,
)
# ---- Browse (repository table + detail) ----
with ui.nav_panel("Browse"):
with ui.card(class_="repo-data-card"):
ui.tags.div(
ui.tags.div(
ui.input_text(
"table_search",
"Search",
placeholder="Search repositories...",
width="100%",
),
style="flex: 1; min-width: 220px;",
),
)
@render.data_frame
def display_df():
data = repositories_table_df()
return render.DataGrid(
data,
height="500px",
selection_mode="row",
)
@render.download(
filename=lambda: f"repositories_{__import__('datetime').datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
)
def download_repositories_csv():
out_df = repositories_table_df()
buf = io.BytesIO()
out_df.write_csv(buf)
buf.seek(0)
yield buf.getvalue()
with ui.card():
@render.ui
def show_clicked():
selected_rows = display_df.cell_selection()["rows"]
if not selected_rows:
return ""
# Row position in the grid matches repositories_table_df (search + column drops).
view = repositories_table_df()
row_pos = selected_rows[0]
# Use html_url as key to look up the full row in filtered_df()
_view_row = view.row(row_pos, named=True)
_row_url = _view_row.get("html_url")
_full_matches = filtered_df().filter(pl.col("html_url") == _row_url) if _row_url else pl.DataFrame()
selected = _full_matches.row(0, named=True) if not _full_matches.is_empty() else _view_row
_readme_md = _safe_markdown_text(selected.get("readme"))
_contributing_md = _safe_markdown_text(selected.get("contributing"))
_security_policy_md = _safe_markdown_text(selected.get("security_policy"))
# Match security metrics row (from security_combined_clean.parquet) by html_url
sec_row = None
if not df_security.is_empty() and "html_url" in df_security.columns:
_matches = df_security.filter(pl.col("html_url") == selected.get("html_url"))
if not _matches.is_empty():
sec_row = _matches.row(0, named=True)
# Two-column layout:
# - Left column: Overview / Impact / Health / Security
# - Right column: README / Contributing / Security Policy
return sui.layout_columns(
ui.div(
sui.navset_tab(
sui.nav_panel(
"Overview",
ui.p(
ui.tags.span("Name: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
_safe_display_str(selected.get("full_name")),
),
ui.p(
ui.tags.span("University: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
_safe_display_str(selected.get("university"), "Unknown"),
),
ui.p(
ui.tags.span("License: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
_safe_display_str(selected.get("license")),
),
ui.p(
ui.tags.span("Language: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
_safe_display_str(selected.get("language")),
),
ui.p(
ui.tags.span("Project Type: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
_safe_display_str(selected.get("type_prediction_gpt_5_mini")),
),
ui.p(
ui.tags.span("Description: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
_safe_display_str(selected.get("description")),
),
ui.p(
ui.tags.span("URL: ", style="color: var(--bs-primary, #0d6efd); font-weight: bold;"),
(
ui.tags.a(
_safe_display_str(selected.get("html_url"), ""),
href=_safe_display_str(selected.get("html_url"), ""),
target="_blank",
)
if _has_nonempty_text(selected.get("html_url"))
else "—"
),
),
),
sui.nav_panel(
"Impact",
ui.tags.table(
ui.tags.tr(
ui.tags.th(
"Metric",
style=(
"padding-right: 6px; text-align: left; "
"font-weight: bold;"
),
),
ui.tags.th("Value", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Number of stars",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td(_safe_int_metric(selected.get("stargazers_count")), style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Number of downloads",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td(_safe_int_metric(selected.get("release_downloads")), style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Number of forks",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td(_safe_int_metric(selected.get("forks_count")), style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Number of issues",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td(_safe_int_metric(selected.get("open_issues_count")), style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Number of contributors",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td(_safe_int_metric(selected.get("contributor_count")), style="text-align: center;"),
),
style="width: 100%; border-collapse: collapse;",
),
),
sui.nav_panel(
"Health",
ui.tags.table(
ui.tags.tr(
ui.tags.th(
"Health check",
style=(
"padding-right: 6px; text-align: left; "
"font-weight: bold;"
),
),
ui.tags.th("Present", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Description",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td("✅" if _has_nonempty_text(selected.get("description")) else "✗", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"README",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td("✅" if _has_nonempty_text(selected.get("readme")) else "✗", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Contributing guide",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td("✅" if _has_nonempty_text(selected.get("contributing")) else "✗", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Code of conduct",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td("✅" if _truthy_feature_flag(selected.get("code_of_conduct_file")) else "✗", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Security policy",
style=(
"padding-right: 6px; "
"color: var(--bs-primary, #0d6efd); font-weight: bold;"
),
),
ui.tags.td("✅" if _has_nonempty_text(selected.get("security_policy")) else "✗", style="text-align: center;"),
),
ui.tags.tr(
ui.tags.td(
"Issue templates",
style=(