Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion 8Knot/cache_manager/cache_facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
from psycopg2.extras import execute_values
from psycopg2 import sql as pg_sql
import pandas as pd
import polars as pl
from sqlalchemy.exc import DBAPIError
from db_manager.collectoss_manager import CollectOSSManager

# requires relative import syntax "import .cx_common" because
# other files importing cache_facade need to know how to resolve
# .cx_common- interpreter is invoked at a higher level, so relative
# import required.
from .cx_common import cache_cx_string
from .cx_common import cache_cx_string, cache_uri

# The engine is opened lazily in the worker process and reused between tasks.
collectoss = CollectOSSManager(worker_query=True)
Expand Down Expand Up @@ -208,3 +209,24 @@ def retrieve_from_cache(
)
logging.warning(f"{tablename} - DATA LOADED - {df.shape} rows,cols")
return df


def retrieve_from_cache_pl(
tablename: str,
repolist: list[int],
) -> pl.DataFrame:
"""
For a given table in cache, get all results with a matching repo_id
directly as a Polars dataframe.
"""
# repo ids are bound as a parameter; a table name cannot be, so it must be a plain identifier
if not tablename.isidentifier():
raise ValueError(f"invalid cache table name: {tablename!r}")
query = f"SELECT * FROM {tablename} t WHERE t.repo_id = ANY($1::int[])" # nosec B608

logging.warning(f"{tablename} - LOADING DATA FROM CACHE")
df = pl.read_database_uri(
query, cache_uri, engine="adbc", execute_options={"parameters": ([int(r) for r in repolist],)}
)
logging.warning(f"{tablename} - DATA LOADED - {df.shape} rows,cols")
return df
3 changes: 3 additions & 0 deletions 8Knot/cache_manager/cx_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import os
import time
from urllib.parse import quote

from psycopg2.extensions import make_dsn

Expand Down Expand Up @@ -36,3 +37,5 @@
host=env_host,
port=env_port,
)

cache_uri = f"postgresql://{quote(env_user, safe='')}:{quote(env_password, safe='')}@{env_host}:{env_port}/{env_dbname}"
62 changes: 18 additions & 44 deletions 8Knot/pages/affiliation/visualizations/commit_domains.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import pandas as pd
import polars as pl
import logging
from dateutil.relativedelta import * # type: ignore
import plotly.express as px
Expand All @@ -10,6 +11,7 @@
from pages.utils.job_utils import nodata_graph, POLL_INTERVAL_MS
import time
import datetime as dt
import pages.utils.preprocessing_utils as preproc_utils
import cache_manager.cache_facade as cf
from components.visualization import VisualizationAIO

Expand Down Expand Up @@ -86,68 +88,40 @@ def commit_domains_graph(repolist, num, start_date, end_date):
logging.warning(f"{VIZ_ID}- START")

