File size: 2,248 Bytes
255ac07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gzip
import json
import os

from matplotlib import pyplot as plt


def load_stats(path: str) -> dict:
    stats: dict = {}
    for filename in os.listdir(path):
        file_path: str = os.path.join(path, filename)
        if os.path.isdir(filename):
            continue
        data: dict
        if filename.endswith('.gz'):
            with gzip.open(file_path, mode='rt') as file:
                data = json.loads(file.read())
        else:
            with open(file_path, mode='rt') as file:
                data = json.loads(file.read())
        print(f'Loaded stats from {file_path}')
        stats.update(**data)
    return stats


def stat_filter(stats: dict, deviation_cutoff=(1.0, 0.0), clamp=(200.0, 2048.0), min_messages=4) -> list[dict]:
    cutoff_threshold: (float, float) = (
        stats['wordsStdDev'] * deviation_cutoff[0], stats['wordsStdDev'] * deviation_cutoff[1])
    if cutoff_threshold[1] <= 0:
        cutoff_threshold = (cutoff_threshold[0], stats['wordsMax'])
    cutoff_min: float = max(max(clamp[0], cutoff_threshold[0]), stats['wordsMean'] - cutoff_threshold[0])
    cutoff_max: float = stats['wordsMean'] + cutoff_threshold[1]
    if clamp[1] > 0:
        cutoff_max = min(clamp[1], cutoff_max)

    conversations: list[dict] = [v for k, v in stats['conversations'].items() if
                                 v['wordsMax'] <= cutoff_max and v['wordsMin'] >= cutoff_min and v[
                                     'messagesCount'] >= min_messages]
    print(
        f'Min: {cutoff_min:0.0f}\tMax: {cutoff_max:0.0f}\n'
        f'Clamped from {cutoff_threshold[0]:0.0f}, {cutoff_threshold[1]:0.0f}')
    print(f'{len(conversations)} conversations')

    return conversations


def build_mean_word_plot(conv_stats: list[float], title: str = 'Conversation Message Mean Words', xlabel: str = 'Mean',
                         ylabel: str = 'Conversations', text: str = '',
                         **kwargs):
    fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
    n, bins, patches = ax.hist(conv_stats, density=True,
                               facecolor='C0', alpha=0.75, **kwargs)
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    plt.figtext(0, 0.95, text)