aboutsummaryrefslogtreecommitdiffstats
path: root/app.py
blob: 2bbf4fe590e741637e60c512d3a5e472d0757e91 (plain)
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
# Copyright (C) 2021 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# You may use this file under the terms of the CC0 license.
# See the file LICENSE.CC0 from this package for details.

from pathlib import Path

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import requests
import os
import io
import sys
import zipfile
import subprocess
from dash.dependencies import Input, Output

external_stylesheets = [
    {
        "href": "https://codepen.io/chriddyp/pen/bWLwgP.css",
        "rel": "stylesheet",
    },
    {
        "href": "https://fonts.googleapis.com/css2?" "family=Titillium+Web&display=swap",
        "rel": "stylesheet",
    },
]

# Main application
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
app.title = "The Qt Project"


def partially_hide(x):
    words = []
    x_split = x.split()
    len_split = len(x_split)

    for i, name in enumerate(x_split):
        # Replace with dots
        # filled = '.' * (len(name) - 1)
        # words.append(f'{name[0]}{filled}')

        # Use first letter
        # words.append(name[0])

        # User F. Lastime
        if i != len_split - 1:
            words.append(f"{name[0]}.")
        else:
            words.append(name)
    return " ".join(words)


def get_domain_chart_data(df):
    d = df.groupby("domain")["domain"].count()
    d = d.to_frame()
    d.rename(columns={"domain": "domain_count"}, inplace=True)
    d = d.sort_values(by="domain_count", ascending=False)
    TOP = 5
    d3 = d[:TOP].copy()
    d3.loc["Other"] = d[TOP:]["domain_count"].sum()
    d3 = d3.iloc[::-1]
    total = d3["domain_count"].sum()
    p = (d3["domain_count"] / total) * 100

    return {
        "data": [
            {
                "x": d3["domain_count"],
                "y": [f"{i} " for i in d3.index],
                "text": p,
                "type": "bar",
                "orientation": "h",
                # "marker": {"color": "#f9e56d"},
                "marker": {"color": "#41CD52"},
                "texttemplate": "%{value} (%{text:.2f} %)",
                "textposition": "auto",
            },
        ],
        "layout": {
            "title": "Commits per email domain",
            "height": "350",
            "padding": {
                "r": "150",
            },
        },
    }


def get_ranking_chart_data(df, column="commit_count"):
    TOP = 10
    d4 = (
        df.groupby("name")
        .agg({"name": "count", "files_changed": "sum", "insertions": "sum", "deletions": "sum"})
        .rename(columns={"name": "commit_count"})
    )
    d4 = d4.sort_values(by=column, ascending=False)[:TOP]
    d4 = d4.reset_index()
    d4["name"] = d4["name"].apply(partially_hide)
    d4 = d4.iloc[::-1]

    titles = {
        "files_changed": "Files changed",
        "commit_count": "Commits",
        "insertions": "Insertions",
        "deletions": "Deletions",
    }

    colors = {
        "files_changed": "#53586b",
        "commit_count": "#222840",
        "insertions": "#41CD52",
        "deletions": "#fb6761",
    }

    return {
        "data": [
            {
                "y": d4["name"],
                "x": d4[column],
                "type": "bar",
                "name": "Commits",
                "orientation": "h",
                "marker": {"color": colors[column]},
            },
        ],
        "layout": {
            "title": f"Contributors ({titles[column]})",
            "yaxis": {"dtick": "1"},
            "bargap": "2",
            "margin": {
                "l": "100",
            },
        },
    }


def get_commit_chart_data(df):
    d = df.groupby("date_week")["date_week"].count()
    d = d.to_frame()
    d.rename(columns={"date_week": "date_count"}, inplace=True)
    d = d.reset_index()
    # d["week"] = d["date_week"].copy().apply(lambda x : int(x.split("W")[-1]))
    # d["year"] = d["date_week"].copy().apply(lambda x : int(x.split("W")[0]))

    return {
        "data": [
            {
                "x": d["date_week"],
                "y": d["date_count"],
                "line": {"color": "#222840"},
                "type": "lines",
                "xaxis": "x1",
            },
        ],
        "layout": {
            "title": "Number of commits",
            "height": "300",
            "xaxis": {"tickangle": "45"},
        },
    }


def get_collab_chart_data(df):
    d = df.groupby("date_week")["email"].nunique()
    d = d.to_frame()
    d.rename(columns={"email": "collaborators_count"}, inplace=True)

    return {
        "data": [
            {
                "x": d.index,
                "y": d["collaborators_count"],
                "line": {"color": "#41CD52"},
                "type": "lines",
            },
        ],
        "layout": {
            "title": "Number of contributors",
            "height": "300",
            "xaxis": {"tickangle": "45"},
        },
    }