# GET ALL DATA FROM POSTGRES CACHE
df = cf.retrieve_from_cache(
df = cf.retrieve_from_cache_pl(
tablename=cmq.__name__,
repolist=repolist,
)

# test if there is data
if df.empty:
if df.is_empty():
logging.warning(f"{VIZ_ID} - NO DATA AVAILABLE")
return nodata_graph

# function for all data pre processing, COULD HAVE ADDITIONAL INPUTS AND OUTPUTS
df = process_data(df, num, start_date, end_date)

fig = create_figure(df)
fig = create_figure(df.to_pandas())

logging.warning(f"{VIZ_ID} - END - {time.perf_counter() - start}")
return fig


def process_data(df: pd.DataFrame, num, start_date, end_date):
# TODO: create docstring

# convert to datetime objects rather than strings
df["author_timestamp"] = pd.to_datetime(df["author_timestamp"], utc=True)

# order values chronologically by author_timestamp date earliest to latest
df = df.sort_values(by="author_timestamp", axis=0, ascending=True)

# filter values based on date picker
if start_date is not None:
df = df[df.author_timestamp >= start_date]
if end_date is not None:
df = df[df.author_timestamp <= end_date]

# creates list of emails for each contribution and flattens list result
emails = df.author_email.tolist()

# remove any entries not in email format and put all emails in lowercase
emails = [x.lower() for x in emails if "@" in x]

# creates list of email domains from the emails list
email_domains = [x[x.rindex("@") + 1 :] for x in emails]

# creates df of domains and counts
df = pd.DataFrame(email_domains, columns=["domains"]).value_counts().to_frame().reset_index()

df = df.rename(columns={"count": "occurrences"})

# changes the name of the company if under a certain threshold
df.loc[df["occurrences"] <= num, "domains"] = "Other"

# groups others together for final counts
df = (
df.groupby(by="domains")["occurrences"]
.sum()
.reset_index()
.sort_values(by=["occurrences"], ascending=False)
.reset_index(drop=True)
def process_data(df: pl.DataFrame, num, start_date, end_date):
df = preproc_utils.filter_date_range(df, "author_timestamp", start_date, end_date)
return (
df.select(pl.col("author_email").str.extract(r"@([^@]*)$").str.to_lowercase().alias("domains"))
.drop_nulls()
.group_by("domains")
.agg(pl.len().cast(pl.Int64).alias("occurrences"))
.with_columns(
pl.when(pl.col("occurrences") <= num).then(pl.lit("Other")).otherwise(pl.col("domains")).alias("domains")
)
.group_by("domains")
.agg(pl.col("occurrences").sum())
.sort(["occurrences", "domains"], descending=[True, False])
)

return df


def create_figure(df: pd.DataFrame):
# graph generation
Expand Down
44 changes: 17 additions & 27 deletions 8Knot/pages/contributions/visualizations/commits_over_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
from dash import callback
from dash.dependencies import Input, Output
import pandas as pd
import polars as pl
import logging
import plotly.express as px
from pages.utils.graph_utils import get_graph_time_values, baby_blue
from queries.commits_query import commits_query as cmq
from pages.utils.job_utils import nodata_graph, POLL_INTERVAL_MS
import time
import pages.utils.preprocessing_utils as preproc_utils
import cache_manager.cache_facade as cf
from components.visualization import VisualizationAIO

Expand Down Expand Up @@ -77,51 +79,39 @@ def commits_over_time_graph(repolist, interval):
logging.warning("COMMITS_OVER_TIME_VIZ - START")

# GET ALL DATA FROM POSTGRES CACHE
df = cf.retrieve_from_cache(
df = cf.retrieve_from_cache_pl(
tablename=cmq.__name__,
repolist=repolist,
)

# test if there is data
if df.empty:
if df.is_empty():
logging.warning("COMMITS OVER TIME - NO DATA AVAILABLE")
return nodata_graph

# function for all data pre processing
df_created = process_data(df, interval)

fig = create_figure(df_created, interval)
fig = create_figure(df_created.to_pandas(), interval)

logging.warning(f"COMMITS_OVER_TIME_VIZ - END - {time.perf_counter() - start}")
return fig


def process_data(df: pd.DataFrame, interval):
# convert to datetime objects with consistent column name
# incoming value should be a posix integer.
df["author_date"] = pd.to_datetime(df["author_date"], utc=True)
df.rename(columns={"author_date": "created_at"}, inplace=True)

# variable to slice on to handle weekly period edge case
period_slice = None
if interval == "W":
# this is to slice the extra period information that comes with the weekly case
period_slice = 10

# get the count of commits in the desired interval in pandas period format, sort index to order entries
df_created = (
df.groupby(by=df.created_at.dt.to_period(interval))["commit_hash"]
.nunique()
.reset_index()
.rename(columns={"created_at": "Date"})
def process_data(df: pl.DataFrame, interval):
every = preproc_utils.TRUNCATE_EVERY[interval]
return (
df.select(
pl.col("author_date").str.to_date("%Y-%m-%d").dt.truncate(every).alias("Date"),
pl.col("commit_hash"),
)
.drop_nulls("Date")
.group_by("Date")
.agg(pl.col("commit_hash").drop_nulls().n_unique().cast(pl.Int64))
.with_columns(pl.col("Date").cast(pl.Datetime("ns")))
.sort("Date")
)

# converts date column to a datetime object, converts to string first to handle period information
# the period slice is to handle weekly corner case
df_created["Date"] = pd.to_datetime(df_created["Date"].astype(str).str[:period_slice])

return df_created


def create_figure(df_created: pd.DataFrame, interval):
# time values for graph
Expand Down
71 changes: 42 additions & 29 deletions 8Knot/pages/contributors/visualizations/contrib_activity_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import pandas as pd
import polars as pl
import logging
from dateutil.relativedelta import * # type: ignore
import plotly.express as px
Expand Down Expand Up @@ -73,56 +74,68 @@ def contrib_activity_cycle_graph(repolist, interval):
logging.warning(f"{VIZ_ID}- START")

# GET ALL DATA FROM POSTGRES CACHE
df = cf.retrieve_from_cache(
df = cf.retrieve_from_cache_pl(
tablename=cmq.__name__,
repolist=repolist,
)

# test if there is data
if df.empty:
if df.is_empty():
logging.warning(f"{VIZ_ID} - NO DATA AVAILABLE")
return nodata_graph

# function for all data pre processing, COULD HAVE ADDITIONAL INPUTS AND OUTPUTS
df = process_data(df, interval)

fig = create_figure(df, interval)
fig = create_figure(to_figure_series(df), interval)

logging.warning(f"{VIZ_ID} - END - {time.perf_counter() - start}")
return fig


def process_data(df: pd.DataFrame, interval):
# for this usecase we want the datetimes to be in their local values
# tricking pandas to keep local values when UTC conversion is required for to_datetime
df["author_timestamp"] = df["author_timestamp"].astype("str").str[:-6]
df["committer_timestamp"] = df["committer_timestamp"].astype("str").str[:-6]

# convert to datetime objects rather than strings
df["author_timestamp"] = pd.to_datetime(df["author_timestamp"], utc=True)
df["committer_timestamp"] = pd.to_datetime(df["committer_timestamp"], utc=True)
# removes duplicate values when the author and committer is the same
df.loc[df["author_timestamp"] == df["committer_timestamp"], "author_timestamp"] = None

df_final = pd.DataFrame()

def process_data(df: pl.DataFrame, interval):
# count a commit once when author and committer times fall in the same hour
author_hour = pl.col("author_timestamp").str.slice(0, 13)
committer_hour = pl.col("committer_timestamp").str.slice(0, 13)
hour_text = df.select(
pl.when(author_hour == committer_hour).then(None).otherwise(author_hour).alias("author_hour"),
committer_hour.alias("committer_hour"),
)
if interval == "H":
# combine the hour values for author and committer
hour = pd.concat([df["author_timestamp"].dt.hour, df["committer_timestamp"].dt.hour])
df_hour = pd.DataFrame(hour, columns=["Hour"])
df_final = df_hour.groupby(["Hour"])["Hour"].count()
else:
# combine the weekday values for author and committer
weekday = pd.concat(
hours = (
pl.concat(
[
hour_text["author_hour"].str.slice(11, 2).cast(pl.Int8),
hour_text["committer_hour"].str.slice(11, 2).cast(pl.Int8),
]
)
.drop_nulls()
.alias("Hour")
)
return hours.to_frame().group_by("Hour").agg(pl.len().cast(pl.Int64).alias("count")).sort("Hour")
days = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday"}
weekdays = (
pl.concat(
[
df["author_timestamp"].dt.day_name(),
df["committer_timestamp"].dt.day_name(),
hour_text["author_hour"].str.slice(0, 10).str.to_date("%Y-%m-%d").dt.weekday(),
hour_text["committer_hour"].str.slice(0, 10).str.to_date("%Y-%m-%d").dt.weekday(),
]
)
df_weekday = pd.DataFrame(weekday, columns=["Weekday"])
df_final = df_weekday.groupby(["Weekday"])["Weekday"].count()
.drop_nulls()
.alias("Weekday")
)
return (
weekdays.to_frame()
.group_by("Weekday")
.agg(pl.len().cast(pl.Int64).alias("count"))
.with_columns(pl.col("Weekday").replace_strict(days, return_dtype=pl.String))
.sort("Weekday")
)


return df_final
def to_figure_series(df: pl.DataFrame) -> pd.Series:
column = df.columns[0]
return df.to_pandas().set_index(column)["count"].rename(column)


def create_figure(df: pd.DataFrame, interval):
Expand Down
Loading
Loading