zack-n-hasan / analyze_stats.py
Druid
initial commit
ca484cf
Raw
History Blame Contribute Delete
9.68 kB
#!/usr/bin/env python3
"""Parse Chatterino .log files, write JSONL to data/, and print dataset stats."""
import re
import json
import string
import sys
from pathlib import Path
from collections import Counter
ROOT = Path(__file__).parent
LOGS_DIR = ROOT / "original-logs"
DATA_DIR = ROOT / "data"
MSG_RE = re.compile(r"^\[(\d{2}:\d{2}:\d{2})\] ([^:]+): (.+)$")
DATE_HEADER_RE = re.compile(r"^# Start logging at (\d{4}-\d{2}-\d{2})")
UNICODE_EMOJI_RE = re.compile(
"["
"\U0001F300-\U0001F9FF"
"\U0001FA00-\U0001FA9F"
"\U00002600-\U000027BF"
"\U00002300-\U000023FF"
"\U00002B00-\U00002BFF"
"\U0001F000-\U0001F02F"
"\U0001F0A0-\U0001F0FF"
"]"
)
# Common global + channel Twitch emotes
TWITCH_EMOTES = {
"PogChamp","Pog","PogU","POGGERS","PauseChamp","PepeHands","FeelsBadMan",
"FeelsGoodMan","Kappa","LUL","KEKW","OMEGALUL","LULW","monkaS","monkaHmm",
"monkaGIGA","AYAYA","NotLikeThis","WutFace","VoteYea","VoteNay","KKona",
"KKonaW","BibleThump","EZ","Sadge","Copium","COPIUM","WidepeepoHappy",
"peepoHappy","peepoSad","peepoWTF","pepeJAM","PepeJAM","pepeLaugh",
"PepeLaugh","pepeD","pepePoint","HYPERCLAP","Clap","TriHard","haHAA",
"ResidentSleeper","gachiHYPER","gachiBASS","forsenCD","forsenE","GIGACHAD",
"BASED","TOOBASED","NODDERS","YEPPERS","YEP","Chatting","Bedge","Hmm",
"WhosThisDiva","CumDance","NOTED","xqcL",
# hasanabi channel
"hasL","hasS","hasPog","hasCop","hasFIST","hasKek","hasFeel","hasThink",
"PIKMINPARTY","pepePoint","TOOBASED",
# zackrawrr channel
"asmongPog","asmongCozy","asmongKEK","ddHuh","XEsht",
}
STOPWORDS = set(
"the a an and or but in on at to for of is are was were be been being "
"have has had do does did will would could should may might shall can "
"i you he she it we they me him her us them my your his its our their "
"what which who where when how this that these those just like so no "
"not dont its its im its yeah yes lol".split()
)
def classify_line(line: str) -> dict | None:
m = MSG_RE.match(line)
if m:
ts, username, message = m.groups()
return {"type": "message", "timestamp": ts, "username": username.strip(), "message": message}
m = re.match(r"^\[(\d{2}:\d{2}:\d{2})\] (.+)$", line)
if not m:
return None
ts, rest = m.groups()
if "permanently banned" in rest:
event = "ban"
elif "timed out" in rest:
event = "timeout"
elif "subscribed" in rest or "gifted" in rest:
event = "subscription"
elif "watch streak" in rest:
event = "watch_streak"
elif "joined channel" in rest or "is live" in rest or rest == "Announcement":
event = "system"
else:
event = "system"
return {"type": event, "timestamp": ts, "text": rest}
def is_emote(token: str) -> bool:
clean = token.strip(string.punctuation)
if clean in TWITCH_EMOTES:
return True
# All-caps alpha, 3+ chars — likely a global or 7TV emote
if clean.isalpha() and clean.isupper() and len(clean) >= 3:
return True
return False
def ngrams(tokens: list[str], n: int) -> list[str]:
return [" ".join(tokens[i : i + n]) for i in range(len(tokens) - n + 1)]
def analyze_channel(channel: str) -> dict:
logs_path = LOGS_DIR / channel
data_path = DATA_DIR / channel
data_path.mkdir(parents=True, exist_ok=True)
messages = []
for log_file in sorted(logs_path.glob("*.log")):
# Extract date from filename e.g. hasanabi-2026-05-07.log
parts = log_file.stem.split("-", 1)
date = parts[1] if len(parts) == 2 else log_file.stem
out_path = data_path / (log_file.stem + ".jsonl")
with open(log_file, encoding="utf-8", errors="replace") as f, \
open(out_path, "w", encoding="utf-8") as out:
for line in f:
line = line.rstrip("\n")
record = classify_line(line)
if record is None:
continue
record["channel"] = channel
record["date"] = date
out.write(json.dumps(record, ensure_ascii=False) + "\n")
if record["type"] == "message":
messages.append(record)
return compute_stats(channel, messages)
def compute_stats(channel: str, messages: list) -> dict:
total = len(messages)
if total == 0:
return {"channel": channel, "total_messages": 0}
user_counts = Counter(m["username"] for m in messages)
unique_users = len(user_counts)
top_user, top_count = user_counts.most_common(1)[0]
single_senders = sum(1 for c in user_counts.values() if c == 1)
pct_single = 100 * single_senders / unique_users
unicode_emoji_total = 0
twitch_emote_total = 0
char_lengths = []
word_counts = []
word_lengths_sample = []
all_content_tokens: list[str] = [] # non-emote tokens for n-grams/TTR
longest_msg = ""
longest_len = 0
for m in messages:
msg = m["message"]
unicode_emoji_total += len(UNICODE_EMOJI_RE.findall(msg))
clen = len(msg)
char_lengths.append(clen)
if clen > longest_len:
longest_len = clen
longest_msg = msg
tokens = msg.split()
word_counts.append(len(tokens))
for tok in tokens:
clean = tok.strip(string.punctuation)
if not clean:
continue
if is_emote(clean):
twitch_emote_total += 1
else:
word_lengths_sample.append(len(clean))
all_content_tokens.append(clean.lower())
# Vocabulary diversity (type-token ratio on first 100k tokens)
sample = all_content_tokens[:100_000]
ttr = len(set(sample)) / len(sample) if sample else 0.0
# N-grams: filter stopword-only grams
def useful(ng: str) -> bool:
return not all(p in STOPWORDS for p in ng.split())
bigram_counter: Counter = Counter()
trigram_counter: Counter = Counter()
for m in messages:
tokens = [t.lower().strip(string.punctuation) for t in m["message"].split() if t.strip(string.punctuation) and not is_emote(t.strip(string.punctuation))]
bigram_counter.update(ngrams(tokens, 2))
trigram_counter.update(ngrams(tokens, 3))
top_bigrams = [(ng, c) for ng, c in bigram_counter.most_common(100) if useful(ng)][:10]
top_trigrams = [(ng, c) for ng, c in trigram_counter.most_common(100) if useful(ng)][:10]
return {
"channel": channel,
"total_messages": total,
"unique_users": unique_users,
"unicode_emoji_count": unicode_emoji_total,
"twitch_emote_count": twitch_emote_total,
"total_emojis": unicode_emoji_total + twitch_emote_total,
"top_sender": {"username": top_user, "count": top_count},
"single_message_senders": single_senders,
"pct_single_message_senders": round(pct_single, 1),
"repeat_senders": unique_users - single_senders,
"avg_messages_per_user": round(total / unique_users, 2),
"avg_message_length_chars": round(sum(char_lengths) / total, 1),
"avg_message_length_words": round(sum(word_counts) / total, 2),
"avg_word_length_chars": round(sum(word_lengths_sample) / len(word_lengths_sample), 2) if word_lengths_sample else 0,
"avg_emojis_per_message": round((unicode_emoji_total + twitch_emote_total) / total, 3),
"longest_message": {"text": longest_msg[:200], "length_chars": longest_len},
"vocabulary_diversity_ttr": round(ttr, 4),
"top_bigrams": top_bigrams,
"top_trigrams": top_trigrams,
}
def print_stats(s: dict) -> None:
ch = s["channel"]
print(f"\n{'='*60}")
print(f" {ch.upper()}")
print(f"{'='*60}")
print(f"Total messages : {s['total_messages']:,}")
print(f"Unique users : {s['unique_users']:,}")
print(f"Unicode emoji : {s['unicode_emoji_count']:,}")
print(f"Twitch emotes : {s['twitch_emote_count']:,}")
print(f"Total emojis : {s['total_emojis']:,}")
print(f"Top sender : {s['top_sender']['username']} ({s['top_sender']['count']:,} messages)")
print(f"Single-msg senders : {s['single_message_senders']:,} ({s['pct_single_message_senders']}% of users)")
print(f"Repeat senders : {s['repeat_senders']:,}")
print(f"Avg msgs/user : {s['avg_messages_per_user']}")
print(f"Avg message (chars) : {s['avg_message_length_chars']}")
print(f"Avg message (words) : {s['avg_message_length_words']}")
print(f"Avg word length : {s['avg_word_length_chars']} chars")
print(f"Avg emojis/message : {s['avg_emojis_per_message']}")
print(f"Vocabulary diversity : {s['vocabulary_diversity_ttr']} (TTR)")
print(f"Longest message : {s['longest_message']['length_chars']} chars")
print(f" \"{s['longest_message']['text'][:120]}\"")
print(f"\nTop bigrams:")
for ng, c in s["top_bigrams"]:
print(f" {c:>6,} {ng}")
print(f"\nTop trigrams:")
for ng, c in s["top_trigrams"]:
print(f" {c:>6,} {ng}")
if __name__ == "__main__":
channels = sys.argv[1:] or [d.name for d in sorted(LOGS_DIR.iterdir()) if d.is_dir()]
results = {}
for ch in channels:
print(f"Processing {ch}...", flush=True)
stats = analyze_channel(ch)
results[ch] = stats
print_stats(stats)
# Save raw stats for reference
out = ROOT / "stats.json"
with open(out, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\nStats saved to {out}")