@app.callback(
    [
        Output("commits-chart", "figure"),
        Output("collaborators-chart", "figure"),
        Output("files-changed-chart", "figure"),
        Output("commit-count-chart", "figure"),
        Output("insertions-chart", "figure"),
        Output("deletions-chart", "figure"),
        Output("domain-chart", "figure"),
    ],
    [
        Input("module-filter", "value"),
        Input("year-filter", "value"),
        Input("tqtc-filter", "value"),
    ],
)
def update_charts(module, year, tqtc):
    """
    This function is in charge of updating the data for all the charts,
    and the connection is done by the chart-id from each.

    As Input, we get the values from the combobox: 'module', and 'year',
    and then we filter the main dataframe, to re-generate the data
    for all the different plots.
    """
    df = data[module][data[module]["datetime"].dt.year >= int(year)]

    if "TQtC" not in tqtc:
        df = df[df.domain != "qt"]

    commit_data = get_commit_chart_data(df)
    collab_data = get_collab_chart_data(df)
    files_changed_data = get_ranking_chart_data(df, column="files_changed")
    commit_count_data = get_ranking_chart_data(df, column="commit_count")
    insertions_data = get_ranking_chart_data(df, column="insertions")
    deletions_data = get_ranking_chart_data(df, column="deletions")
    domain_data = get_domain_chart_data(df)

    return (
        commit_data,
        collab_data,
        files_changed_data,
        commit_count_data,
        insertions_data,
        deletions_data,
        domain_data,
    )


def get_header():
    """
    This is in charge of return the divs that form the header,
    both the left logo/title and the right side menu.
    """
    return html.Div(
        children=[
            html.Div(
                children=[
                    html.Img(src="assets/theqtproject.png", className="header-logo"),
                ],
                className="header-title-left",
            ),
            html.Div(
                children=[
                    html.A(children="Code Review", href="https://codereview.qt-project.org/"),
                    html.A(children="Bug Tracker", href="https://bugreports.qt.io"),
                    html.A(children="Wiki", href="https://wiki.qt.io"),
                    html.A(children="Docs", href="https://doc.qt.io"),
                    html.A(children="Mailing List", href="https://lists.qt-project.org"),
                    html.A(children="Forum", href="https://forum.qt.io"),
                    html.A(children="Qt.io", href="https://qt.io", style={"color": "#41CD52"}),
                ],
                className="header-menu-right",
            ),
        ],
        className="header",
    )


def get_left_column(divs=[]):
    """
    This returns the left divs which contain explanatory text
    about different topics, defined by different markdown files
    on this project.
    """

    def get_div(i):
        return html.Div(
            children=[
                dcc.Markdown(i),
            ],
            className="card pad",
        )

    content = [get_div(i) for i in divs if i]

    return html.Div(
        children=content,
        className="six columns",
    )


def get_services_status():
    gerrit_url = "https://codereview.qt-project.org/projects/qt%2Fqtbase/HEAD"
    coin_url = "https://testresults.qt.io/coin/api/capabilities"

    def get_st(url):
        response = requests.get(url)
        if response.status_code == 200:
            return "Online   🟩"
        elif response.status_code == 404:
            return "Offline  🟥"
        else:
            return "Undefined  🟧"

    return html.Div(
        children=[
            html.H4(children="Services Status"),
            html.Div(
                children=[
                    html.Div(
                        children=[
                            html.B(
                                children="Gerrit: ",
                                style={"display": "inline-block", "margin-right": "5px"},
                            ),
                            html.A(
                                children=f"{get_st(gerrit_url)}",
                                href="https://codereview.qt-project.org",
                                style={"display": "inline-block"},
                            ),
                        ],
                    ),
                ],
                className="five columns",
            ),
            html.Div(
                children=[
                    html.Div(
                        children=[
                            html.B(
                                children="COIN: ",
                                style={"display": "inline-block", "margin-right": "5px"},
                            ),
                            html.A(
                                children=f"{get_st(coin_url)}",
                                href="https://testresults.qt.io",
                                style={"display": "inline-block"},
                            ),
                        ],
                    ),
                ],
                className="five columns",
            ),
        ],
        className="row card",
    )


def get_filter(modules, years):
    """
    Get div containing the combobox to filter the modules
    and years, to trigger the charts update.
    """
    return html.Div(
        children=[
            html.Div(
                children=[
                    html.Div(
                        children=[
                            html.Div(children="Module", className="menu-title"),
                            dcc.Dropdown(
                                id="module-filter",
                                options=[{"label": m, "value": m} for m in modules],
                                value="qtbase",
                                clearable=False,
                                className="dropdown",
                            ),
                        ],
                    ),
                    dcc.Checklist(
                        id="tqtc-filter",
                        options=[
                            {"label": "Include commits from The Qt Company", "value": "TQtC"},
                        ],
                        value=["TQtC"],
                        className="tqtc-filter",
                    ),
                ],
                className="six columns",
            ),
            html.Div(
                children=[
                    html.Div(
                        children=[
                            html.Div(children="Year", className="menu-title"),
                            dcc.Dropdown(
                                id="year-filter",
                                options=[{"label": m, "value": m} for m in years],
                                value="2018",
                                clearable=False,
                                className="dropdown",
                            ),
                        ],
                    ),
                ],
                className="six columns",
            ),
        ],
        className="row card option-select",
    )


