summaryrefslogtreecommitdiff
path: root/bjoern/videoanalyse/utils.py
blob: 69215ff9a00b5ec0e001a0422d81148513f73ace (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
#!/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(vp_path / "analysis_results.csv")
    analysis = pd.read_csv(ocr_path)
    analysis["Starttime"] = analysis["start_time"].apply(
        add_video_time_to_start, args=(video_date,)
    )

    # logs = pd.read_csv(vp_path / f"{vp_path.name}.csv")
    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)