Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions aw-watcher-browser-classifier/classifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""
aw-watcher-browser-classifier
------------------------------
A custom ActivityWatch watcher that reads events from the existing
aw-watcher-web bucket (tab title + URL) and classifies each event into
a research-relevant category, then writes the classified events into
a new bucket so they're queryable/visualizable separately.
"""

import time
import logging
from datetime import datetime, timedelta, timezone
from urllib.parse import urlparse

from aw_client import ActivityWatchClient

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger(__name__)

CLIENT_NAME = "aw-watcher-browser-classifier"
POLL_INTERVAL_SECONDS = 10
SOURCE_BUCKET_SUFFIX = "aw-watcher-web"
LOOKBACK_SECONDS = 30

CATEGORY_RULES = {
"research": [
"arxiv.org", "scholar.google.com", "jstor.org", "wikipedia.org",
"pubmed.ncbi.nlm.nih.gov", "ieee.org", "acm.org", "researchgate.net",
],
"dev_tools": [
"github.com", "stackoverflow.com", "docs.python.org", "developer.mozilla.org",
"leetcode.com", "neetcode.io", "npmjs.com", "pypi.org",
],
"social_distraction": [
"reddit.com", "instagram.com", "twitter.com", "x.com",
"tiktok.com", "facebook.com", "youtube.com",
],
"communication": [
"mail.google.com", "outlook.com", "slack.com", "discord.com",
],
}

DEFAULT_CATEGORY = "uncategorized"


def classify_url(url: str) -> str:
if not url:
return DEFAULT_CATEGORY
try:
domain = urlparse(url).netloc.lower()
except Exception:
return DEFAULT_CATEGORY
for category, domains in CATEGORY_RULES.items():
if any(known_domain in domain for known_domain in domains):
return category
Comment on lines +53 to +55

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Substring domain check causes false positives

known_domain in domain checks whether the rule string is a substring of the parsed netloc. For example, "x.com" would match "notx.com" and "neetcode.io" would match "myneetcode.io". Anchoring the check (e.g., domain == known_domain or domain.endswith("." + known_domain)) would prevent these misclassifications.

return DEFAULT_CATEGORY


def find_web_bucket(client: ActivityWatchClient):
buckets = client.get_buckets()
for bucket_id in buckets:
if SOURCE_BUCKET_SUFFIX in bucket_id:
return bucket_id
return None


def main():
client = ActivityWatchClient(CLIENT_NAME, testing=False)

source_bucket = find_web_bucket(client)
if not source_bucket:
log.error(
"Could not find an aw-watcher-web bucket. Make sure the "
"ActivityWatch browser extension is installed and logging."
)
return

output_bucket = f"{CLIENT_NAME}_{client.client_hostname}"
client.create_bucket(output_bucket, event_type="classified_browser_activity", queued=True)
log.info("Reading from: %s", source_bucket)
log.info("Writing to: %s", output_bucket)

with client:
while True:
since = datetime.now(timezone.utc) - timedelta(seconds=LOOKBACK_SECONDS)
recent_events = client.get_events(source_bucket, start=since, limit=50)

for event in recent_events:
url = event.data.get("url", "")
title = event.data.get("title", "")
category = classify_url(url)

classified_event = {
"timestamp": event.timestamp,
"duration": event.duration.total_seconds() if event.duration else 0,
"data": {"url": url, "title": title, "category": category},
}
client.heartbeat(
output_bucket, classified_event,
pulsetime=POLL_INTERVAL_SECONDS + 5, queued=True,
)
Comment on lines +93 to +101

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 heartbeat receives a plain dict instead of an Event object

The official aw-client API signature is heartbeat(bucket_id: str, event: Event, pulsetime: float, ...) where event must be an aw_core.models.Event instance. Passing a plain dict here will raise an AttributeError at runtime when the client internally accesses attributes like .timestamp and .data on the object.

log.info("Classified [%s] -> %s", category, url or title)

time.sleep(POLL_INTERVAL_SECONDS)
Comment on lines +84 to +104

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Overlapping lookback window causes duplicate events in the output bucket

LOOKBACK_SECONDS = 30 but the loop sleeps only POLL_INTERVAL_SECONDS = 10 seconds between runs. Each poll fetches the last 30 s of source events, so roughly 20 s worth of events from the previous cycle are re-fetched and re-heartbeated every iteration — meaning each source event is written ~3 times to the output bucket. There is no deduplication guard (e.g., tracking the last-processed timestamp or event ID).



if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
log.info("Stopped.")
1 change: 1 addition & 0 deletions progress.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Update: Mon Mar 23 03:20:19 EDT 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Personal progress note should not be committed to the repository

progress.txt is a personal bookkeeping file with no relevance to the codebase. It should be removed from the PR and added to .gitignore.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!