Spaces:
Sleeping
Sleeping
Upload 14 files
Browse files- activity_log.py +175 -0
- analytics.py +199 -0
- app.py +122 -0
- config.toml +17 -0
- dashboard.py +253 -0
- database.py +265 -0
- main.py +99 -0
- requirements.txt +7 -3
- seed_demo.py +103 -0
- settings.py +262 -0
- startup.py +43 -0
- tracker.py +367 -0
- tray.py +71 -0
- ui_utils.py +309 -0
activity_log.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Page 3: Activity Log
|
| 3 |
+
Searchable, filterable, paginated activity table.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from datetime import datetime, timedelta, date
|
| 9 |
+
|
| 10 |
+
from ui_utils import (
|
| 11 |
+
fmt_duration, privacy_badge, page_header,
|
| 12 |
+
CATEGORY_COLORS, get_db, get_date_range
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
PAGE_SIZE = 50
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def render():
|
| 20 |
+
db = get_db()
|
| 21 |
+
privacy_badge()
|
| 22 |
+
page_header("Activity Log", "Browse and search all tracked sessions")
|
| 23 |
+
|
| 24 |
+
# ── Filters ───────────────────────────────────────────────────────────────
|
| 25 |
+
col1, col2, col3, col4 = st.columns([1.5, 1, 1, 1])
|
| 26 |
+
|
| 27 |
+
with col1:
|
| 28 |
+
search = st.text_input("🔍 Search", placeholder="App, title, or category…")
|
| 29 |
+
|
| 30 |
+
with col2:
|
| 31 |
+
range_sel = st.selectbox("Range", ["Today", "Yesterday", "Last 7 days", "Last 30 days", "Custom"], index=2)
|
| 32 |
+
|
| 33 |
+
start, end = get_date_range(range_sel)
|
| 34 |
+
if range_sel == "Custom":
|
| 35 |
+
with col3:
|
| 36 |
+
start_d = st.date_input("From", value=date.today() - timedelta(days=6))
|
| 37 |
+
with col4:
|
| 38 |
+
end_d = st.date_input("To", value=date.today())
|
| 39 |
+
start = datetime.combine(start_d, datetime.min.time())
|
| 40 |
+
end = datetime.combine(end_d, datetime.max.time())
|
| 41 |
+
|
| 42 |
+
# Filter by category
|
| 43 |
+
cats = [c["name"] for c in db.get_categories()]
|
| 44 |
+
with col3 if range_sel != "Custom" else st.columns(1)[0]:
|
| 45 |
+
pass
|
| 46 |
+
cat_filter_col, show_idle_col = st.columns([2, 1])
|
| 47 |
+
with cat_filter_col:
|
| 48 |
+
selected_cats = st.multiselect("Filter by category", cats, default=[])
|
| 49 |
+
with show_idle_col:
|
| 50 |
+
show_idle = st.checkbox("Include idle", value=False)
|
| 51 |
+
|
| 52 |
+
# ── Count & Pagination ────────────────────────────────────────────────────
|
| 53 |
+
total_count = db.get_activity_count(start, end, search)
|
| 54 |
+
|
| 55 |
+
if "log_page" not in st.session_state:
|
| 56 |
+
st.session_state.log_page = 0
|
| 57 |
+
page = st.session_state.log_page
|
| 58 |
+
offset = page * PAGE_SIZE
|
| 59 |
+
total_pages = max(1, (total_count + PAGE_SIZE - 1) // PAGE_SIZE)
|
| 60 |
+
|
| 61 |
+
# ── Fetch Data ────────────────────────────────────────────────────────────
|
| 62 |
+
rows = db.get_activities(start, end, search=search, limit=PAGE_SIZE, offset=offset)
|
| 63 |
+
|
| 64 |
+
# Apply local filters
|
| 65 |
+
if selected_cats:
|
| 66 |
+
rows = [r for r in rows if r.get("category") in selected_cats]
|
| 67 |
+
if not show_idle:
|
| 68 |
+
rows = [r for r in rows if not r.get("is_idle")]
|
| 69 |
+
|
| 70 |
+
# ── Stats bar ─────────────────────────────────────────────────────────────
|
| 71 |
+
st.markdown(
|
| 72 |
+
f"<p style='color:#9090b0; font-size:0.8rem; margin:8px 0;'>"
|
| 73 |
+
f"Showing {len(rows)} of {total_count:,} records | "
|
| 74 |
+
f"Page {page + 1} of {total_pages}"
|
| 75 |
+
f"</p>",
|
| 76 |
+
unsafe_allow_html=True,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# ── Table ─────────────────────────────────────────────────────────────────
|
| 80 |
+
if rows:
|
| 81 |
+
html_rows = ""
|
| 82 |
+
for r in rows:
|
| 83 |
+
cat = r.get("category", "uncategorized")
|
| 84 |
+
color = CATEGORY_COLORS.get(cat, "#6366f1")
|
| 85 |
+
ts = r.get("timestamp", "")[:19].replace("T", " ")
|
| 86 |
+
is_idle_icon = "💤" if r.get("is_idle") else "●"
|
| 87 |
+
idle_color = "#374151" if r.get("is_idle") else "#10b981"
|
| 88 |
+
dur = fmt_duration(r.get("duration_seconds", 0))
|
| 89 |
+
app = str(r.get("app_name", ""))[:30]
|
| 90 |
+
title = str(r.get("window_title", ""))[:60]
|
| 91 |
+
|
| 92 |
+
html_rows += f"""
|
| 93 |
+
<tr style="border-bottom:1px solid #1a1a2a; transition:background 0.15s;"
|
| 94 |
+
onmouseover="this.style.background='#1c1c27'" onmouseout="this.style.background='transparent'">
|
| 95 |
+
<td style="padding:9px 12px; font-family:'DM Mono',monospace; font-size:0.78rem; color:#9090b0; white-space:nowrap;">{ts}</td>
|
| 96 |
+
<td style="padding:9px 12px; font-weight:500; color:#f0f0ff; font-size:0.85rem;">{app}</td>
|
| 97 |
+
<td style="padding:9px 12px; color:#9090b0; font-size:0.82rem; max-width:280px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">{title}</td>
|
| 98 |
+
<td style="padding:9px 12px; font-family:'DM Mono',monospace; font-size:0.82rem; color:#9090b0;">{dur}</td>
|
| 99 |
+
<td style="padding:9px 12px;">
|
| 100 |
+
<span style="background:{color}22; color:{color}; border:1px solid {color}44;
|
| 101 |
+
border-radius:20px; padding:2px 8px; font-size:0.7rem; font-weight:600; font-family:'DM Mono',monospace;">{cat}</span>
|
| 102 |
+
</td>
|
| 103 |
+
<td style="padding:9px 12px; color:{idle_color}; font-size:0.9rem;" title="{'Idle' if r.get('is_idle') else 'Active'}">{is_idle_icon}</td>
|
| 104 |
+
</tr>"""
|
| 105 |
+
|
| 106 |
+
st.markdown(f"""
|
| 107 |
+
<div style="overflow-x:auto; border:1px solid #2a2a3a; border-radius:12px; margin-bottom:1rem;">
|
| 108 |
+
<table style="width:100%; border-collapse:collapse; font-family:'Inter',sans-serif;">
|
| 109 |
+
<thead>
|
| 110 |
+
<tr style="background:#111118; color:#5a5a7a; font-size:0.7rem; text-transform:uppercase; letter-spacing:0.08em; border-bottom:1px solid #2a2a3a;">
|
| 111 |
+
<th style="text-align:left; padding:10px 12px; font-weight:500;">Time</th>
|
| 112 |
+
<th style="text-align:left; padding:10px 12px; font-weight:500;">App</th>
|
| 113 |
+
<th style="text-align:left; padding:10px 12px; font-weight:500;">Window Title</th>
|
| 114 |
+
<th style="text-align:left; padding:10px 12px; font-weight:500;">Duration</th>
|
| 115 |
+
<th style="text-align:left; padding:10px 12px; font-weight:500;">Category</th>
|
| 116 |
+
<th style="text-align:left; padding:10px 12px; font-weight:500;">Status</th>
|
| 117 |
+
</tr>
|
| 118 |
+
</thead>
|
| 119 |
+
<tbody>{html_rows}</tbody>
|
| 120 |
+
</table>
|
| 121 |
+
</div>
|
| 122 |
+
""", unsafe_allow_html=True)
|
| 123 |
+
else:
|
| 124 |
+
st.markdown("""
|
| 125 |
+
<div style="padding:3rem; text-align:center; border:1px dashed #2a2a3a; border-radius:12px; color:#5a5a7a;">
|
| 126 |
+
No activity records found for the selected filters.
|
| 127 |
+
</div>""", unsafe_allow_html=True)
|
| 128 |
+
|
| 129 |
+
# ── Pagination controls ───────────────────────────────────────────────────
|
| 130 |
+
pc1, pc2, pc3, pc4, pc5 = st.columns([1, 1, 2, 1, 1])
|
| 131 |
+
with pc1:
|
| 132 |
+
if st.button("⏮ First") and page > 0:
|
| 133 |
+
st.session_state.log_page = 0
|
| 134 |
+
st.rerun()
|
| 135 |
+
with pc2:
|
| 136 |
+
if st.button("◀ Prev") and page > 0:
|
| 137 |
+
st.session_state.log_page = page - 1
|
| 138 |
+
st.rerun()
|
| 139 |
+
with pc3:
|
| 140 |
+
st.markdown(
|
| 141 |
+
f"<div style='text-align:center; color:#9090b0; font-size:0.82rem; padding-top:8px;'>"
|
| 142 |
+
f"Page {page + 1} / {total_pages}</div>",
|
| 143 |
+
unsafe_allow_html=True,
|
| 144 |
+
)
|
| 145 |
+
with pc4:
|
| 146 |
+
if st.button("Next ▶") and page < total_pages - 1:
|
| 147 |
+
st.session_state.log_page = page + 1
|
| 148 |
+
st.rerun()
|
| 149 |
+
with pc5:
|
| 150 |
+
if st.button("Last ⏭") and page < total_pages - 1:
|
| 151 |
+
st.session_state.log_page = total_pages - 1
|
| 152 |
+
st.rerun()
|
| 153 |
+
|
| 154 |
+
# ── Export ────────────────────────────────────────────────────────────────
|
| 155 |
+
st.markdown("---")
|
| 156 |
+
all_rows = db.get_activities(start, end, search=search, limit=100000)
|
| 157 |
+
if all_rows:
|
| 158 |
+
df_export = pd.DataFrame(all_rows)
|
| 159 |
+
col_ex1, col_ex2 = st.columns([1, 1])
|
| 160 |
+
with col_ex1:
|
| 161 |
+
st.download_button(
|
| 162 |
+
"📥 Export visible data (CSV)",
|
| 163 |
+
df_export.to_csv(index=False).encode("utf-8"),
|
| 164 |
+
file_name="focustrack_log.csv",
|
| 165 |
+
mime="text/csv",
|
| 166 |
+
use_container_width=True,
|
| 167 |
+
)
|
| 168 |
+
with col_ex2:
|
| 169 |
+
st.download_button(
|
| 170 |
+
"📥 Export visible data (JSON)",
|
| 171 |
+
df_export.to_json(orient="records", indent=2).encode("utf-8"),
|
| 172 |
+
file_name="focustrack_log.json",
|
| 173 |
+
mime="application/json",
|
| 174 |
+
use_container_width=True,
|
| 175 |
+
)
|
analytics.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Page 2: Analytics & Reports
|
| 3 |
+
Date-range charts, heatmaps, export.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import plotly.express as px
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import json
|
| 11 |
+
import io
|
| 12 |
+
from datetime import datetime, timedelta, date
|
| 13 |
+
|
| 14 |
+
from ui_utils import (
|
| 15 |
+
fmt_duration, fmt_duration_long, get_focus_score,
|
| 16 |
+
privacy_badge, page_header, CATEGORY_COLORS, get_db, get_date_range
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def render():
|
| 21 |
+
db = get_db()
|
| 22 |
+
privacy_badge()
|
| 23 |
+
page_header("Analytics & Reports", "Visualize your productivity trends")
|
| 24 |
+
|
| 25 |
+
# ── Date Range Selector ───────────────────────────────────────────────────
|
| 26 |
+
col_range, col_start, col_end = st.columns([1.5, 1, 1])
|
| 27 |
+
with col_range:
|
| 28 |
+
range_sel = st.selectbox(
|
| 29 |
+
"Date range",
|
| 30 |
+
["Today", "Yesterday", "Last 7 days", "Last 30 days", "Custom"],
|
| 31 |
+
index=2,
|
| 32 |
+
)
|
| 33 |
+
start, end = get_date_range(range_sel)
|
| 34 |
+
if range_sel == "Custom":
|
| 35 |
+
with col_start:
|
| 36 |
+
start_d = st.date_input("From", value=date.today() - timedelta(days=6))
|
| 37 |
+
with col_end:
|
| 38 |
+
end_d = st.date_input("To", value=date.today())
|
| 39 |
+
start = datetime.combine(start_d, datetime.min.time())
|
| 40 |
+
end = datetime.combine(end_d, datetime.max.time())
|
| 41 |
+
|
| 42 |
+
# ── Summary Metrics ───────────────────────────────────────────────────────
|
| 43 |
+
summary = db.get_summary(start, end)
|
| 44 |
+
focus_sec = summary.get("focus_seconds") or 0
|
| 45 |
+
idle_sec = summary.get("idle_seconds") or 0
|
| 46 |
+
total_sec = summary.get("total_seconds") or 0
|
| 47 |
+
|
| 48 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 49 |
+
with c1: st.metric("Total Focus Time", fmt_duration_long(focus_sec))
|
| 50 |
+
with c2: st.metric("Total Idle Time", fmt_duration_long(idle_sec))
|
| 51 |
+
with c3: st.metric("Focus Score", f"{get_focus_score(focus_sec, total_sec)}%")
|
| 52 |
+
with c4: st.metric("Tracked Time", fmt_duration_long(total_sec))
|
| 53 |
+
|
| 54 |
+
st.markdown("<div style='height:0.75rem'></div>", unsafe_allow_html=True)
|
| 55 |
+
|
| 56 |
+
# ── Daily Activity Bar Chart ──────────────────────────────────────────────
|
| 57 |
+
daily = db.get_daily_totals(start, end)
|
| 58 |
+
if daily:
|
| 59 |
+
st.markdown("#### Daily Activity")
|
| 60 |
+
df_daily = pd.DataFrame(daily)
|
| 61 |
+
df_daily["focus_min"] = df_daily["focus_seconds"] / 60
|
| 62 |
+
df_daily["idle_min"] = df_daily["idle_seconds"] / 60
|
| 63 |
+
|
| 64 |
+
fig = go.Figure()
|
| 65 |
+
fig.add_bar(
|
| 66 |
+
x=df_daily["day"], y=df_daily["focus_min"],
|
| 67 |
+
name="Focus", marker_color="#6366f1",
|
| 68 |
+
hovertemplate="<b>%{x}</b><br>Focus: %{y:.0f} min<extra></extra>"
|
| 69 |
+
)
|
| 70 |
+
fig.add_bar(
|
| 71 |
+
x=df_daily["day"], y=df_daily["idle_min"],
|
| 72 |
+
name="Idle", marker_color="#374151",
|
| 73 |
+
hovertemplate="<b>%{x}</b><br>Idle: %{y:.0f} min<extra></extra>"
|
| 74 |
+
)
|
| 75 |
+
fig.update_layout(
|
| 76 |
+
barmode="stack", height=280,
|
| 77 |
+
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
|
| 78 |
+
font=dict(color="#9090b0", family="Inter"),
|
| 79 |
+
margin=dict(t=10, b=30, l=0, r=0),
|
| 80 |
+
xaxis=dict(showgrid=False),
|
| 81 |
+
yaxis=dict(showgrid=True, gridcolor="#2a2a3a", title="Minutes"),
|
| 82 |
+
legend=dict(orientation="h", yanchor="bottom", y=1, xanchor="left", x=0),
|
| 83 |
+
)
|
| 84 |
+
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
|
| 85 |
+
|
| 86 |
+
# ── Two-column: Category Breakdown + Top Apps ─────────────────────────────
|
| 87 |
+
col_l, col_r = st.columns(2)
|
| 88 |
+
|
| 89 |
+
with col_l:
|
| 90 |
+
st.markdown("#### Time by Category")
|
| 91 |
+
cat_data = db.get_by_category(start, end)
|
| 92 |
+
if cat_data:
|
| 93 |
+
df_cat = pd.DataFrame(cat_data)
|
| 94 |
+
df_cat["minutes"] = df_cat["total_seconds"] / 60
|
| 95 |
+
colors = [CATEGORY_COLORS.get(c, "#6366f1") for c in df_cat["category"]]
|
| 96 |
+
fig_cat = px.bar(
|
| 97 |
+
df_cat, x="minutes", y="category", orientation="h",
|
| 98 |
+
color="category", color_discrete_map=CATEGORY_COLORS,
|
| 99 |
+
labels={"minutes": "Minutes", "category": ""},
|
| 100 |
+
)
|
| 101 |
+
fig_cat.update_layout(
|
| 102 |
+
height=300, showlegend=False,
|
| 103 |
+
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
|
| 104 |
+
font=dict(color="#9090b0", family="Inter"),
|
| 105 |
+
margin=dict(t=10, b=30, l=0, r=0),
|
| 106 |
+
xaxis=dict(showgrid=True, gridcolor="#2a2a3a"),
|
| 107 |
+
yaxis=dict(showgrid=False),
|
| 108 |
+
)
|
| 109 |
+
st.plotly_chart(fig_cat, use_container_width=True, config={"displayModeBar": False})
|
| 110 |
+
else:
|
| 111 |
+
st.markdown("<p style='color:#5a5a7a'>No data for this range.</p>", unsafe_allow_html=True)
|
| 112 |
+
|
| 113 |
+
with col_r:
|
| 114 |
+
st.markdown("#### Top Apps Leaderboard")
|
| 115 |
+
apps_data = db.get_by_app(start, end, limit=10)
|
| 116 |
+
if apps_data:
|
| 117 |
+
df_apps = pd.DataFrame(apps_data)
|
| 118 |
+
df_apps["minutes"] = df_apps["total_seconds"] / 60
|
| 119 |
+
html = ""
|
| 120 |
+
max_min = df_apps["minutes"].max() or 1
|
| 121 |
+
for i, row in df_apps.iterrows():
|
| 122 |
+
cat = row.get("category", "uncategorized")
|
| 123 |
+
color = CATEGORY_COLORS.get(cat, "#6366f1")
|
| 124 |
+
pct = int((row["minutes"] / max_min) * 100)
|
| 125 |
+
rank = i + 1
|
| 126 |
+
html += f"""
|
| 127 |
+
<div style="display:flex; align-items:center; gap:10px; padding:8px 0; border-bottom:1px solid #1e1e2e;">
|
| 128 |
+
<div style="font-family:'DM Mono',monospace; font-size:0.8rem; color:#5a5a7a; min-width:20px;">#{rank}</div>
|
| 129 |
+
<div style="flex:1; min-width:0;">
|
| 130 |
+
<div style="font-size:0.85rem; font-weight:500; color:#f0f0ff; margin-bottom:3px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">{row['app_name'][:30]}</div>
|
| 131 |
+
<div style="background:#1e1e2e; border-radius:4px; height:4px;">
|
| 132 |
+
<div style="background:{color}; width:{pct}%; height:100%; border-radius:4px;"></div>
|
| 133 |
+
</div>
|
| 134 |
+
</div>
|
| 135 |
+
<div style="font-family:'DM Mono',monospace; font-size:0.8rem; color:#9090b0; min-width:55px; text-align:right;">{fmt_duration(row['total_seconds'])}</div>
|
| 136 |
+
</div>"""
|
| 137 |
+
st.markdown(f'<div style="font-family:Inter,sans-serif;">{html}</div>', unsafe_allow_html=True)
|
| 138 |
+
else:
|
| 139 |
+
st.markdown("<p style='color:#5a5a7a'>No data for this range.</p>", unsafe_allow_html=True)
|
| 140 |
+
|
| 141 |
+
# ── Weekly Heatmap ────────────────────────────────────────────────────────
|
| 142 |
+
if range_sel in ("Last 7 days", "Last 30 days", "Custom"):
|
| 143 |
+
st.markdown("#### Weekly Activity Heatmap (hours × days)")
|
| 144 |
+
acts = db.get_activities(start, end, limit=50000)
|
| 145 |
+
if acts:
|
| 146 |
+
df_all = pd.DataFrame(acts)
|
| 147 |
+
df_all["dt"] = pd.to_datetime(df_all["timestamp"])
|
| 148 |
+
df_all["hour"] = df_all["dt"].dt.hour
|
| 149 |
+
df_all["day"] = df_all["dt"].dt.strftime("%a %b %d")
|
| 150 |
+
heatmap = df_all.groupby(["day", "hour"])["duration_seconds"].sum().reset_index()
|
| 151 |
+
heatmap["minutes"] = heatmap["duration_seconds"] / 60
|
| 152 |
+
pivot = heatmap.pivot_table(index="day", columns="hour", values="minutes", fill_value=0)
|
| 153 |
+
|
| 154 |
+
fig_hm = go.Figure(go.Heatmap(
|
| 155 |
+
z=pivot.values,
|
| 156 |
+
x=[f"{h:02d}:00" for h in pivot.columns],
|
| 157 |
+
y=pivot.index.tolist(),
|
| 158 |
+
colorscale=[[0, "#0a0a0f"], [0.3, "#1a1a3a"], [0.7, "#4040a0"], [1, "#6366f1"]],
|
| 159 |
+
showscale=True,
|
| 160 |
+
hovertemplate="<b>%{y}</b> at <b>%{x}</b><br>%{z:.0f} minutes<extra></extra>",
|
| 161 |
+
))
|
| 162 |
+
fig_hm.update_layout(
|
| 163 |
+
height=max(200, len(pivot) * 30 + 80),
|
| 164 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 165 |
+
plot_bgcolor="rgba(0,0,0,0)",
|
| 166 |
+
font=dict(color="#9090b0", family="Inter"),
|
| 167 |
+
margin=dict(t=10, b=30, l=80, r=0),
|
| 168 |
+
xaxis=dict(tickfont=dict(size=9)),
|
| 169 |
+
yaxis=dict(tickfont=dict(size=9)),
|
| 170 |
+
)
|
| 171 |
+
st.plotly_chart(fig_hm, use_container_width=True, config={"displayModeBar": False})
|
| 172 |
+
|
| 173 |
+
# ── Export ────────────────────────────────────────────────────────────────
|
| 174 |
+
st.markdown("---")
|
| 175 |
+
st.markdown("#### Export Data")
|
| 176 |
+
col_ex1, col_ex2, col_ex3 = st.columns([1, 1, 4])
|
| 177 |
+
|
| 178 |
+
acts_for_export = db.get_activities(start, end, limit=100000)
|
| 179 |
+
if acts_for_export:
|
| 180 |
+
df_export = pd.DataFrame(acts_for_export)
|
| 181 |
+
|
| 182 |
+
with col_ex1:
|
| 183 |
+
csv_buf = df_export.to_csv(index=False).encode("utf-8")
|
| 184 |
+
st.download_button(
|
| 185 |
+
"📥 Export CSV", csv_buf,
|
| 186 |
+
file_name=f"focustrack_export_{start.date()}_{end.date()}.csv",
|
| 187 |
+
mime="text/csv", use_container_width=True
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
with col_ex2:
|
| 191 |
+
json_buf = df_export.to_json(orient="records", indent=2).encode("utf-8")
|
| 192 |
+
st.download_button(
|
| 193 |
+
"📥 Export JSON", json_buf,
|
| 194 |
+
file_name=f"focustrack_export_{start.date()}_{end.date()}.json",
|
| 195 |
+
mime="application/json", use_container_width=True
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
st.markdown("<p style='color:#5a5a7a; font-size:0.85rem;'>No data to export for selected range.</p>",
|
| 199 |
+
unsafe_allow_html=True)
|
app.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Streamlit Dashboard Entry Point
|
| 3 |
+
Run with: streamlit run app.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 9 |
+
|
| 10 |
+
import streamlit as st
|
| 11 |
+
from ui_utils import DARK_CSS, LIGHT_CSS, get_db
|
| 12 |
+
|
| 13 |
+
# ─── Page Config (must be first Streamlit call) ───────────────────────────────
|
| 14 |
+
st.set_page_config(
|
| 15 |
+
page_title="FocusTrack",
|
| 16 |
+
page_icon="🎯",
|
| 17 |
+
layout="wide",
|
| 18 |
+
initial_sidebar_state="expanded",
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# ─── Theme ────────────────────────────────────────────────────────────────────
|
| 22 |
+
db = get_db()
|
| 23 |
+
theme = db.get_setting("theme", "dark")
|
| 24 |
+
st.markdown(DARK_CSS if theme == "dark" else LIGHT_CSS, unsafe_allow_html=True)
|
| 25 |
+
|
| 26 |
+
# ─── Demo Mode Banner ─────────────────────────────────────────────────────────
|
| 27 |
+
import os
|
| 28 |
+
IS_HF = os.environ.get("SPACE_ID") is not None # True when running on HF Spaces
|
| 29 |
+
if IS_HF:
|
| 30 |
+
st.markdown("""
|
| 31 |
+
<div style="background:linear-gradient(90deg,#1a1a2e,#16213e);border:1px solid #6366f133;
|
| 32 |
+
border-radius:10px;padding:10px 16px;margin-bottom:1rem;font-size:0.82rem;
|
| 33 |
+
display:flex;align-items:center;gap:10px;color:#9090b0;">
|
| 34 |
+
<span style="font-size:1.1rem;">🎮</span>
|
| 35 |
+
<span><strong style="color:#6366f1;">Demo Mode</strong> — Live window tracking requires running locally on your laptop.
|
| 36 |
+
This demo shows 14 days of sample data.
|
| 37 |
+
<a href="https://github.com/yourname/focustrack" style="color:#22d3ee;">Get the full app →</a></span>
|
| 38 |
+
</div>
|
| 39 |
+
""", unsafe_allow_html=True)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ─── Sidebar ──────────────────────────────────────────────────────────────────
|
| 43 |
+
with st.sidebar:
|
| 44 |
+
# Logo
|
| 45 |
+
st.markdown("""
|
| 46 |
+
<div style="padding: 1rem 0 1.5rem; border-bottom: 1px solid #2a2a3a; margin-bottom: 1rem;">
|
| 47 |
+
<div style="display:flex; align-items:center; gap:10px;">
|
| 48 |
+
<div style="
|
| 49 |
+
width:36px; height:36px; border-radius:10px;
|
| 50 |
+
background: linear-gradient(135deg, #6366f1, #22d3ee);
|
| 51 |
+
display:flex; align-items:center; justify-content:center;
|
| 52 |
+
font-size:1.1rem; box-shadow: 0 4px 12px #6366f144;
|
| 53 |
+
">🎯</div>
|
| 54 |
+
<div>
|
| 55 |
+
<div style="font-family:'Syne',sans-serif; font-weight:800; font-size:1.1rem; color:#f0f0ff; letter-spacing:-0.02em;">FocusTrack</div>
|
| 56 |
+
<div style="font-size:0.68rem; color:#5a5a7a; letter-spacing:0.08em; text-transform:uppercase;">Productivity Tracker</div>
|
| 57 |
+
</div>
|
| 58 |
+
</div>
|
| 59 |
+
</div>
|
| 60 |
+
""", unsafe_allow_html=True)
|
| 61 |
+
|
| 62 |
+
# Navigation
|
| 63 |
+
nav_items = {
|
| 64 |
+
"🏠 Live Dashboard": "dashboard",
|
| 65 |
+
"📊 Analytics": "analytics",
|
| 66 |
+
"📋 Activity Log": "activity_log",
|
| 67 |
+
"⚙️ Settings": "settings",
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
if "page" not in st.session_state:
|
| 71 |
+
st.session_state.page = "dashboard"
|
| 72 |
+
|
| 73 |
+
for label, key in nav_items.items():
|
| 74 |
+
is_active = st.session_state.page == key
|
| 75 |
+
if st.button(
|
| 76 |
+
label,
|
| 77 |
+
key=f"nav_{key}",
|
| 78 |
+
use_container_width=True,
|
| 79 |
+
):
|
| 80 |
+
st.session_state.page = key
|
| 81 |
+
st.rerun()
|
| 82 |
+
|
| 83 |
+
# Tracker status badge
|
| 84 |
+
st.markdown("<div style='margin-top:1rem; border-top:1px solid #2a2a3a; padding-top:1rem;'></div>",
|
| 85 |
+
unsafe_allow_html=True)
|
| 86 |
+
|
| 87 |
+
tracker_status = db.get_setting("tracker_running", "true")
|
| 88 |
+
status_map = {
|
| 89 |
+
"true": ("● Tracking", "#10b981"),
|
| 90 |
+
"paused": ("● Paused", "#f59e0b"),
|
| 91 |
+
"false": ("● Stopped", "#f43f5e"),
|
| 92 |
+
}
|
| 93 |
+
s_label, s_color = status_map.get(tracker_status, ("● Unknown", "#6366f1"))
|
| 94 |
+
st.markdown(
|
| 95 |
+
f"<div style='font-size:0.78rem; font-weight:600; color:{s_color}; "
|
| 96 |
+
f"padding:6px 12px; background:{s_color}11; border-radius:8px; "
|
| 97 |
+
f"border:1px solid {s_color}33; text-align:center;'>{s_label}</div>",
|
| 98 |
+
unsafe_allow_html=True,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Privacy badge in sidebar
|
| 102 |
+
st.markdown("""
|
| 103 |
+
<div style="margin-top:auto; padding-top:2rem; font-size:0.7rem; color:#5a5a7a; text-align:center; line-height:1.5;">
|
| 104 |
+
🔒 100% private<br>All data stays on your device
|
| 105 |
+
</div>
|
| 106 |
+
""", unsafe_allow_html=True)
|
| 107 |
+
|
| 108 |
+
# ─── Main Content ─────────────────────────────────────────────────────────────
|
| 109 |
+
page = st.session_state.get("page", "dashboard")
|
| 110 |
+
|
| 111 |
+
if page == "dashboard":
|
| 112 |
+
from ui_pages.dashboard import render
|
| 113 |
+
render()
|
| 114 |
+
elif page == "analytics":
|
| 115 |
+
from ui_pages.analytics import render
|
| 116 |
+
render()
|
| 117 |
+
elif page == "activity_log":
|
| 118 |
+
from ui_pages.activity_log import render
|
| 119 |
+
render()
|
| 120 |
+
elif page == "settings":
|
| 121 |
+
from ui_pages.settings import render
|
| 122 |
+
render()
|
config.toml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[theme]
|
| 2 |
+
base = "dark"
|
| 3 |
+
primaryColor = "#6366f1"
|
| 4 |
+
backgroundColor = "#0a0a0f"
|
| 5 |
+
secondaryBackgroundColor = "#111118"
|
| 6 |
+
textColor = "#f0f0ff"
|
| 7 |
+
font = "sans serif"
|
| 8 |
+
|
| 9 |
+
[server]
|
| 10 |
+
port = 7860
|
| 11 |
+
address = "0.0.0.0"
|
| 12 |
+
headless = true
|
| 13 |
+
enableCORS = false
|
| 14 |
+
enableXsrfProtection = false
|
| 15 |
+
|
| 16 |
+
[browser]
|
| 17 |
+
gatherUsageStats = false
|
dashboard.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Page 1: Live Dashboard
|
| 3 |
+
Real-time activity overview with charts and controls.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import plotly.express as px
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from datetime import datetime, timedelta, date
|
| 11 |
+
|
| 12 |
+
from ui_utils import (
|
| 13 |
+
fmt_duration, fmt_duration_long, get_focus_score,
|
| 14 |
+
privacy_badge, page_header, status_dot, category_pill,
|
| 15 |
+
CATEGORY_COLORS, get_db
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def render():
|
| 20 |
+
db = get_db()
|
| 21 |
+
privacy_badge()
|
| 22 |
+
page_header("Live Dashboard", "Real-time activity overview")
|
| 23 |
+
|
| 24 |
+
# ── Current Session Card ──────────────────────────────────────────────────
|
| 25 |
+
latest = db.get_latest_activity()
|
| 26 |
+
tracker_status = db.get_setting("tracker_running", "true")
|
| 27 |
+
|
| 28 |
+
status_label = {
|
| 29 |
+
"true": ("running", "#10b981"),
|
| 30 |
+
"paused": ("paused", "#f59e0b"),
|
| 31 |
+
"false": ("stopped", "#f43f5e"),
|
| 32 |
+
}.get(tracker_status, ("unknown", "#6366f1"))
|
| 33 |
+
|
| 34 |
+
app_name = latest.get("app_name", "—") if latest else "—"
|
| 35 |
+
window = latest.get("window_title", "—") if latest else "—"
|
| 36 |
+
category = latest.get("category", "—") if latest else "—"
|
| 37 |
+
cat_color = CATEGORY_COLORS.get(category, "#6366f1")
|
| 38 |
+
|
| 39 |
+
st.markdown(f"""
|
| 40 |
+
<div style="
|
| 41 |
+
background: linear-gradient(135deg, #16161f 0%, #1a1a2a 100%);
|
| 42 |
+
border: 1px solid #2a2a3a; border-left: 4px solid {cat_color};
|
| 43 |
+
border-radius: 16px; padding: 1.5rem 2rem; margin-bottom: 1.5rem;
|
| 44 |
+
display: flex; justify-content: space-between; align-items: center;
|
| 45 |
+
box-shadow: 0 4px 20px rgba(0,0,0,0.3);
|
| 46 |
+
">
|
| 47 |
+
<div>
|
| 48 |
+
<div style="display:flex; align-items:center; gap:10px; margin-bottom:6px;">
|
| 49 |
+
<span style="font-size:0.75rem; color:#9090b0; font-family:'DM Mono',monospace; text-transform:uppercase; letter-spacing:0.1em;">NOW TRACKING</span>
|
| 50 |
+
<span style="background:{status_label[1]}22; color:{status_label[1]}; border:1px solid {status_label[1]}44; border-radius:20px; padding:2px 10px; font-size:0.7rem; font-weight:600;">● {status_label[0].upper()}</span>
|
| 51 |
+
</div>
|
| 52 |
+
<div style="font-family:'Syne',sans-serif; font-size:1.6rem; font-weight:700; color:#f0f0ff; margin-bottom:4px; letter-spacing:-0.02em;">
|
| 53 |
+
{app_name[:60]}
|
| 54 |
+
</div>
|
| 55 |
+
<div style="color:#9090b0; font-size:0.85rem; margin-bottom:8px; max-width:600px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
|
| 56 |
+
{window[:80]}
|
| 57 |
+
</div>
|
| 58 |
+
<span style="background:{cat_color}22; color:{cat_color}; border:1px solid {cat_color}44; border-radius:20px; padding:3px 12px; font-size:0.72rem; font-weight:600; font-family:'DM Mono',monospace;">
|
| 59 |
+
{category}
|
| 60 |
+
</span>
|
| 61 |
+
</div>
|
| 62 |
+
<div style="text-align:right; color:#9090b0; font-family:'DM Mono',monospace; font-size:0.8rem;">
|
| 63 |
+
{datetime.now().strftime("%H:%M:%S")}
|
| 64 |
+
</div>
|
| 65 |
+
</div>
|
| 66 |
+
""", unsafe_allow_html=True)
|
| 67 |
+
|
| 68 |
+
# ── Summary Metrics ────────────────────────────────────────────────────────
|
| 69 |
+
today_start = datetime.combine(date.today(), datetime.min.time())
|
| 70 |
+
today_end = datetime.combine(date.today(), datetime.max.time())
|
| 71 |
+
summary = db.get_summary(today_start, today_end)
|
| 72 |
+
|
| 73 |
+
focus_sec = summary.get("focus_seconds") or 0
|
| 74 |
+
idle_sec = summary.get("idle_seconds") or 0
|
| 75 |
+
total_sec = summary.get("total_seconds") or 0
|
| 76 |
+
focus_score = get_focus_score(focus_sec, total_sec)
|
| 77 |
+
|
| 78 |
+
top_apps = db.get_by_app(today_start, today_end, limit=1)
|
| 79 |
+
top_app = top_apps[0]["app_name"] if top_apps else "—"
|
| 80 |
+
|
| 81 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 82 |
+
with c1:
|
| 83 |
+
st.metric("🎯 Focus Today", fmt_duration_long(focus_sec),
|
| 84 |
+
delta=f"+{fmt_duration(focus_sec)}" if focus_sec > 0 else None)
|
| 85 |
+
with c2:
|
| 86 |
+
st.metric("💤 Idle Time", fmt_duration_long(idle_sec))
|
| 87 |
+
with c3:
|
| 88 |
+
pct_color = "normal" if focus_score >= 60 else "inverse"
|
| 89 |
+
st.metric("📊 Focus Score", f"{focus_score}%",
|
| 90 |
+
delta="Good" if focus_score >= 60 else "Low",
|
| 91 |
+
delta_color=pct_color)
|
| 92 |
+
with c4:
|
| 93 |
+
st.metric("🏆 Top App", top_app[:20] if top_app != "—" else "—")
|
| 94 |
+
|
| 95 |
+
st.markdown("<div style='height:1rem'></div>", unsafe_allow_html=True)
|
| 96 |
+
|
| 97 |
+
# ── Controls ──────────────────────────────────────────────────────────────
|
| 98 |
+
st.markdown("**Tracker Controls**")
|
| 99 |
+
col1, col2, col3, col4 = st.columns([1, 1, 1, 4])
|
| 100 |
+
with col1:
|
| 101 |
+
if st.button("▶ Start", use_container_width=True):
|
| 102 |
+
db.set_setting("tracker_running", "true")
|
| 103 |
+
st.toast("✅ Tracker started!", icon="▶")
|
| 104 |
+
st.rerun()
|
| 105 |
+
with col2:
|
| 106 |
+
if st.button("⏸ Pause", use_container_width=True):
|
| 107 |
+
db.set_setting("tracker_running", "paused")
|
| 108 |
+
st.toast("⏸ Tracker paused", icon="⏸")
|
| 109 |
+
st.rerun()
|
| 110 |
+
with col3:
|
| 111 |
+
if st.button("⏹ Stop", use_container_width=True):
|
| 112 |
+
db.set_setting("tracker_running", "false")
|
| 113 |
+
st.toast("⏹ Tracker stopped", icon="⏹")
|
| 114 |
+
st.rerun()
|
| 115 |
+
|
| 116 |
+
st.markdown("<div style='height:0.5rem'></div>", unsafe_allow_html=True)
|
| 117 |
+
|
| 118 |
+
# ── Charts Row ────────────────────────────────────────────────────────────
|
| 119 |
+
col_left, col_right = st.columns([1.1, 1.9])
|
| 120 |
+
|
| 121 |
+
with col_left:
|
| 122 |
+
st.markdown("#### Time by Category")
|
| 123 |
+
cat_data = db.get_by_category(today_start, today_end)
|
| 124 |
+
if cat_data:
|
| 125 |
+
df_cat = pd.DataFrame(cat_data)
|
| 126 |
+
df_cat["minutes"] = df_cat["total_seconds"] / 60
|
| 127 |
+
df_cat["label"] = df_cat.apply(
|
| 128 |
+
lambda r: f"{r['category']} ({fmt_duration(r['total_seconds'])})", axis=1
|
| 129 |
+
)
|
| 130 |
+
colors = [CATEGORY_COLORS.get(c, "#6366f1") for c in df_cat["category"]]
|
| 131 |
+
fig = go.Figure(go.Pie(
|
| 132 |
+
labels=df_cat["category"],
|
| 133 |
+
values=df_cat["minutes"],
|
| 134 |
+
hole=0.55,
|
| 135 |
+
marker=dict(colors=colors, line=dict(width=2, color="#0a0a0f")),
|
| 136 |
+
textinfo="label+percent",
|
| 137 |
+
textfont=dict(size=11, family="Inter"),
|
| 138 |
+
hovertemplate="<b>%{label}</b><br>%{value:.0f} min<br>%{percent}<extra></extra>",
|
| 139 |
+
))
|
| 140 |
+
fig.update_layout(
|
| 141 |
+
showlegend=False,
|
| 142 |
+
margin=dict(t=20, b=20, l=20, r=20),
|
| 143 |
+
height=300,
|
| 144 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 145 |
+
plot_bgcolor="rgba(0,0,0,0)",
|
| 146 |
+
font=dict(color="#9090b0", family="Inter"),
|
| 147 |
+
annotations=[dict(
|
| 148 |
+
text=f"<b>{fmt_duration(focus_sec)}</b>",
|
| 149 |
+
x=0.5, y=0.5, font_size=16,
|
| 150 |
+
font_family="Syne", font_color="#f0f0ff",
|
| 151 |
+
showarrow=False
|
| 152 |
+
)]
|
| 153 |
+
)
|
| 154 |
+
st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})
|
| 155 |
+
else:
|
| 156 |
+
st.markdown("""
|
| 157 |
+
<div style="height:280px; display:flex; align-items:center; justify-content:center;
|
| 158 |
+
color:#5a5a7a; font-size:0.9rem; border:1px dashed #2a2a3a; border-radius:12px;">
|
| 159 |
+
No data yet today. Start the tracker to begin.
|
| 160 |
+
</div>""", unsafe_allow_html=True)
|
| 161 |
+
|
| 162 |
+
with col_right:
|
| 163 |
+
st.markdown("#### Hourly Activity Timeline")
|
| 164 |
+
hourly = db.get_hourly_timeline(date.today())
|
| 165 |
+
if hourly:
|
| 166 |
+
df_h = pd.DataFrame(hourly)
|
| 167 |
+
df_h["hour_label"] = df_h["hour"].apply(lambda h: f"{int(h):02d}:00")
|
| 168 |
+
df_h["minutes"] = df_h["total_seconds"] / 60
|
| 169 |
+
df_h["color"] = df_h["category"].map(lambda c: CATEGORY_COLORS.get(c, "#6366f1"))
|
| 170 |
+
|
| 171 |
+
fig2 = px.bar(
|
| 172 |
+
df_h, x="hour_label", y="minutes",
|
| 173 |
+
color="category",
|
| 174 |
+
color_discrete_map=CATEGORY_COLORS,
|
| 175 |
+
labels={"hour_label": "Hour", "minutes": "Minutes"},
|
| 176 |
+
barmode="stack",
|
| 177 |
+
)
|
| 178 |
+
fig2.update_layout(
|
| 179 |
+
margin=dict(t=20, b=30, l=0, r=0),
|
| 180 |
+
height=300,
|
| 181 |
+
paper_bgcolor="rgba(0,0,0,0)",
|
| 182 |
+
plot_bgcolor="rgba(0,0,0,0)",
|
| 183 |
+
font=dict(color="#9090b0", family="Inter"),
|
| 184 |
+
xaxis=dict(showgrid=False, tickfont=dict(size=10)),
|
| 185 |
+
yaxis=dict(showgrid=True, gridcolor="#2a2a3a", tickfont=dict(size=10)),
|
| 186 |
+
legend=dict(
|
| 187 |
+
orientation="h", yanchor="bottom", y=1.02,
|
| 188 |
+
xanchor="left", x=0, font=dict(size=10)
|
| 189 |
+
),
|
| 190 |
+
bargap=0.15,
|
| 191 |
+
)
|
| 192 |
+
st.plotly_chart(fig2, use_container_width=True, config={"displayModeBar": False})
|
| 193 |
+
else:
|
| 194 |
+
st.markdown("""
|
| 195 |
+
<div style="height:280px; display:flex; align-items:center; justify-content:center;
|
| 196 |
+
color:#5a5a7a; font-size:0.9rem; border:1px dashed #2a2a3a; border-radius:12px;">
|
| 197 |
+
No hourly data yet for today.
|
| 198 |
+
</div>""", unsafe_allow_html=True)
|
| 199 |
+
|
| 200 |
+
# ── Top Apps Table ────────────────────────────────────────────────────────
|
| 201 |
+
st.markdown("#### Top Apps Today")
|
| 202 |
+
top_apps_data = db.get_by_app(today_start, today_end, limit=8)
|
| 203 |
+
if top_apps_data:
|
| 204 |
+
df_apps = pd.DataFrame(top_apps_data)
|
| 205 |
+
df_apps["time"] = df_apps["total_seconds"].apply(fmt_duration_long)
|
| 206 |
+
df_apps["pct"] = df_apps["total_seconds"].apply(
|
| 207 |
+
lambda s: f"{(s / focus_sec * 100):.0f}%" if focus_sec > 0 else "—"
|
| 208 |
+
)
|
| 209 |
+
# Render as styled rows
|
| 210 |
+
html_rows = ""
|
| 211 |
+
for _, row in df_apps.iterrows():
|
| 212 |
+
cat = row.get("category", "uncategorized")
|
| 213 |
+
color = CATEGORY_COLORS.get(cat, "#6366f1")
|
| 214 |
+
bar_w = int((row["total_seconds"] / (df_apps["total_seconds"].max() or 1)) * 100)
|
| 215 |
+
html_rows += f"""
|
| 216 |
+
<tr style="border-bottom:1px solid #1e1e2e;">
|
| 217 |
+
<td style="padding:10px 12px; font-weight:500; color:#f0f0ff;">{row['app_name'][:40]}</td>
|
| 218 |
+
<td style="padding:10px 12px;">
|
| 219 |
+
<span style="background:{color}22; color:{color}; border:1px solid {color}44;
|
| 220 |
+
border-radius:20px; padding:2px 8px; font-size:0.7rem; font-family:'DM Mono',monospace;">{cat}</span>
|
| 221 |
+
</td>
|
| 222 |
+
<td style="padding:10px 12px; font-family:'DM Mono',monospace; font-size:0.85rem;">{row['time']}</td>
|
| 223 |
+
<td style="padding:10px 24px 10px 12px; min-width:120px;">
|
| 224 |
+
<div style="background:#1e1e2e; border-radius:4px; height:6px; overflow:hidden;">
|
| 225 |
+
<div style="background:{color}; width:{bar_w}%; height:100%; border-radius:4px;"></div>
|
| 226 |
+
</div>
|
| 227 |
+
</td>
|
| 228 |
+
</tr>"""
|
| 229 |
+
|
| 230 |
+
st.markdown(f"""
|
| 231 |
+
<table style="width:100%; border-collapse:collapse; font-size:0.85rem; font-family:'Inter',sans-serif;">
|
| 232 |
+
<thead>
|
| 233 |
+
<tr style="color:#5a5a7a; font-size:0.72rem; text-transform:uppercase; letter-spacing:0.08em; border-bottom:1px solid #2a2a3a;">
|
| 234 |
+
<th style="text-align:left; padding:8px 12px; font-weight:500;">App</th>
|
| 235 |
+
<th style="text-align:left; padding:8px 12px; font-weight:500;">Category</th>
|
| 236 |
+
<th style="text-align:left; padding:8px 12px; font-weight:500;">Time</th>
|
| 237 |
+
<th style="text-align:left; padding:8px 24px 8px 12px; font-weight:500;">Share</th>
|
| 238 |
+
</tr>
|
| 239 |
+
</thead>
|
| 240 |
+
<tbody>{html_rows}</tbody>
|
| 241 |
+
</table>
|
| 242 |
+
""", unsafe_allow_html=True)
|
| 243 |
+
else:
|
| 244 |
+
st.markdown("<p style='color:#5a5a7a; font-size:0.85rem;'>No app data yet. Start tracking!</p>",
|
| 245 |
+
unsafe_allow_html=True)
|
| 246 |
+
|
| 247 |
+
# Auto-refresh every 10 seconds
|
| 248 |
+
if st.session_state.get("auto_refresh", True):
|
| 249 |
+
import time
|
| 250 |
+
st.markdown("""
|
| 251 |
+
<script>
|
| 252 |
+
setTimeout(() => window.location.reload(), 15000);
|
| 253 |
+
</script>""", unsafe_allow_html=True)
|
database.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Database Layer
|
| 3 |
+
SQLite-based local storage. Zero cloud, zero accounts.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sqlite3
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from datetime import datetime, date
|
| 11 |
+
from typing import Optional, List, Dict, Any
|
| 12 |
+
import threading
|
| 13 |
+
|
| 14 |
+
logger = logging.getLogger("focustrack.database")
|
| 15 |
+
|
| 16 |
+
DB_PATH = Path(__file__).parent / "data" / "activity.db"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Database:
|
| 20 |
+
"""Thread-safe SQLite database manager for FocusTrack."""
|
| 21 |
+
|
| 22 |
+
def __init__(self, db_path: Path = DB_PATH):
|
| 23 |
+
self.db_path = db_path
|
| 24 |
+
self.db_path.parent.mkdir(exist_ok=True)
|
| 25 |
+
self._local = threading.local()
|
| 26 |
+
|
| 27 |
+
def _get_conn(self) -> sqlite3.Connection:
|
| 28 |
+
"""Get thread-local database connection."""
|
| 29 |
+
if not hasattr(self._local, "conn") or self._local.conn is None:
|
| 30 |
+
self._local.conn = sqlite3.connect(
|
| 31 |
+
str(self.db_path),
|
| 32 |
+
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
|
| 33 |
+
check_same_thread=False,
|
| 34 |
+
)
|
| 35 |
+
self._local.conn.row_factory = sqlite3.Row
|
| 36 |
+
self._local.conn.execute("PRAGMA journal_mode=WAL")
|
| 37 |
+
self._local.conn.execute("PRAGMA synchronous=NORMAL")
|
| 38 |
+
return self._local.conn
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def conn(self) -> sqlite3.Connection:
|
| 42 |
+
return self._get_conn()
|
| 43 |
+
|
| 44 |
+
def initialize(self):
|
| 45 |
+
"""Create tables and default data."""
|
| 46 |
+
self.conn.executescript("""
|
| 47 |
+
CREATE TABLE IF NOT EXISTS activities (
|
| 48 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 49 |
+
timestamp DATETIME NOT NULL,
|
| 50 |
+
app_name TEXT NOT NULL,
|
| 51 |
+
window_title TEXT NOT NULL,
|
| 52 |
+
duration_seconds INTEGER DEFAULT 0,
|
| 53 |
+
category TEXT DEFAULT 'uncategorized',
|
| 54 |
+
is_idle BOOLEAN DEFAULT 0
|
| 55 |
+
);
|
| 56 |
+
|
| 57 |
+
CREATE INDEX IF NOT EXISTS idx_activities_timestamp
|
| 58 |
+
ON activities(timestamp);
|
| 59 |
+
CREATE INDEX IF NOT EXISTS idx_activities_app
|
| 60 |
+
ON activities(app_name);
|
| 61 |
+
|
| 62 |
+
CREATE TABLE IF NOT EXISTS settings (
|
| 63 |
+
key TEXT PRIMARY KEY,
|
| 64 |
+
value TEXT NOT NULL
|
| 65 |
+
);
|
| 66 |
+
|
| 67 |
+
CREATE TABLE IF NOT EXISTS categories (
|
| 68 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 69 |
+
name TEXT UNIQUE NOT NULL,
|
| 70 |
+
color TEXT DEFAULT '#6366f1',
|
| 71 |
+
keywords TEXT DEFAULT '[]',
|
| 72 |
+
apps TEXT DEFAULT '[]'
|
| 73 |
+
);
|
| 74 |
+
""")
|
| 75 |
+
self.conn.commit()
|
| 76 |
+
self._seed_defaults()
|
| 77 |
+
logger.info(f"Database ready at {self.db_path}")
|
| 78 |
+
|
| 79 |
+
def _seed_defaults(self):
|
| 80 |
+
"""Insert default settings and categories if not present."""
|
| 81 |
+
defaults = {
|
| 82 |
+
"idle_threshold_seconds": "300",
|
| 83 |
+
"heartbeat_interval": "5",
|
| 84 |
+
"theme": "dark",
|
| 85 |
+
"auto_start": "false",
|
| 86 |
+
"ignored_apps": '["Finder", "explorer.exe"]',
|
| 87 |
+
"tracker_running": "true",
|
| 88 |
+
}
|
| 89 |
+
for key, value in defaults.items():
|
| 90 |
+
self.conn.execute(
|
| 91 |
+
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)",
|
| 92 |
+
(key, value)
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
default_categories = [
|
| 96 |
+
("coding", "#22d3ee", '["code", "terminal", "vim", "emacs", "debug"]', '["code", "cursor", "vscode", "pycharm", "intellij", "xcode", "terminal", "iterm", "warp", "alacritty", "sublime", "atom", "neovim"]'),
|
| 97 |
+
("browsing", "#f59e0b", '["http", "www", "chrome", "firefox", "safari"]', '["chrome", "firefox", "safari", "edge", "brave", "opera"]'),
|
| 98 |
+
("communication", "#10b981", '["mail", "slack", "teams", "discord", "zoom"]', '["slack", "discord", "teams", "zoom", "meet", "mail", "outlook", "telegram", "whatsapp"]'),
|
| 99 |
+
("design", "#a78bfa", '["figma", "sketch", "photoshop", "illustrator"]','["figma", "sketch", "photoshop", "illustrator", "xd", "canva", "affinity"]'),
|
| 100 |
+
("documents", "#fb923c", '["word", "excel", "sheets", "docs", "notion"]', '["word", "excel", "notion", "obsidian", "pages", "numbers", "libreoffice"]'),
|
| 101 |
+
("media", "#f43f5e", '["youtube", "spotify", "vlc", "netflix"]', '["spotify", "vlc", "quicktime", "itunes", "music"]'),
|
| 102 |
+
("system", "#64748b", '["settings", "finder", "explorer"]', '["finder", "explorer", "systempreferences", "taskmanager"]'),
|
| 103 |
+
("idle", "#374151", '[]', '[]'),
|
| 104 |
+
]
|
| 105 |
+
for cat in default_categories:
|
| 106 |
+
self.conn.execute(
|
| 107 |
+
"INSERT OR IGNORE INTO categories (name, color, keywords, apps) VALUES (?,?,?,?)",
|
| 108 |
+
cat
|
| 109 |
+
)
|
| 110 |
+
self.conn.commit()
|
| 111 |
+
|
| 112 |
+
# ─── Activity CRUD ───────────────────────────────────────────────────────
|
| 113 |
+
|
| 114 |
+
def log_activity(self, timestamp: datetime, app_name: str, window_title: str,
|
| 115 |
+
duration_seconds: int, category: str, is_idle: bool):
|
| 116 |
+
self.conn.execute(
|
| 117 |
+
"""INSERT INTO activities
|
| 118 |
+
(timestamp, app_name, window_title, duration_seconds, category, is_idle)
|
| 119 |
+
VALUES (?,?,?,?,?,?)""",
|
| 120 |
+
(timestamp.isoformat(), app_name, window_title,
|
| 121 |
+
duration_seconds, category, int(is_idle))
|
| 122 |
+
)
|
| 123 |
+
self.conn.commit()
|
| 124 |
+
|
| 125 |
+
def get_activities(self, start: datetime, end: datetime,
|
| 126 |
+
search: str = "", limit: int = 500, offset: int = 0) -> List[Dict]:
|
| 127 |
+
query = """
|
| 128 |
+
SELECT * FROM activities
|
| 129 |
+
WHERE timestamp BETWEEN ? AND ?
|
| 130 |
+
"""
|
| 131 |
+
params: list = [start.isoformat(), end.isoformat()]
|
| 132 |
+
if search:
|
| 133 |
+
query += " AND (app_name LIKE ? OR window_title LIKE ? OR category LIKE ?)"
|
| 134 |
+
params += [f"%{search}%", f"%{search}%", f"%{search}%"]
|
| 135 |
+
query += " ORDER BY timestamp DESC LIMIT ? OFFSET ?"
|
| 136 |
+
params += [limit, offset]
|
| 137 |
+
rows = self.conn.execute(query, params).fetchall()
|
| 138 |
+
return [dict(r) for r in rows]
|
| 139 |
+
|
| 140 |
+
def get_activity_count(self, start: datetime, end: datetime, search: str = "") -> int:
|
| 141 |
+
query = "SELECT COUNT(*) FROM activities WHERE timestamp BETWEEN ? AND ?"
|
| 142 |
+
params: list = [start.isoformat(), end.isoformat()]
|
| 143 |
+
if search:
|
| 144 |
+
query += " AND (app_name LIKE ? OR window_title LIKE ? OR category LIKE ?)"
|
| 145 |
+
params += [f"%{search}%", f"%{search}%", f"%{search}%"]
|
| 146 |
+
return self.conn.execute(query, params).fetchone()[0]
|
| 147 |
+
|
| 148 |
+
def get_summary(self, start: datetime, end: datetime) -> Dict[str, Any]:
|
| 149 |
+
"""Aggregate stats for dashboard cards."""
|
| 150 |
+
row = self.conn.execute("""
|
| 151 |
+
SELECT
|
| 152 |
+
SUM(CASE WHEN is_idle=0 THEN duration_seconds ELSE 0 END) as focus_seconds,
|
| 153 |
+
SUM(CASE WHEN is_idle=1 THEN duration_seconds ELSE 0 END) as idle_seconds,
|
| 154 |
+
SUM(duration_seconds) as total_seconds,
|
| 155 |
+
COUNT(DISTINCT app_name) as unique_apps
|
| 156 |
+
FROM activities
|
| 157 |
+
WHERE timestamp BETWEEN ? AND ?
|
| 158 |
+
""", (start.isoformat(), end.isoformat())).fetchone()
|
| 159 |
+
return dict(row) if row else {}
|
| 160 |
+
|
| 161 |
+
def get_by_category(self, start: datetime, end: datetime) -> List[Dict]:
|
| 162 |
+
rows = self.conn.execute("""
|
| 163 |
+
SELECT category,
|
| 164 |
+
SUM(duration_seconds) as total_seconds,
|
| 165 |
+
COUNT(*) as sessions
|
| 166 |
+
FROM activities
|
| 167 |
+
WHERE timestamp BETWEEN ? AND ? AND is_idle=0
|
| 168 |
+
GROUP BY category
|
| 169 |
+
ORDER BY total_seconds DESC
|
| 170 |
+
""", (start.isoformat(), end.isoformat())).fetchall()
|
| 171 |
+
return [dict(r) for r in rows]
|
| 172 |
+
|
| 173 |
+
def get_by_app(self, start: datetime, end: datetime, limit: int = 10) -> List[Dict]:
|
| 174 |
+
rows = self.conn.execute("""
|
| 175 |
+
SELECT app_name, category,
|
| 176 |
+
SUM(duration_seconds) as total_seconds,
|
| 177 |
+
COUNT(*) as sessions
|
| 178 |
+
FROM activities
|
| 179 |
+
WHERE timestamp BETWEEN ? AND ? AND is_idle=0
|
| 180 |
+
GROUP BY app_name
|
| 181 |
+
ORDER BY total_seconds DESC
|
| 182 |
+
LIMIT ?
|
| 183 |
+
""", (start.isoformat(), end.isoformat(), limit)).fetchall()
|
| 184 |
+
return [dict(r) for r in rows]
|
| 185 |
+
|
| 186 |
+
def get_hourly_timeline(self, target_date: date) -> List[Dict]:
|
| 187 |
+
start = datetime.combine(target_date, datetime.min.time())
|
| 188 |
+
end = datetime.combine(target_date, datetime.max.time())
|
| 189 |
+
rows = self.conn.execute("""
|
| 190 |
+
SELECT strftime('%H', timestamp) as hour,
|
| 191 |
+
category,
|
| 192 |
+
SUM(duration_seconds) as total_seconds
|
| 193 |
+
FROM activities
|
| 194 |
+
WHERE timestamp BETWEEN ? AND ? AND is_idle=0
|
| 195 |
+
GROUP BY hour, category
|
| 196 |
+
ORDER BY hour
|
| 197 |
+
""", (start.isoformat(), end.isoformat())).fetchall()
|
| 198 |
+
return [dict(r) for r in rows]
|
| 199 |
+
|
| 200 |
+
def get_daily_totals(self, start: datetime, end: datetime) -> List[Dict]:
|
| 201 |
+
rows = self.conn.execute("""
|
| 202 |
+
SELECT date(timestamp) as day,
|
| 203 |
+
SUM(CASE WHEN is_idle=0 THEN duration_seconds ELSE 0 END) as focus_seconds,
|
| 204 |
+
SUM(CASE WHEN is_idle=1 THEN duration_seconds ELSE 0 END) as idle_seconds
|
| 205 |
+
FROM activities
|
| 206 |
+
WHERE timestamp BETWEEN ? AND ?
|
| 207 |
+
GROUP BY day
|
| 208 |
+
ORDER BY day
|
| 209 |
+
""", (start.isoformat(), end.isoformat())).fetchall()
|
| 210 |
+
return [dict(r) for r in rows]
|
| 211 |
+
|
| 212 |
+
def get_latest_activity(self) -> Optional[Dict]:
|
| 213 |
+
row = self.conn.execute(
|
| 214 |
+
"SELECT * FROM activities ORDER BY timestamp DESC LIMIT 1"
|
| 215 |
+
).fetchone()
|
| 216 |
+
return dict(row) if row else None
|
| 217 |
+
|
| 218 |
+
# ─── Settings ────────────────────────────────────────────────────────────
|
| 219 |
+
|
| 220 |
+
def get_setting(self, key: str, default: Any = None) -> Any:
|
| 221 |
+
row = self.conn.execute(
|
| 222 |
+
"SELECT value FROM settings WHERE key=?", (key,)
|
| 223 |
+
).fetchone()
|
| 224 |
+
return row[0] if row else default
|
| 225 |
+
|
| 226 |
+
def set_setting(self, key: str, value: Any):
|
| 227 |
+
self.conn.execute(
|
| 228 |
+
"INSERT OR REPLACE INTO settings (key, value) VALUES (?,?)",
|
| 229 |
+
(key, str(value))
|
| 230 |
+
)
|
| 231 |
+
self.conn.commit()
|
| 232 |
+
|
| 233 |
+
def get_all_settings(self) -> Dict[str, str]:
|
| 234 |
+
rows = self.conn.execute("SELECT key, value FROM settings").fetchall()
|
| 235 |
+
return {r[0]: r[1] for r in rows}
|
| 236 |
+
|
| 237 |
+
# ─── Categories ──────────────────────────────────────────────────────────
|
| 238 |
+
|
| 239 |
+
def get_categories(self) -> List[Dict]:
|
| 240 |
+
rows = self.conn.execute("SELECT * FROM categories ORDER BY name").fetchall()
|
| 241 |
+
return [dict(r) for r in rows]
|
| 242 |
+
|
| 243 |
+
def upsert_category(self, name: str, color: str, keywords: list, apps: list):
|
| 244 |
+
self.conn.execute("""
|
| 245 |
+
INSERT OR REPLACE INTO categories (name, color, keywords, apps)
|
| 246 |
+
VALUES (?,?,?,?)
|
| 247 |
+
""", (name, color, json.dumps(keywords), json.dumps(apps)))
|
| 248 |
+
self.conn.commit()
|
| 249 |
+
|
| 250 |
+
def delete_category(self, name: str):
|
| 251 |
+
self.conn.execute("DELETE FROM categories WHERE name=?", (name,))
|
| 252 |
+
self.conn.commit()
|
| 253 |
+
|
| 254 |
+
# ─── Maintenance ─────────────────────────────────────────────────────────
|
| 255 |
+
|
| 256 |
+
def clear_all_data(self):
|
| 257 |
+
self.conn.execute("DELETE FROM activities")
|
| 258 |
+
self.conn.commit()
|
| 259 |
+
logger.warning("All activity data cleared")
|
| 260 |
+
|
| 261 |
+
def get_db_size_mb(self) -> float:
|
| 262 |
+
try:
|
| 263 |
+
return self.db_path.stat().st_size / (1024 * 1024)
|
| 264 |
+
except Exception:
|
| 265 |
+
return 0.0
|
main.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Main Entry Point
|
| 3 |
+
Starts the tracker service and optionally the dashboard.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import os
|
| 8 |
+
import argparse
|
| 9 |
+
import threading
|
| 10 |
+
import subprocess
|
| 11 |
+
import logging
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
# Add project root to path
|
| 15 |
+
ROOT = Path(__file__).parent
|
| 16 |
+
sys.path.insert(0, str(ROOT))
|
| 17 |
+
|
| 18 |
+
# ── Create required directories BEFORE logging setup ──────────────────────────
|
| 19 |
+
(ROOT / "logs").mkdir(exist_ok=True)
|
| 20 |
+
(ROOT / "data").mkdir(exist_ok=True)
|
| 21 |
+
|
| 22 |
+
from tracker import ActivityTracker
|
| 23 |
+
from database import Database
|
| 24 |
+
|
| 25 |
+
logging.basicConfig(
|
| 26 |
+
level=logging.INFO,
|
| 27 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 28 |
+
handlers=[
|
| 29 |
+
logging.FileHandler(ROOT / "logs" / "focustrack.log"),
|
| 30 |
+
logging.StreamHandler(),
|
| 31 |
+
],
|
| 32 |
+
)
|
| 33 |
+
logger = logging.getLogger("focustrack.main")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def start_dashboard():
|
| 37 |
+
"""Launch the Streamlit dashboard in a subprocess."""
|
| 38 |
+
ui_path = Path(__file__).parent / "app.py"
|
| 39 |
+
cmd = [sys.executable, "-m", "streamlit", "run", str(ui_path),
|
| 40 |
+
"--server.port", "8501",
|
| 41 |
+
"--server.headless", "true",
|
| 42 |
+
"--server.address", "localhost",
|
| 43 |
+
"--browser.gatherUsageStats", "false"]
|
| 44 |
+
logger.info("Starting FocusTrack Dashboard at http://localhost:8501")
|
| 45 |
+
proc = subprocess.Popen(cmd)
|
| 46 |
+
return proc
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def start_tray(tracker: ActivityTracker):
|
| 50 |
+
"""Start system tray icon (optional, graceful fallback)."""
|
| 51 |
+
try:
|
| 52 |
+
from tray import TrayApp
|
| 53 |
+
tray = TrayApp(tracker)
|
| 54 |
+
tray.run()
|
| 55 |
+
except Exception as e:
|
| 56 |
+
logger.warning(f"System tray unavailable: {e}. Running headless.")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main():
|
| 60 |
+
parser = argparse.ArgumentParser(description="FocusTrack - Local Activity Tracker")
|
| 61 |
+
parser.add_argument("--no-tray", action="store_true", help="Disable system tray")
|
| 62 |
+
parser.add_argument("--no-dashboard", action="store_true", help="Don't open browser dashboard")
|
| 63 |
+
parser.add_argument("--tracker-only", action="store_true", help="Run tracker without dashboard")
|
| 64 |
+
args = parser.parse_args()
|
| 65 |
+
|
| 66 |
+
# Initialize database
|
| 67 |
+
db = Database()
|
| 68 |
+
db.initialize()
|
| 69 |
+
logger.info("Database initialized")
|
| 70 |
+
|
| 71 |
+
# Start tracker
|
| 72 |
+
tracker = ActivityTracker(db)
|
| 73 |
+
tracker_thread = threading.Thread(target=tracker.run, daemon=True)
|
| 74 |
+
tracker_thread.start()
|
| 75 |
+
logger.info("Activity tracker started")
|
| 76 |
+
|
| 77 |
+
# Start dashboard
|
| 78 |
+
dashboard_proc = None
|
| 79 |
+
if not args.tracker_only and not args.no_dashboard:
|
| 80 |
+
dashboard_proc = start_dashboard()
|
| 81 |
+
|
| 82 |
+
# Start tray
|
| 83 |
+
if not args.no_tray:
|
| 84 |
+
tray_thread = threading.Thread(target=start_tray, args=(tracker,), daemon=True)
|
| 85 |
+
tray_thread.start()
|
| 86 |
+
|
| 87 |
+
logger.info("FocusTrack is running. Press Ctrl+C to stop.")
|
| 88 |
+
try:
|
| 89 |
+
tracker_thread.join()
|
| 90 |
+
except KeyboardInterrupt:
|
| 91 |
+
logger.info("Shutting down FocusTrack...")
|
| 92 |
+
tracker.stop()
|
| 93 |
+
if dashboard_proc:
|
| 94 |
+
dashboard_proc.terminate()
|
| 95 |
+
sys.exit(0)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
requirements.txt
CHANGED
|
@@ -1,3 +1,7 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FocusTrack - Hugging Face Spaces requirements
|
| 2 |
+
streamlit>=1.35.0
|
| 3 |
+
plotly>=5.22.0
|
| 4 |
+
pandas>=2.2.0
|
| 5 |
+
altair>=5.3.0
|
| 6 |
+
psutil>=5.9.8
|
| 7 |
+
Pillow>=10.3.0
|
seed_demo.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Demo Data Seeder
|
| 3 |
+
Run this to populate the database with realistic sample data for testing.
|
| 4 |
+
Usage: python seed_demo.py
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import random
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from datetime import datetime, timedelta, date
|
| 11 |
+
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 13 |
+
|
| 14 |
+
from database import Database
|
| 15 |
+
|
| 16 |
+
DEMO_SESSIONS = [
|
| 17 |
+
# (app_name, window_title, category)
|
| 18 |
+
("cursor", "focustrack/tracker.py - Cursor", "coding"),
|
| 19 |
+
("cursor", "focustrack/app.py - Cursor", "coding"),
|
| 20 |
+
("Terminal", "zsh — ~/focustrack", "coding"),
|
| 21 |
+
("iTerm2", "python main.py", "coding"),
|
| 22 |
+
("Chrome", "GitHub - focustrack/focustrack", "browsing"),
|
| 23 |
+
("Chrome", "Stack Overflow - Python threading", "browsing"),
|
| 24 |
+
("Chrome", "YouTube - Lo-fi beats to code to", "media"),
|
| 25 |
+
("Slack", "focustrack - #general", "communication"),
|
| 26 |
+
("Figma", "FocusTrack UI Design", "design"),
|
| 27 |
+
("Notion", "Project Notes - FocusTrack", "documents"),
|
| 28 |
+
("Spotify", "Now Playing - Chill Mix", "media"),
|
| 29 |
+
("zoom", "Daily Standup - Zoom Meeting", "communication"),
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def seed(days: int = 14):
|
| 34 |
+
db = Database()
|
| 35 |
+
db.initialize()
|
| 36 |
+
print(f"Seeding {days} days of demo data...")
|
| 37 |
+
|
| 38 |
+
count = 0
|
| 39 |
+
for d in range(days, -1, -1):
|
| 40 |
+
target = date.today() - timedelta(days=d)
|
| 41 |
+
|
| 42 |
+
# Work hours: 9am - 7pm with some gaps
|
| 43 |
+
start_hour = 9 + random.randint(0, 1)
|
| 44 |
+
end_hour = 18 + random.randint(-1, 2)
|
| 45 |
+
|
| 46 |
+
current_time = datetime.combine(target, datetime.min.time()).replace(
|
| 47 |
+
hour=start_hour, minute=random.randint(0, 30)
|
| 48 |
+
)
|
| 49 |
+
end_time = datetime.combine(target, datetime.min.time()).replace(
|
| 50 |
+
hour=end_hour, minute=random.randint(0, 30)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Skip weekends mostly
|
| 54 |
+
if target.weekday() >= 5 and random.random() > 0.3:
|
| 55 |
+
continue
|
| 56 |
+
|
| 57 |
+
while current_time < end_time:
|
| 58 |
+
# Occasional idle blocks
|
| 59 |
+
if random.random() < 0.08:
|
| 60 |
+
duration = random.randint(5, 20) * 60 # 5-20 min idle
|
| 61 |
+
db.log_activity(
|
| 62 |
+
timestamp=current_time,
|
| 63 |
+
app_name="idle",
|
| 64 |
+
window_title="",
|
| 65 |
+
duration_seconds=5,
|
| 66 |
+
category="idle",
|
| 67 |
+
is_idle=True,
|
| 68 |
+
)
|
| 69 |
+
current_time += timedelta(seconds=duration)
|
| 70 |
+
count += 1
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
# Pick a session
|
| 74 |
+
session = random.choice(DEMO_SESSIONS)
|
| 75 |
+
app, title, category = session
|
| 76 |
+
|
| 77 |
+
# Session duration: 2-40 minutes
|
| 78 |
+
session_duration = random.randint(2, 40) * 60
|
| 79 |
+
end_session = min(current_time + timedelta(seconds=session_duration), end_time)
|
| 80 |
+
|
| 81 |
+
# Log heartbeats at 5s intervals
|
| 82 |
+
tick = current_time
|
| 83 |
+
while tick < end_session:
|
| 84 |
+
db.log_activity(
|
| 85 |
+
timestamp=tick,
|
| 86 |
+
app_name=app,
|
| 87 |
+
window_title=title,
|
| 88 |
+
duration_seconds=5,
|
| 89 |
+
category=category,
|
| 90 |
+
is_idle=False,
|
| 91 |
+
)
|
| 92 |
+
tick += timedelta(seconds=5)
|
| 93 |
+
count += 1
|
| 94 |
+
|
| 95 |
+
current_time = end_session + timedelta(seconds=random.randint(5, 60))
|
| 96 |
+
|
| 97 |
+
print(f"✅ Seeded {count:,} activity records across {days} days.")
|
| 98 |
+
print(f" Database: {db.db_path}")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
days = int(sys.argv[1]) if len(sys.argv) > 1 else 14
|
| 103 |
+
seed(days)
|
settings.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Page 4: Settings
|
| 3 |
+
Configure tracker behavior, categories, and data management.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import json
|
| 8 |
+
import shutil
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
from ui_utils import privacy_badge, page_header, CATEGORY_COLORS, get_db
|
| 13 |
+
|
| 14 |
+
DB_PATH = Path(__file__).parent.parent / "data" / "activity.db"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def render():
|
| 18 |
+
db = get_db()
|
| 19 |
+
privacy_badge()
|
| 20 |
+
page_header("Settings", "Configure FocusTrack to your workflow")
|
| 21 |
+
|
| 22 |
+
settings = db.get_all_settings()
|
| 23 |
+
|
| 24 |
+
tab1, tab2, tab3, tab4 = st.tabs(["⚙️ Tracker", "🏷️ Categories", "🗄️ Data & Backup", "🎨 Appearance"])
|
| 25 |
+
|
| 26 |
+
# ─── Tab 1: Tracker Settings ──────────────────────────────────────────────
|
| 27 |
+
with tab1:
|
| 28 |
+
st.markdown("#### Tracking Behavior")
|
| 29 |
+
|
| 30 |
+
col1, col2 = st.columns(2)
|
| 31 |
+
with col1:
|
| 32 |
+
idle_threshold = st.number_input(
|
| 33 |
+
"Idle threshold (seconds)",
|
| 34 |
+
min_value=30, max_value=3600,
|
| 35 |
+
value=int(settings.get("idle_threshold_seconds", 300)),
|
| 36 |
+
step=30,
|
| 37 |
+
help="User is considered idle after this many seconds without mouse/keyboard activity."
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
heartbeat = st.number_input(
|
| 41 |
+
"Heartbeat interval (seconds)",
|
| 42 |
+
min_value=1, max_value=60,
|
| 43 |
+
value=int(settings.get("heartbeat_interval", 5)),
|
| 44 |
+
step=1,
|
| 45 |
+
help="How often activity is logged. Lower = more granular, higher = less CPU."
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
with col2:
|
| 49 |
+
ignored_raw = settings.get("ignored_apps", '[]')
|
| 50 |
+
try:
|
| 51 |
+
ignored_list = json.loads(ignored_raw)
|
| 52 |
+
except Exception:
|
| 53 |
+
ignored_list = []
|
| 54 |
+
|
| 55 |
+
ignored_text = st.text_area(
|
| 56 |
+
"Ignored apps (one per line)",
|
| 57 |
+
value="\n".join(ignored_list),
|
| 58 |
+
height=120,
|
| 59 |
+
help="Apps listed here will not be tracked."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
auto_start = st.toggle(
|
| 63 |
+
"Auto-start tracker on launch",
|
| 64 |
+
value=settings.get("auto_start", "false") == "true"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if st.button("💾 Save Tracker Settings", use_container_width=False):
|
| 68 |
+
db.set_setting("idle_threshold_seconds", str(idle_threshold))
|
| 69 |
+
db.set_setting("heartbeat_interval", str(heartbeat))
|
| 70 |
+
db.set_setting("auto_start", "true" if auto_start else "false")
|
| 71 |
+
new_ignored = [a.strip() for a in ignored_text.strip().split("\n") if a.strip()]
|
| 72 |
+
db.set_setting("ignored_apps", json.dumps(new_ignored))
|
| 73 |
+
st.toast("✅ Tracker settings saved!", icon="✅")
|
| 74 |
+
st.rerun()
|
| 75 |
+
|
| 76 |
+
st.markdown("---")
|
| 77 |
+
st.markdown("#### Tracker Status")
|
| 78 |
+
|
| 79 |
+
status = db.get_setting("tracker_running", "true")
|
| 80 |
+
status_map = {"true": ("🟢 Running", "#10b981"), "paused": ("🟡 Paused", "#f59e0b"), "false": ("🔴 Stopped", "#f43f5e")}
|
| 81 |
+
label, color = status_map.get(status, ("Unknown", "#6366f1"))
|
| 82 |
+
st.markdown(
|
| 83 |
+
f"<span style='color:{color}; font-size:1rem; font-weight:600;'>{label}</span>",
|
| 84 |
+
unsafe_allow_html=True
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
col_s1, col_s2, col_s3 = st.columns([1, 1, 1])
|
| 88 |
+
with col_s1:
|
| 89 |
+
if st.button("▶ Start", use_container_width=True):
|
| 90 |
+
db.set_setting("tracker_running", "true")
|
| 91 |
+
st.toast("Tracker started")
|
| 92 |
+
st.rerun()
|
| 93 |
+
with col_s2:
|
| 94 |
+
if st.button("⏸ Pause", use_container_width=True):
|
| 95 |
+
db.set_setting("tracker_running", "paused")
|
| 96 |
+
st.toast("Tracker paused")
|
| 97 |
+
st.rerun()
|
| 98 |
+
with col_s3:
|
| 99 |
+
if st.button("⏹ Stop", use_container_width=True):
|
| 100 |
+
db.set_setting("tracker_running", "false")
|
| 101 |
+
st.toast("Tracker stopped")
|
| 102 |
+
st.rerun()
|
| 103 |
+
|
| 104 |
+
# ─── Tab 2: Categories ────────────────────────────────────────────────────
|
| 105 |
+
with tab2:
|
| 106 |
+
st.markdown("#### Category Rules")
|
| 107 |
+
st.markdown("<p style='color:#9090b0; font-size:0.85rem;'>Define which apps and keywords map to which category. The tracker uses these rules to auto-categorize activity.</p>", unsafe_allow_html=True)
|
| 108 |
+
|
| 109 |
+
cats = db.get_categories()
|
| 110 |
+
|
| 111 |
+
for cat in cats:
|
| 112 |
+
with st.expander(f"{'●'} {cat['name'].title()}", expanded=False):
|
| 113 |
+
col_n, col_c = st.columns([3, 1])
|
| 114 |
+
with col_n:
|
| 115 |
+
cat_name = st.text_input("Name", value=cat["name"], key=f"cname_{cat['id']}")
|
| 116 |
+
with col_c:
|
| 117 |
+
cat_color = st.color_picker("Color", value=cat["color"], key=f"ccolor_{cat['id']}")
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
kw_list = json.loads(cat["keywords"] or "[]")
|
| 121 |
+
app_list = json.loads(cat["apps"] or "[]")
|
| 122 |
+
except Exception:
|
| 123 |
+
kw_list, app_list = [], []
|
| 124 |
+
|
| 125 |
+
col_k, col_a = st.columns(2)
|
| 126 |
+
with col_k:
|
| 127 |
+
kw_text = st.text_area(
|
| 128 |
+
"Keywords (one per line)",
|
| 129 |
+
value="\n".join(kw_list),
|
| 130 |
+
height=100,
|
| 131 |
+
key=f"kw_{cat['id']}",
|
| 132 |
+
help="These words are matched against app name and window title."
|
| 133 |
+
)
|
| 134 |
+
with col_a:
|
| 135 |
+
app_text = st.text_area(
|
| 136 |
+
"App names (one per line)",
|
| 137 |
+
value="\n".join(app_list),
|
| 138 |
+
height=100,
|
| 139 |
+
key=f"apps_{cat['id']}",
|
| 140 |
+
help="Partial matches against the process/app name."
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
col_save, col_del = st.columns([1, 1])
|
| 144 |
+
with col_save:
|
| 145 |
+
if st.button("💾 Save", key=f"save_cat_{cat['id']}", use_container_width=True):
|
| 146 |
+
new_kw = [k.strip() for k in kw_text.strip().split("\n") if k.strip()]
|
| 147 |
+
new_app = [a.strip() for a in app_text.strip().split("\n") if a.strip()]
|
| 148 |
+
db.upsert_category(cat_name, cat_color, new_kw, new_app)
|
| 149 |
+
st.toast(f"✅ '{cat_name}' saved")
|
| 150 |
+
st.rerun()
|
| 151 |
+
with col_del:
|
| 152 |
+
if cat["name"] not in ("idle", "uncategorized"):
|
| 153 |
+
if st.button("🗑 Delete", key=f"del_cat_{cat['id']}", use_container_width=True):
|
| 154 |
+
db.delete_category(cat["name"])
|
| 155 |
+
st.toast(f"Deleted '{cat['name']}'")
|
| 156 |
+
st.rerun()
|
| 157 |
+
|
| 158 |
+
st.markdown("---")
|
| 159 |
+
st.markdown("#### Add New Category")
|
| 160 |
+
nc1, nc2, nc3 = st.columns([2, 1, 1])
|
| 161 |
+
with nc1:
|
| 162 |
+
new_cat_name = st.text_input("Category name", placeholder="e.g. learning")
|
| 163 |
+
with nc2:
|
| 164 |
+
new_cat_color = st.color_picker("Color", value="#6366f1")
|
| 165 |
+
with nc3:
|
| 166 |
+
st.markdown("<div style='margin-top:28px'></div>", unsafe_allow_html=True)
|
| 167 |
+
if st.button("➕ Add Category", use_container_width=True):
|
| 168 |
+
if new_cat_name.strip():
|
| 169 |
+
db.upsert_category(new_cat_name.strip(), new_cat_color, [], [])
|
| 170 |
+
st.toast(f"✅ Added '{new_cat_name}'")
|
| 171 |
+
st.rerun()
|
| 172 |
+
|
| 173 |
+
# ─── Tab 3: Data & Backup ─────────────────────────────────────────────────
|
| 174 |
+
with tab3:
|
| 175 |
+
st.markdown("#### Database Info")
|
| 176 |
+
|
| 177 |
+
db_size = db.get_db_size_mb()
|
| 178 |
+
from datetime import date
|
| 179 |
+
from datetime import datetime as dt2
|
| 180 |
+
from ui_utils import get_date_range
|
| 181 |
+
start, end = get_date_range("Last 30 days")
|
| 182 |
+
count = db.get_activity_count(start, end)
|
| 183 |
+
|
| 184 |
+
col_i1, col_i2, col_i3 = st.columns(3)
|
| 185 |
+
with col_i1:
|
| 186 |
+
st.metric("Database Size", f"{db_size:.2f} MB")
|
| 187 |
+
with col_i2:
|
| 188 |
+
st.metric("Records (30d)", f"{count:,}")
|
| 189 |
+
with col_i3:
|
| 190 |
+
st.metric("DB Location", "Local only ✅")
|
| 191 |
+
|
| 192 |
+
st.code(str(DB_PATH), language=None)
|
| 193 |
+
|
| 194 |
+
st.markdown("---")
|
| 195 |
+
st.markdown("#### Backup Database")
|
| 196 |
+
col_b1, col_b2 = st.columns([1, 2])
|
| 197 |
+
with col_b1:
|
| 198 |
+
if st.button("📦 Download Backup", use_container_width=True):
|
| 199 |
+
if DB_PATH.exists():
|
| 200 |
+
with open(DB_PATH, "rb") as f:
|
| 201 |
+
data = f.read()
|
| 202 |
+
st.download_button(
|
| 203 |
+
"💾 Save activity.db",
|
| 204 |
+
data,
|
| 205 |
+
file_name=f"focustrack_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db",
|
| 206 |
+
mime="application/octet-stream",
|
| 207 |
+
use_container_width=True,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
st.markdown("---")
|
| 211 |
+
st.markdown("#### Restore Database")
|
| 212 |
+
uploaded = st.file_uploader("Upload a backup .db file", type=["db"])
|
| 213 |
+
if uploaded:
|
| 214 |
+
if st.button("⚠️ Restore from backup (overwrites current data)"):
|
| 215 |
+
DB_PATH.write_bytes(uploaded.read())
|
| 216 |
+
if "db" in st.session_state:
|
| 217 |
+
del st.session_state["db"]
|
| 218 |
+
st.toast("✅ Database restored! Please refresh the page.", icon="✅")
|
| 219 |
+
|
| 220 |
+
st.markdown("---")
|
| 221 |
+
st.markdown("#### Danger Zone")
|
| 222 |
+
st.markdown(
|
| 223 |
+
"<div style='background:#1a0a0f; border:1px solid #4a1a2a; border-radius:12px; padding:1.25rem; margin-bottom:1rem;'>"
|
| 224 |
+
"<p style='color:#f43f5e; font-weight:600; margin:0 0 8px;'>⚠️ Clear All Data</p>"
|
| 225 |
+
"<p style='color:#9090b0; font-size:0.85rem; margin:0;'>This permanently deletes all tracked activity. This action cannot be undone.</p>"
|
| 226 |
+
"</div>",
|
| 227 |
+
unsafe_allow_html=True,
|
| 228 |
+
)
|
| 229 |
+
confirm = st.text_input("Type DELETE to confirm")
|
| 230 |
+
if st.button("🗑 Clear All Activity Data", type="secondary"):
|
| 231 |
+
if confirm == "DELETE":
|
| 232 |
+
db.clear_all_data()
|
| 233 |
+
st.toast("All data cleared.")
|
| 234 |
+
st.rerun()
|
| 235 |
+
else:
|
| 236 |
+
st.error("Please type DELETE to confirm.")
|
| 237 |
+
|
| 238 |
+
# ─── Tab 4: Appearance ────────────────────────────────────────────────────
|
| 239 |
+
with tab4:
|
| 240 |
+
st.markdown("#### Theme")
|
| 241 |
+
current_theme = db.get_setting("theme", "dark")
|
| 242 |
+
theme = st.radio(
|
| 243 |
+
"Color mode",
|
| 244 |
+
["dark", "light"],
|
| 245 |
+
index=0 if current_theme == "dark" else 1,
|
| 246 |
+
horizontal=True,
|
| 247 |
+
)
|
| 248 |
+
if theme != current_theme:
|
| 249 |
+
db.set_setting("theme", theme)
|
| 250 |
+
st.toast("Theme updated — refresh to apply.")
|
| 251 |
+
st.rerun()
|
| 252 |
+
|
| 253 |
+
st.markdown("---")
|
| 254 |
+
st.markdown("#### About FocusTrack")
|
| 255 |
+
st.markdown("""
|
| 256 |
+
<div style="background:#16161f; border:1px solid #2a2a3a; border-radius:12px; padding:1.5rem;">
|
| 257 |
+
<h3 style="font-family:'Syne',sans-serif; margin:0 0 8px; color:#f0f0ff;">FocusTrack v1.0</h3>
|
| 258 |
+
<p style="color:#9090b0; font-size:0.85rem; margin:0 0 4px;">100% local, privacy-first productivity tracker.</p>
|
| 259 |
+
<p style="color:#9090b0; font-size:0.85rem; margin:0 0 4px;">Built with Python 3.11+ · Streamlit · SQLite · Plotly</p>
|
| 260 |
+
<p style="color:#5a5a7a; font-size:0.8rem; margin:0;">No internet • No accounts • No cloud • Your data never leaves your device.</p>
|
| 261 |
+
</div>
|
| 262 |
+
""", unsafe_allow_html=True)
|
startup.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Startup script for Hugging Face Spaces.
|
| 3 |
+
Auto-seeds demo data if the database is empty, then launches the dashboard.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import subprocess
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).parent
|
| 11 |
+
sys.path.insert(0, str(ROOT))
|
| 12 |
+
|
| 13 |
+
# Ensure data/logs dirs exist
|
| 14 |
+
(ROOT / "data").mkdir(exist_ok=True)
|
| 15 |
+
(ROOT / "logs").mkdir(exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# Auto-seed demo data if DB is empty or new
|
| 18 |
+
from database import Database
|
| 19 |
+
db = Database()
|
| 20 |
+
db.initialize()
|
| 21 |
+
|
| 22 |
+
count = db.get_activity_count(
|
| 23 |
+
__import__('datetime').datetime(2000, 1, 1),
|
| 24 |
+
__import__('datetime').datetime(2099, 1, 1),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
if count == 0:
|
| 28 |
+
print("🌱 No data found — seeding demo data...")
|
| 29 |
+
import seed_demo
|
| 30 |
+
seed_demo.seed(days=14)
|
| 31 |
+
print("✅ Demo data ready!")
|
| 32 |
+
else:
|
| 33 |
+
print(f"✅ Database has {count:,} records, skipping seed.")
|
| 34 |
+
|
| 35 |
+
# Launch Streamlit
|
| 36 |
+
print("🚀 Starting FocusTrack dashboard...")
|
| 37 |
+
subprocess.run([
|
| 38 |
+
sys.executable, "-m", "streamlit", "run", str(ROOT / "app.py"),
|
| 39 |
+
"--server.port", "7860",
|
| 40 |
+
"--server.address", "0.0.0.0",
|
| 41 |
+
"--server.headless", "true",
|
| 42 |
+
"--browser.gatherUsageStats", "false",
|
| 43 |
+
])
|
tracker.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Activity Tracker Engine
|
| 3 |
+
Detects active window, tracks idle time, logs heartbeats.
|
| 4 |
+
Cross-platform: Windows / macOS / Linux
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import time
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import platform
|
| 11 |
+
import threading
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from typing import Optional, Tuple
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger("focustrack.tracker")
|
| 17 |
+
|
| 18 |
+
SYSTEM = platform.system() # 'Windows', 'Darwin', 'Linux'
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ─── Window Detection ────────────────────────────────────────────────────────
|
| 22 |
+
|
| 23 |
+
def get_active_window() -> Tuple[str, str]:
|
| 24 |
+
"""
|
| 25 |
+
Returns (app_name, window_title) for the currently focused window.
|
| 26 |
+
Cross-platform with graceful fallbacks.
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
if SYSTEM == "Windows":
|
| 30 |
+
return _get_window_windows()
|
| 31 |
+
elif SYSTEM == "Darwin":
|
| 32 |
+
return _get_window_macos()
|
| 33 |
+
else:
|
| 34 |
+
return _get_window_linux()
|
| 35 |
+
except Exception as e:
|
| 36 |
+
logger.debug(f"Window detection error: {e}")
|
| 37 |
+
return ("unknown", "unknown")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _get_window_windows() -> Tuple[str, str]:
|
| 41 |
+
import ctypes
|
| 42 |
+
import ctypes.wintypes
|
| 43 |
+
user32 = ctypes.windll.user32
|
| 44 |
+
hwnd = user32.GetForegroundWindow()
|
| 45 |
+
length = user32.GetWindowTextLengthW(hwnd)
|
| 46 |
+
buf = ctypes.create_unicode_buffer(length + 1)
|
| 47 |
+
user32.GetWindowTextW(hwnd, buf, length + 1)
|
| 48 |
+
title = buf.value or "unknown"
|
| 49 |
+
|
| 50 |
+
# Get process name
|
| 51 |
+
pid = ctypes.wintypes.DWORD()
|
| 52 |
+
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
|
| 53 |
+
try:
|
| 54 |
+
import psutil
|
| 55 |
+
proc = psutil.Process(pid.value)
|
| 56 |
+
app = proc.name().replace(".exe", "")
|
| 57 |
+
except Exception:
|
| 58 |
+
app = "unknown"
|
| 59 |
+
return (app, title)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _get_window_macos() -> Tuple[str, str]:
|
| 63 |
+
try:
|
| 64 |
+
from AppKit import NSWorkspace
|
| 65 |
+
ws = NSWorkspace.sharedWorkspace()
|
| 66 |
+
app = ws.activeApplication()
|
| 67 |
+
app_name = app.get("NSApplicationName", "unknown") if app else "unknown"
|
| 68 |
+
title = "unknown"
|
| 69 |
+
try:
|
| 70 |
+
import subprocess
|
| 71 |
+
script = 'tell application "System Events" to get name of first window of (first process whose frontmost is true)'
|
| 72 |
+
result = subprocess.run(
|
| 73 |
+
["osascript", "-e", script], capture_output=True, text=True, timeout=2
|
| 74 |
+
)
|
| 75 |
+
if result.returncode == 0:
|
| 76 |
+
title = result.stdout.strip()
|
| 77 |
+
except Exception:
|
| 78 |
+
pass
|
| 79 |
+
return (app_name, title)
|
| 80 |
+
except ImportError:
|
| 81 |
+
# Fallback via subprocess
|
| 82 |
+
try:
|
| 83 |
+
import subprocess
|
| 84 |
+
script = """
|
| 85 |
+
tell application "System Events"
|
| 86 |
+
set frontApp to name of first application process whose frontmost is true
|
| 87 |
+
set frontTitle to ""
|
| 88 |
+
try
|
| 89 |
+
set frontTitle to name of front window of (first process whose frontmost is true)
|
| 90 |
+
end try
|
| 91 |
+
return frontApp & "|" & frontTitle
|
| 92 |
+
end tell
|
| 93 |
+
"""
|
| 94 |
+
result = subprocess.run(
|
| 95 |
+
["osascript", "-e", script], capture_output=True, text=True, timeout=3
|
| 96 |
+
)
|
| 97 |
+
if result.returncode == 0:
|
| 98 |
+
parts = result.stdout.strip().split("|", 1)
|
| 99 |
+
return (parts[0], parts[1] if len(parts) > 1 else "")
|
| 100 |
+
except Exception:
|
| 101 |
+
pass
|
| 102 |
+
return ("unknown", "unknown")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _get_window_linux() -> Tuple[str, str]:
|
| 106 |
+
try:
|
| 107 |
+
import subprocess
|
| 108 |
+
# Try xdotool
|
| 109 |
+
wid = subprocess.run(
|
| 110 |
+
["xdotool", "getactivewindow"], capture_output=True, text=True, timeout=2
|
| 111 |
+
)
|
| 112 |
+
if wid.returncode == 0:
|
| 113 |
+
wid_val = wid.stdout.strip()
|
| 114 |
+
name = subprocess.run(
|
| 115 |
+
["xdotool", "getwindowname", wid_val],
|
| 116 |
+
capture_output=True, text=True, timeout=2
|
| 117 |
+
)
|
| 118 |
+
pid_result = subprocess.run(
|
| 119 |
+
["xdotool", "getwindowpid", wid_val],
|
| 120 |
+
capture_output=True, text=True, timeout=2
|
| 121 |
+
)
|
| 122 |
+
title = name.stdout.strip() if name.returncode == 0 else "unknown"
|
| 123 |
+
app = "unknown"
|
| 124 |
+
if pid_result.returncode == 0:
|
| 125 |
+
try:
|
| 126 |
+
import psutil
|
| 127 |
+
proc = psutil.Process(int(pid_result.stdout.strip()))
|
| 128 |
+
app = proc.name()
|
| 129 |
+
except Exception:
|
| 130 |
+
pass
|
| 131 |
+
return (app, title)
|
| 132 |
+
except FileNotFoundError:
|
| 133 |
+
pass
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
# Fallback: wmctrl
|
| 137 |
+
import subprocess
|
| 138 |
+
result = subprocess.run(
|
| 139 |
+
["wmctrl", "-a", ":ACTIVE:"], capture_output=True, text=True
|
| 140 |
+
)
|
| 141 |
+
except Exception:
|
| 142 |
+
pass
|
| 143 |
+
|
| 144 |
+
return ("unknown", "unknown")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# ─── Categorizer ───────────────────────────────────────────────────��─────────
|
| 148 |
+
|
| 149 |
+
class Categorizer:
|
| 150 |
+
"""Rule-based app categorization using DB-defined rules."""
|
| 151 |
+
|
| 152 |
+
def __init__(self, db):
|
| 153 |
+
self.db = db
|
| 154 |
+
self._cache: dict = {}
|
| 155 |
+
self._reload_interval = 60 # seconds
|
| 156 |
+
self._last_reload = 0.0
|
| 157 |
+
self._load_rules()
|
| 158 |
+
|
| 159 |
+
def _load_rules(self):
|
| 160 |
+
cats = self.db.get_categories()
|
| 161 |
+
self._rules = []
|
| 162 |
+
for cat in cats:
|
| 163 |
+
self._rules.append({
|
| 164 |
+
"name": cat["name"],
|
| 165 |
+
"keywords": json.loads(cat["keywords"] or "[]"),
|
| 166 |
+
"apps": json.loads(cat["apps"] or "[]"),
|
| 167 |
+
})
|
| 168 |
+
self._last_reload = time.time()
|
| 169 |
+
|
| 170 |
+
def categorize(self, app_name: str, window_title: str, is_idle: bool) -> str:
|
| 171 |
+
if is_idle:
|
| 172 |
+
return "idle"
|
| 173 |
+
|
| 174 |
+
# Reload rules periodically
|
| 175 |
+
if time.time() - self._last_reload > self._reload_interval:
|
| 176 |
+
self._load_rules()
|
| 177 |
+
|
| 178 |
+
app_lower = app_name.lower()
|
| 179 |
+
title_lower = window_title.lower()
|
| 180 |
+
|
| 181 |
+
for rule in self._rules:
|
| 182 |
+
if rule["name"] == "idle":
|
| 183 |
+
continue
|
| 184 |
+
for app_kw in rule["apps"]:
|
| 185 |
+
if app_kw.lower() in app_lower:
|
| 186 |
+
return rule["name"]
|
| 187 |
+
for kw in rule["keywords"]:
|
| 188 |
+
if kw.lower() in title_lower or kw.lower() in app_lower:
|
| 189 |
+
return rule["name"]
|
| 190 |
+
|
| 191 |
+
return "uncategorized"
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
# ─── Idle Detector ───────────────────────────────────────────────────────────
|
| 195 |
+
|
| 196 |
+
class IdleDetector:
|
| 197 |
+
"""Tracks mouse + keyboard activity to detect idle state."""
|
| 198 |
+
|
| 199 |
+
def __init__(self, threshold_seconds: int = 300):
|
| 200 |
+
self.threshold = threshold_seconds
|
| 201 |
+
self._last_event = time.time()
|
| 202 |
+
self._listener = None
|
| 203 |
+
self._running = False
|
| 204 |
+
|
| 205 |
+
def start(self):
|
| 206 |
+
self._running = True
|
| 207 |
+
try:
|
| 208 |
+
from pynput import mouse, keyboard
|
| 209 |
+
|
| 210 |
+
def on_activity(*args, **kwargs):
|
| 211 |
+
self._last_event = time.time()
|
| 212 |
+
|
| 213 |
+
self._mouse_listener = mouse.Listener(
|
| 214 |
+
on_move=on_activity, on_click=on_activity, on_scroll=on_activity
|
| 215 |
+
)
|
| 216 |
+
self._keyboard_listener = keyboard.Listener(on_press=on_activity)
|
| 217 |
+
self._mouse_listener.start()
|
| 218 |
+
self._keyboard_listener.start()
|
| 219 |
+
logger.info("Idle detector started (pynput)")
|
| 220 |
+
except Exception as e:
|
| 221 |
+
logger.warning(f"pynput unavailable ({e}), idle detection disabled")
|
| 222 |
+
|
| 223 |
+
def stop(self):
|
| 224 |
+
self._running = False
|
| 225 |
+
try:
|
| 226 |
+
if self._mouse_listener:
|
| 227 |
+
self._mouse_listener.stop()
|
| 228 |
+
if self._keyboard_listener:
|
| 229 |
+
self._keyboard_listener.stop()
|
| 230 |
+
except Exception:
|
| 231 |
+
pass
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def is_idle(self) -> bool:
|
| 235 |
+
return (time.time() - self._last_event) > self.threshold
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def idle_seconds(self) -> float:
|
| 239 |
+
elapsed = time.time() - self._last_event
|
| 240 |
+
return max(0.0, elapsed - self.threshold) if self.is_idle else 0.0
|
| 241 |
+
|
| 242 |
+
def update_threshold(self, seconds: int):
|
| 243 |
+
self.threshold = seconds
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# ─── Main Tracker ────────────────────────────────────────────────────────────
|
| 247 |
+
|
| 248 |
+
class ActivityTracker:
|
| 249 |
+
"""
|
| 250 |
+
Background activity tracking service.
|
| 251 |
+
Logs heartbeats every N seconds to SQLite.
|
| 252 |
+
"""
|
| 253 |
+
|
| 254 |
+
def __init__(self, db):
|
| 255 |
+
self.db = db
|
| 256 |
+
self._running = False
|
| 257 |
+
self._paused = False
|
| 258 |
+
self._lock = threading.Lock()
|
| 259 |
+
|
| 260 |
+
idle_threshold = int(db.get_setting("idle_threshold_seconds", 300))
|
| 261 |
+
self.heartbeat_interval = int(db.get_setting("heartbeat_interval", 5))
|
| 262 |
+
|
| 263 |
+
self.idle_detector = IdleDetector(idle_threshold)
|
| 264 |
+
self.categorizer = Categorizer(db)
|
| 265 |
+
|
| 266 |
+
# Current session state
|
| 267 |
+
self.current_app = ""
|
| 268 |
+
self.current_title = ""
|
| 269 |
+
self.current_category = ""
|
| 270 |
+
self.session_start = datetime.now()
|
| 271 |
+
self.is_idle = False
|
| 272 |
+
|
| 273 |
+
def run(self):
|
| 274 |
+
"""Main tracking loop. Runs in a background thread."""
|
| 275 |
+
self._running = True
|
| 276 |
+
self.idle_detector.start()
|
| 277 |
+
logger.info(f"Tracker started (heartbeat: {self.heartbeat_interval}s)")
|
| 278 |
+
|
| 279 |
+
ignored_raw = self.db.get_setting("ignored_apps", "[]")
|
| 280 |
+
try:
|
| 281 |
+
ignored_apps = [a.lower() for a in json.loads(ignored_raw)]
|
| 282 |
+
except Exception:
|
| 283 |
+
ignored_apps = []
|
| 284 |
+
|
| 285 |
+
while self._running:
|
| 286 |
+
try:
|
| 287 |
+
if not self._paused:
|
| 288 |
+
self._tick(ignored_apps)
|
| 289 |
+
time.sleep(self.heartbeat_interval)
|
| 290 |
+
except Exception as e:
|
| 291 |
+
logger.error(f"Tracker error: {e}", exc_info=True)
|
| 292 |
+
time.sleep(self.heartbeat_interval)
|
| 293 |
+
|
| 294 |
+
def _tick(self, ignored_apps: list):
|
| 295 |
+
"""One heartbeat: detect window, log activity."""
|
| 296 |
+
app_name, window_title = get_active_window()
|
| 297 |
+
is_idle = self.idle_detector.is_idle
|
| 298 |
+
|
| 299 |
+
# Skip ignored apps
|
| 300 |
+
if any(ig in app_name.lower() for ig in ignored_apps):
|
| 301 |
+
return
|
| 302 |
+
|
| 303 |
+
category = self.categorizer.categorize(app_name, window_title, is_idle)
|
| 304 |
+
|
| 305 |
+
with self._lock:
|
| 306 |
+
self.current_app = app_name
|
| 307 |
+
self.current_title = window_title
|
| 308 |
+
self.current_category = category
|
| 309 |
+
self.is_idle = is_idle
|
| 310 |
+
|
| 311 |
+
# Check if session changed
|
| 312 |
+
if (app_name != self.current_app or
|
| 313 |
+
abs((datetime.now() - self.session_start).total_seconds()) > 30):
|
| 314 |
+
self.session_start = datetime.now()
|
| 315 |
+
|
| 316 |
+
self.db.log_activity(
|
| 317 |
+
timestamp=datetime.now(),
|
| 318 |
+
app_name=app_name,
|
| 319 |
+
window_title=window_title,
|
| 320 |
+
duration_seconds=self.heartbeat_interval,
|
| 321 |
+
category=category,
|
| 322 |
+
is_idle=is_idle,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
# ─── Controls ────────────────────────────────────────────────────────────
|
| 326 |
+
|
| 327 |
+
def pause(self):
|
| 328 |
+
self._paused = True
|
| 329 |
+
self.db.set_setting("tracker_running", "paused")
|
| 330 |
+
logger.info("Tracker paused")
|
| 331 |
+
|
| 332 |
+
def resume(self):
|
| 333 |
+
self._paused = False
|
| 334 |
+
self.db.set_setting("tracker_running", "true")
|
| 335 |
+
logger.info("Tracker resumed")
|
| 336 |
+
|
| 337 |
+
def stop(self):
|
| 338 |
+
self._running = False
|
| 339 |
+
self.idle_detector.stop()
|
| 340 |
+
self.db.set_setting("tracker_running", "false")
|
| 341 |
+
logger.info("Tracker stopped")
|
| 342 |
+
|
| 343 |
+
@property
|
| 344 |
+
def status(self) -> str:
|
| 345 |
+
if not self._running:
|
| 346 |
+
return "stopped"
|
| 347 |
+
if self._paused:
|
| 348 |
+
return "paused"
|
| 349 |
+
return "running"
|
| 350 |
+
|
| 351 |
+
def get_current_state(self) -> dict:
|
| 352 |
+
with self._lock:
|
| 353 |
+
return {
|
| 354 |
+
"app": self.current_app,
|
| 355 |
+
"title": self.current_title,
|
| 356 |
+
"category": self.current_category,
|
| 357 |
+
"is_idle": self.is_idle,
|
| 358 |
+
"status": self.status,
|
| 359 |
+
"session_start": self.session_start.isoformat(),
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
def reload_settings(self):
|
| 363 |
+
"""Reload settings from DB (called after settings change)."""
|
| 364 |
+
idle_threshold = int(self.db.get_setting("idle_threshold_seconds", 300))
|
| 365 |
+
self.heartbeat_interval = int(self.db.get_setting("heartbeat_interval", 5))
|
| 366 |
+
self.idle_detector.update_threshold(idle_threshold)
|
| 367 |
+
logger.info("Tracker settings reloaded")
|
tray.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - System Tray Icon
|
| 3 |
+
Provides a quick menu for Start/Pause/Quit and opens dashboard.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
import webbrowser
|
| 8 |
+
import threading
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger("focustrack.tray")
|
| 11 |
+
|
| 12 |
+
ICON_DATA = None # Will use a generated icon
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import pystray
|
| 16 |
+
from PIL import Image, ImageDraw
|
| 17 |
+
PYSTRAY_AVAILABLE = True
|
| 18 |
+
except ImportError:
|
| 19 |
+
PYSTRAY_AVAILABLE = False
|
| 20 |
+
logger.warning("pystray/PIL not available - tray icon disabled")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _create_icon_image(color: str = "#6366f1"):
|
| 24 |
+
"""Generate a simple circular tray icon."""
|
| 25 |
+
img = Image.new("RGBA", (64, 64), (0, 0, 0, 0))
|
| 26 |
+
draw = ImageDraw.Draw(img)
|
| 27 |
+
# Outer circle
|
| 28 |
+
draw.ellipse([4, 4, 60, 60], fill=color)
|
| 29 |
+
# Inner 'F' for FocusTrack
|
| 30 |
+
draw.rectangle([20, 18, 26, 46], fill="white")
|
| 31 |
+
draw.rectangle([20, 18, 40, 24], fill="white")
|
| 32 |
+
draw.rectangle([20, 30, 36, 36], fill="white")
|
| 33 |
+
return img
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TrayApp:
|
| 37 |
+
def __init__(self, tracker):
|
| 38 |
+
self.tracker = tracker
|
| 39 |
+
|
| 40 |
+
def run(self):
|
| 41 |
+
if not PYSTRAY_AVAILABLE:
|
| 42 |
+
logger.info("Tray not available, skipping")
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
def open_dashboard(icon, item):
|
| 46 |
+
webbrowser.open("http://localhost:8501")
|
| 47 |
+
|
| 48 |
+
def pause_resume(icon, item):
|
| 49 |
+
if self.tracker.status == "running":
|
| 50 |
+
self.tracker.pause()
|
| 51 |
+
icon.title = "FocusTrack [Paused]"
|
| 52 |
+
else:
|
| 53 |
+
self.tracker.resume()
|
| 54 |
+
icon.title = "FocusTrack [Running]"
|
| 55 |
+
|
| 56 |
+
def quit_app(icon, item):
|
| 57 |
+
self.tracker.stop()
|
| 58 |
+
icon.stop()
|
| 59 |
+
|
| 60 |
+
menu = pystray.Menu(
|
| 61 |
+
pystray.MenuItem("📊 Open Dashboard", open_dashboard, default=True),
|
| 62 |
+
pystray.Menu.SEPARATOR,
|
| 63 |
+
pystray.MenuItem("⏸ Pause / Resume", pause_resume),
|
| 64 |
+
pystray.Menu.SEPARATOR,
|
| 65 |
+
pystray.MenuItem("✖ Quit FocusTrack", quit_app),
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
icon_img = _create_icon_image()
|
| 69 |
+
icon = pystray.Icon("FocusTrack", icon_img, "FocusTrack [Running]", menu)
|
| 70 |
+
logger.info("System tray icon started")
|
| 71 |
+
icon.run()
|
ui_utils.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FocusTrack - Shared UI utilities, CSS themes, and helper functions.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import streamlit as st
|
| 6 |
+
from datetime import datetime, timedelta, date
|
| 7 |
+
from typing import Optional
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# ─── CSS Theme ───────────────────────────────────────────────────────────────
|
| 12 |
+
|
| 13 |
+
DARK_CSS = """
|
| 14 |
+
<style>
|
| 15 |
+
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Syne:wght@400;600;700;800&family=Inter:wght@300;400;500;600&display=swap');
|
| 16 |
+
|
| 17 |
+
:root {
|
| 18 |
+
--bg-primary: #0a0a0f;
|
| 19 |
+
--bg-secondary: #111118;
|
| 20 |
+
--bg-card: #16161f;
|
| 21 |
+
--bg-card-hover: #1c1c27;
|
| 22 |
+
--border: #2a2a3a;
|
| 23 |
+
--border-glow: #6366f133;
|
| 24 |
+
--text-primary: #f0f0ff;
|
| 25 |
+
--text-secondary:#9090b0;
|
| 26 |
+
--text-muted: #5a5a7a;
|
| 27 |
+
--accent: #6366f1;
|
| 28 |
+
--accent-glow: #6366f144;
|
| 29 |
+
--accent-2: #22d3ee;
|
| 30 |
+
--accent-3: #f59e0b;
|
| 31 |
+
--accent-4: #10b981;
|
| 32 |
+
--success: #10b981;
|
| 33 |
+
--warning: #f59e0b;
|
| 34 |
+
--danger: #f43f5e;
|
| 35 |
+
--radius: 12px;
|
| 36 |
+
--radius-lg: 20px;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/* Global resets */
|
| 40 |
+
html, body, [class*="css"] {
|
| 41 |
+
font-family: 'Inter', sans-serif;
|
| 42 |
+
background-color: var(--bg-primary) !important;
|
| 43 |
+
color: var(--text-primary) !important;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
/* Hide Streamlit chrome */
|
| 47 |
+
#MainMenu, footer, .stDeployButton { display: none !important; }
|
| 48 |
+
.block-container { padding-top: 1.5rem !important; padding-bottom: 2rem !important; max-width: 1400px; }
|
| 49 |
+
|
| 50 |
+
/* Sidebar */
|
| 51 |
+
[data-testid="stSidebar"] {
|
| 52 |
+
background: var(--bg-secondary) !important;
|
| 53 |
+
border-right: 1px solid var(--border) !important;
|
| 54 |
+
}
|
| 55 |
+
[data-testid="stSidebar"] * { color: var(--text-primary) !important; }
|
| 56 |
+
|
| 57 |
+
/* Metric cards */
|
| 58 |
+
[data-testid="stMetric"] {
|
| 59 |
+
background: var(--bg-card) !important;
|
| 60 |
+
border: 1px solid var(--border) !important;
|
| 61 |
+
border-radius: var(--radius) !important;
|
| 62 |
+
padding: 1.25rem 1.5rem !important;
|
| 63 |
+
transition: all 0.2s ease;
|
| 64 |
+
}
|
| 65 |
+
[data-testid="stMetric"]:hover {
|
| 66 |
+
border-color: var(--accent) !important;
|
| 67 |
+
box-shadow: 0 0 20px var(--accent-glow) !important;
|
| 68 |
+
}
|
| 69 |
+
[data-testid="stMetricLabel"] { color: var(--text-secondary) !important; font-size: 0.8rem !important; }
|
| 70 |
+
[data-testid="stMetricValue"] { color: var(--text-primary) !important; font-family: 'Syne', sans-serif !important; }
|
| 71 |
+
[data-testid="stMetricDelta"] { font-size: 0.75rem !important; }
|
| 72 |
+
|
| 73 |
+
/* Buttons */
|
| 74 |
+
.stButton > button {
|
| 75 |
+
background: var(--bg-card) !important;
|
| 76 |
+
color: var(--text-primary) !important;
|
| 77 |
+
border: 1px solid var(--border) !important;
|
| 78 |
+
border-radius: var(--radius) !important;
|
| 79 |
+
font-family: 'Inter', sans-serif !important;
|
| 80 |
+
font-weight: 500 !important;
|
| 81 |
+
transition: all 0.2s ease !important;
|
| 82 |
+
}
|
| 83 |
+
.stButton > button:hover {
|
| 84 |
+
border-color: var(--accent) !important;
|
| 85 |
+
background: var(--accent-glow) !important;
|
| 86 |
+
color: var(--accent) !important;
|
| 87 |
+
}
|
| 88 |
+
.stButton > button:active { transform: scale(0.98); }
|
| 89 |
+
|
| 90 |
+
/* DataFrames */
|
| 91 |
+
[data-testid="stDataFrame"] {
|
| 92 |
+
border: 1px solid var(--border) !important;
|
| 93 |
+
border-radius: var(--radius) !important;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
/* Inputs / selects */
|
| 97 |
+
.stTextInput > div > div > input,
|
| 98 |
+
.stSelectbox > div > div,
|
| 99 |
+
.stDateInput > div > div > input,
|
| 100 |
+
.stNumberInput > div > div > input {
|
| 101 |
+
background: var(--bg-card) !important;
|
| 102 |
+
color: var(--text-primary) !important;
|
| 103 |
+
border: 1px solid var(--border) !important;
|
| 104 |
+
border-radius: var(--radius) !important;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
/* Radio */
|
| 108 |
+
.stRadio > div { gap: 0.5rem !important; }
|
| 109 |
+
|
| 110 |
+
/* Tabs */
|
| 111 |
+
.stTabs [data-baseweb="tab-list"] {
|
| 112 |
+
background: var(--bg-secondary) !important;
|
| 113 |
+
border-radius: var(--radius) !important;
|
| 114 |
+
padding: 4px !important;
|
| 115 |
+
gap: 4px !important;
|
| 116 |
+
border: 1px solid var(--border) !important;
|
| 117 |
+
}
|
| 118 |
+
.stTabs [data-baseweb="tab"] {
|
| 119 |
+
background: transparent !important;
|
| 120 |
+
color: var(--text-secondary) !important;
|
| 121 |
+
border-radius: 8px !important;
|
| 122 |
+
font-weight: 500 !important;
|
| 123 |
+
}
|
| 124 |
+
.stTabs [aria-selected="true"] {
|
| 125 |
+
background: var(--bg-card) !important;
|
| 126 |
+
color: var(--text-primary) !important;
|
| 127 |
+
border: 1px solid var(--border) !important;
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
/* Dividers */
|
| 131 |
+
hr { border-color: var(--border) !important; }
|
| 132 |
+
|
| 133 |
+
/* Scrollbar */
|
| 134 |
+
::-webkit-scrollbar { width: 6px; height: 6px; }
|
| 135 |
+
::-webkit-scrollbar-track { background: var(--bg-primary); }
|
| 136 |
+
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; }
|
| 137 |
+
::-webkit-scrollbar-thumb:hover { background: var(--accent); }
|
| 138 |
+
</style>
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
LIGHT_CSS = """
|
| 142 |
+
<style>
|
| 143 |
+
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Syne:wght@400;600;700;800&family=Inter:wght@300;400;500;600&display=swap');
|
| 144 |
+
|
| 145 |
+
:root {
|
| 146 |
+
--bg-primary: #f8f8fc;
|
| 147 |
+
--bg-secondary: #f0f0f8;
|
| 148 |
+
--bg-card: #ffffff;
|
| 149 |
+
--bg-card-hover: #f5f5fd;
|
| 150 |
+
--border: #e2e2f0;
|
| 151 |
+
--border-glow: #6366f122;
|
| 152 |
+
--text-primary: #1a1a2e;
|
| 153 |
+
--text-secondary:#6060a0;
|
| 154 |
+
--text-muted: #9090b8;
|
| 155 |
+
--accent: #6366f1;
|
| 156 |
+
--accent-glow: #6366f122;
|
| 157 |
+
--accent-2: #0891b2;
|
| 158 |
+
--accent-3: #d97706;
|
| 159 |
+
--accent-4: #059669;
|
| 160 |
+
--success: #059669;
|
| 161 |
+
--warning: #d97706;
|
| 162 |
+
--danger: #e11d48;
|
| 163 |
+
--radius: 12px;
|
| 164 |
+
--radius-lg: 20px;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
html, body, [class*="css"] {
|
| 168 |
+
font-family: 'Inter', sans-serif;
|
| 169 |
+
background-color: var(--bg-primary) !important;
|
| 170 |
+
color: var(--text-primary) !important;
|
| 171 |
+
}
|
| 172 |
+
#MainMenu, footer, .stDeployButton { display: none !important; }
|
| 173 |
+
.block-container { padding-top: 1.5rem !important; max-width: 1400px; }
|
| 174 |
+
|
| 175 |
+
[data-testid="stSidebar"] {
|
| 176 |
+
background: var(--bg-secondary) !important;
|
| 177 |
+
border-right: 1px solid var(--border) !important;
|
| 178 |
+
}
|
| 179 |
+
[data-testid="stMetric"] {
|
| 180 |
+
background: var(--bg-card) !important;
|
| 181 |
+
border: 1px solid var(--border) !important;
|
| 182 |
+
border-radius: var(--radius) !important;
|
| 183 |
+
padding: 1.25rem 1.5rem !important;
|
| 184 |
+
box-shadow: 0 1px 3px rgba(0,0,0,0.06) !important;
|
| 185 |
+
}
|
| 186 |
+
</style>
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
CATEGORY_COLORS = {
|
| 190 |
+
"coding": "#22d3ee",
|
| 191 |
+
"browsing": "#f59e0b",
|
| 192 |
+
"communication": "#10b981",
|
| 193 |
+
"design": "#a78bfa",
|
| 194 |
+
"documents": "#fb923c",
|
| 195 |
+
"media": "#f43f5e",
|
| 196 |
+
"system": "#64748b",
|
| 197 |
+
"idle": "#374151",
|
| 198 |
+
"uncategorized": "#6366f1",
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ─── Helpers ─────────────────────────────────────────────────────────────────
|
| 203 |
+
|
| 204 |
+
def fmt_duration(seconds: Optional[float]) -> str:
|
| 205 |
+
"""Format seconds to human-readable HH:MM or Xh Ym."""
|
| 206 |
+
if not seconds:
|
| 207 |
+
return "0m"
|
| 208 |
+
seconds = int(seconds)
|
| 209 |
+
h, m = divmod(seconds // 60, 60) if seconds >= 3600 else (0, seconds // 60)
|
| 210 |
+
if seconds >= 3600:
|
| 211 |
+
return f"{h}h {m:02d}m"
|
| 212 |
+
return f"{m}m {seconds % 60:02d}s" if m == 0 else f"{m}m"
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def fmt_duration_long(seconds: Optional[float]) -> str:
|
| 216 |
+
if not seconds:
|
| 217 |
+
return "0 min"
|
| 218 |
+
seconds = int(seconds)
|
| 219 |
+
h = seconds // 3600
|
| 220 |
+
m = (seconds % 3600) // 60
|
| 221 |
+
parts = []
|
| 222 |
+
if h: parts.append(f"{h}h")
|
| 223 |
+
if m: parts.append(f"{m}m")
|
| 224 |
+
return " ".join(parts) or "< 1m"
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def get_focus_score(focus_sec: float, total_sec: float) -> float:
|
| 228 |
+
if not total_sec:
|
| 229 |
+
return 0.0
|
| 230 |
+
return round((focus_sec / total_sec) * 100, 1)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def privacy_badge():
|
| 234 |
+
"""Render the privacy badge present on every screen."""
|
| 235 |
+
st.markdown("""
|
| 236 |
+
<div style="
|
| 237 |
+
display:inline-flex; align-items:center; gap:6px;
|
| 238 |
+
background:rgba(99,102,241,0.08); border:1px solid rgba(99,102,241,0.2);
|
| 239 |
+
border-radius:20px; padding:4px 12px; font-size:0.72rem;
|
| 240 |
+
color:#9090b0; font-family:'Inter',sans-serif; margin-bottom:0.5rem;
|
| 241 |
+
">
|
| 242 |
+
<span style="color:#10b981; font-size:0.85rem;">●</span>
|
| 243 |
+
<strong style="color:#6366f1;">100% private</strong>
|
| 244 |
+
• All data stays on your device
|
| 245 |
+
</div>
|
| 246 |
+
""", unsafe_allow_html=True)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def page_header(title: str, subtitle: str = ""):
|
| 250 |
+
"""Render a styled page header."""
|
| 251 |
+
st.markdown(f"""
|
| 252 |
+
<div style="margin-bottom:1.5rem;">
|
| 253 |
+
<h1 style="
|
| 254 |
+
font-family:'Syne',sans-serif; font-weight:800;
|
| 255 |
+
font-size:1.9rem; margin:0; letter-spacing:-0.02em;
|
| 256 |
+
background: linear-gradient(135deg, #f0f0ff, #9090d0);
|
| 257 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
| 258 |
+
">{title}</h1>
|
| 259 |
+
{"" if not subtitle else f'<p style="color:#9090b0; margin:4px 0 0; font-size:0.88rem;">{subtitle}</p>'}
|
| 260 |
+
</div>
|
| 261 |
+
""", unsafe_allow_html=True)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def status_dot(status: str) -> str:
|
| 265 |
+
colors = {"running": "#10b981", "paused": "#f59e0b", "stopped": "#f43f5e"}
|
| 266 |
+
labels = {"running": "Tracking", "paused": "Paused", "stopped": "Stopped"}
|
| 267 |
+
c = colors.get(status, "#6366f1")
|
| 268 |
+
l = labels.get(status, status.title())
|
| 269 |
+
return f'<span style="color:{c}; font-size:0.8rem;">● {l}</span>'
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def category_pill(category: str) -> str:
|
| 273 |
+
color = CATEGORY_COLORS.get(category, "#6366f1")
|
| 274 |
+
return (
|
| 275 |
+
f'<span style="background:{color}22; color:{color}; '
|
| 276 |
+
f'border:1px solid {color}44; border-radius:20px; '
|
| 277 |
+
f'padding:2px 10px; font-size:0.72rem; font-weight:600; '
|
| 278 |
+
f'font-family:DM Mono,monospace">{category}</span>'
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def get_db():
|
| 283 |
+
"""Get cached database instance via session state."""
|
| 284 |
+
from database import Database
|
| 285 |
+
if "db" not in st.session_state:
|
| 286 |
+
db = Database()
|
| 287 |
+
db.initialize()
|
| 288 |
+
st.session_state.db = db
|
| 289 |
+
return st.session_state.db
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def get_date_range(selection: str):
|
| 293 |
+
today = date.today()
|
| 294 |
+
if selection == "Today":
|
| 295 |
+
start = datetime.combine(today, datetime.min.time())
|
| 296 |
+
end = datetime.combine(today, datetime.max.time())
|
| 297 |
+
elif selection == "Yesterday":
|
| 298 |
+
y = today - timedelta(days=1)
|
| 299 |
+
start = datetime.combine(y, datetime.min.time())
|
| 300 |
+
end = datetime.combine(y, datetime.max.time())
|
| 301 |
+
elif selection == "Last 7 days":
|
| 302 |
+
start = datetime.combine(today - timedelta(days=6), datetime.min.time())
|
| 303 |
+
end = datetime.combine(today, datetime.max.time())
|
| 304 |
+
elif selection == "Last 30 days":
|
| 305 |
+
start = datetime.combine(today - timedelta(days=29), datetime.min.time())
|
| 306 |
+
end = datetime.combine(today, datetime.max.time())
|
| 307 |
+
else: # Custom
|
| 308 |
+
return None, None
|
| 309 |
+
return start, end
|