def get_filter_email(lists):
    """
    Get div containing the combobox to filter the mailing lists,
    to trigger the charts update.
    """
    return html.Div(
        children=[
            html.Div(
                children=[
                    html.Div(
                        children=[
                            html.Div(children="Mailing List", className="menu-title"),
                            dcc.Dropdown(
                                id="mailing-list-filter",
                                options=[{"label": m, "value": m} for m in lists],
                                value="development",
                                clearable=False,
                                className="dropdown",
                            ),
                        ],
                    ),
                ],
                className="six columns",
            ),
            html.Div(
                children=[
                    html.Div(
                        children=[
                            html.Div(children="Year", className="menu-title"),
                            dcc.Dropdown(
                                id="mailing-list-year-filter",
                                options=[{"label": m, "value": m} for m in years],
                                value="2018",
                                clearable=False,
                                className="dropdown",
                            ),
                        ],
                    ),
                ],
                className="six columns",
            ),
        ],
        className="row card option-select",
    )


def get_markdown_content(filename):
    print(f"Reading '{filename}'...")
    content = ""
    with open(filename, "r") as f:
        content = f.read()
    return content


# Download the data from an external source which runs a cronjob
# to keep an updated ZIP file with the processed data.
# Heroku will restart every day, so the data will be updated on
# a daily basis.
print("Downloading data...")
r = requests.get("https://qtstats.info/data_csv.zip")
if r.status_code == 404:
    print("Error: Problem downloading the Data")
    sys.exit(-1)

with zipfile.ZipFile(io.BytesIO(r.content)) as z:
    z.extractall(".")

print(f"--\nCSV files found: {len(os.listdir('data/'))}\n--")


# Loading all the data
print("Loading all the CSV files...")
modules = []
years = set()
lists = set()
data = {}
email_data = {}
for f in Path("data").glob("*.csv"):
    if "email" in f.name:
        ml = f.stem.replace("emails_", "")
        email_data[ml] = pd.read_csv(f.relative_to(Path(".")), sep=";")
        email_data[ml]["datetime"] = pd.to_datetime(email_data[ml]["date"], format="%Y-%m-%d")
    else:
        data[f.stem] = pd.read_csv(f.relative_to(Path(".")), sep=";")
        data[f.stem]["datetime"] = pd.to_datetime(data[f.stem]["date"], format="%Y-%m-%d")
        data[f.stem].sort_values("datetime", inplace=True)
        data[f.stem]["date_week"] = data[f.stem]["datetime"].apply(
            lambda x: f"{x.year} W{str(x.week).zfill(3)}"
        )
        modules.append(f.stem)
        years.update(set(data[f.stem]["datetime"].dt.year))
        print(f"-- Read '{f.stem}': {data[f.stem].shape}")

# Generate entry with all the content
data["All Qt"] = pd.concat([i for _, i in data.items()], ignore_index=True)
modules.append("All Qt")

modules = sorted(modules)
years = [i for i in sorted(years)]
lists = sorted(i.replace("emails_", "") for i in email_data.keys())
print("Done")

# Reading 'markdown' files
left_boxes = [
    get_markdown_content("learn_more.md"),
    get_markdown_content("contribute.md"),
    get_markdown_content("guidelines.md"),
    get_markdown_content("quips.md"),
]

# Layout
app.layout = html.Div(
    children=[
        get_header(),
        html.Div(
            children=[
                html.Div(
                    children=[
                        get_left_column(divs=left_boxes),
                        html.Div(
                            children=[
                                get_services_status(),
                                get_filter(modules, years),
                                html.Div(
                                    children=dcc.Graph(id="commits-chart"),
                                    className="card",
                                ),
                                html.Div(
                                    children=dcc.Graph(id="collaborators-chart"),
                                    className="card",
                                ),
                                html.Div(
                                    children=dcc.Graph(id="domain-chart"),
                                    className="card",
                                ),
                                html.Div(
                                    children=[
                                        html.Div(
                                            children=dcc.Graph(id="files-changed-chart"),
                                            className="six columns card",
                                        ),
                                        html.Div(
                                            children=dcc.Graph(id="commit-count-chart"),
                                            className="six columns card",
                                        ),
                                    ],
                                    className="row",
                                ),
                                html.Div(
                                    children=[
                                        html.Div(
                                            children=dcc.Graph(id="insertions-chart"),
                                            className="six columns card",
                                        ),
                                        html.Div(
                                            children=dcc.Graph(id="deletions-chart"),
                                            className="six columns card",
                                        ),
                                    ],
                                    className="row",
                                ),
                            ],
                            className="six columns",
                        ),
                    ],
                    className="row",
                ),
            ],
            className="wrapper",
        ),
    ],
)

if __name__ == "__main__":
    app.run_server(debug=False, threaded=True)