summaryrefslogtreecommitdiff
path: root/bjoern/videoanalyse/utils.py
blob: f9b2ca0b88bb2d24c4e38293d6de4faeeaa8334e (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
#!/usr/bin/env python3

import csv
from datetime import datetime, timedelta

import numpy as np
import pandas as pd
from Levenshtein import distance as levendist
from sklearn.cluster import DBSCAN
from sklearn.metrics import pairwise_distances


def combine_ocr_logs(video_path, ocr_path, log_path):
    date_format = "%Y-%m-%d %H-%M-%S"
    video_date = datetime.strptime(video_path.stem, date_format)
    print(video_date)
    # video_delta = timedelta(hours=video_date.hour, minutes=video_date.minute, seconds=video_date.second)

    def add_video_time_to_start(x, video_date):
        start = timedelta(seconds=int(round(x)))
        return (start + video_date).time().isoformat()

    analysis = pd.read_csv(ocr_path)
    analysis["Starttime"] = analysis["start_time"].apply(
        add_video_time_to_start, args=(video_date,)
    )

    logs = pd.read_csv(log_path)

    def get_log_url(start_time):
        start_time = datetime.strptime(start_time, "%H:%M:%S")

        for _, row in logs.iterrows():
            log_start = datetime.strptime(row[0], "%H:%M:%S")
            log_end = datetime.strptime(row[1], "%H:%M:%S")
            if start_time >= log_start and start_time <= log_end:
                return row[3]
        return 0

    analysis["log_url"] = analysis.apply(lambda row: get_log_url(row.Starttime), axis=1)

    # analysis.to_csv(vp_path / "merged.csv", quoting=csv.QUOTE_NONNUMERIC)
    return analysis


def levendist_normalized(s1, s2, log_url):
    return levendist(s1, s2) / len(str(log_url))


def calc_levenshtein_distance(df):
    df["levenshtein-distance"] = df.apply(
        lambda row: levendist(str(row.url), str(row.log_url)) / len(str(row.log_url)),
        axis=1,
    )
    return df


def group_urls(urls):
    unique_urls = np.unique(urls)

    # TODO: casting deprecation np
    def levenshtein_from_idx(idx1, idx2):
        return levendist(unique_urls[int(idx1)], unique_urls[int(idx2)])

    X = np.searchsorted(unique_urls, list([[x] for x in urls]))

    distance_matrix = pairwise_distances(
        X=X, Y=None, metric=levenshtein_from_idx, n_jobs=-1
    )
    # TODO: eps and min_samples parameter
    db = DBSCAN(eps=10, min_samples=5, metric="precomputed").fit(distance_matrix)
    labels = db.labels_
    zipped = zip(urls, labels)

    # grouping solution from: https://www.geeksforgeeks.org/python-group-tuple-into-list-based-on-value/
    # create an empty dictionary to store the grouped tuples
    grouped_dict = {}

    # loop through the tuples in the list
    for tup in zipped:
        # get the second element of the tuple
        key = tup[1]
        # if the key is not already in the dictionary, add it with an empty list as value
        if key not in grouped_dict:
            grouped_dict[key] = []
        # append the current tuple to the list corresponding to the key in the dictionary
        grouped_dict[key].append(tup[0])

    # convert the dictionary values to lists and store in res
    url_groups = [v for _, v in grouped_dict.items()]

    return url_groups


# TODO: use df instead of csv reader
# TODO: return df instead of writing to file
def write_grouped_metrics(df, url_groups, data_path):
    # # for every row check which group its url belongs to and add a column with group indices
    # # also add columns with longest/most frequent url in group
    with open(data_path / "metrics.csv", "r") as input_file, open(
        data_path / "metrics_grps.csv", "w", newline=""
    ) as output_file:
        csv_reader = csv.reader(input_file, quotechar='"')
        csv_writer = csv.writer(
            output_file, quotechar='"', quoting=csv.QUOTE_NONNUMERIC
        )
        header = next(csv_reader)
        header.extend(
            [
                "group_index",
                "longest",
                "longest-distance",
                "most_frequent",
                "most_frequent-distance",
            ]
        )
        csv_writer.writerow(header)
        for row in csv_reader:
            ocr_url = row[2]
            log_url = row[5]
            for idx, grp in enumerate(url_groups):
                if ocr_url in grp:
                    row.append(str(idx))
                    longest_in_grp = max(grp, key=len)
                    row.append(longest_in_grp)
                    row.append(levendist_normalized(log_url, longest_in_grp, log_url))
                    most_frequent_in_grp = max(set(grp), key=grp.count)
                    row.append(str(most_frequent_in_grp))
                    row.append(
                        levendist_normalized(log_url, most_frequent_in_grp, log_url)
                    )
            csv_writer.writerow(row)


def evaluate_results(tab_results, log_tab_results):
    vp_code = [df["vp_code"].values[0] for df in tab_results]

    mean_long = []
    mean_freq = []
    count_groups = []
    count_log_urls = []
    count_grp_diff = []
    grp_tabswitches = []
    tabswitches_diff = []
    for tab_df, log_tab_df in zip(tab_results, log_tab_results):
        groups = set(tab_df["group"].values)
        group_long = 0
        group_freq = 0
        count_groups.append(len(groups))
        count_log_urls.append(len(set(tab_df["log_url"].values)))
        count_grp_diff.append(len(groups) - len(set(tab_df["log_url"].values)))
        grp_tabswitches.append(len(tab_df["group"].values))
        tabswitches_diff = len(tab_df["group"].values) - len(log_tab_df["group"].values)
        for group in groups:
            group_df = tab_df.loc[tab_df["group"] == group]
            group_long += group_df["longest-distance"].values[0]
            group_freq += group_df["most_frequent-distance"].values[0]
        mean_long.append(group_long / len(groups))
        mean_freq.append(group_freq / len(groups))

    metrics = {
        "vp_code": vp_code,
        "mean_long": mean_long,
        "mean_freq": mean_freq,
        "count_groups": count_groups,
        # "count_log_urls": count_log_urls,
        "count_grp_diff": count_grp_diff,
        "grp_tabswitches": grp_tabswitches,
        "tabswitches_diff": tabswitches_diff,
    }

    evals = pd.DataFrame(metrics)

    return evals