https://github.com/victormarlor/hyperfocus
Typed, test-driven FastAPI backend using SQLModel and SQLite to analyze user focus, interruptions, and time-based productivity metrics.
https://github.com/victormarlor/hyperfocus
analytics api-design async-python backend clean-architecture deep-work developer-tools docker fastapi focus-tracking productivity pydantic pytest python rest-api sqlite sqlmodel time-tracking
Last synced: about 1 month ago
JSON representation
Typed, test-driven FastAPI backend using SQLModel and SQLite to analyze user focus, interruptions, and time-based productivity metrics.
- Host: GitHub
- URL: https://github.com/victormarlor/hyperfocus
- Owner: victormarlor
- License: mit
- Created: 2025-11-17T18:47:41.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2025-11-17T19:47:26.000Z (about 1 month ago)
- Last Synced: 2025-11-17T20:26:01.245Z (about 1 month ago)
- Topics: analytics, api-design, async-python, backend, clean-architecture, deep-work, developer-tools, docker, fastapi, focus-tracking, productivity, pydantic, pytest, python, rest-api, sqlite, sqlmodel, time-tracking
- Language: Python
- Homepage:
- Size: 22.5 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README

# HyperFocus β Deep Work & Interruptions Analytics API
HyperFocus is a backend API designed to help remote workers and students understand **how they actually focus** during their workday.
It lets a user:
- Start and end *focus sessions*
- Log *interruptions* (phone, family, noise, self-distractions, urgent tasksβ¦)
- Generate **analytics** about:
- Total focused time vs. time lost
- Which interruption types affect them the most
- At what hours they are most productive
- When they get most distracted
- Weekly concentration patterns
---
## π‘ Problem
People who work or study remotely get interrupted all the time:
- Family or roommates
- Phone notifications
- Noise
- βQuickβ urgent tasks
- Self-distractions (social media, random browsing, etc.)
We all *feel* less productive, but it's hard to **measure**:
- How much time we really work vs. lose
- Which sources of interruption hurt us the most
- When (time of day or week) we struggle to focus
**HyperFocus** converts those everyday interruptions into meaningful metrics and patterns you can act on.
---
## π― What This API Does
Core capabilities:
- β
Manage users
- β
Track focus sessions per user
- β
Log interruptions inside a session
- β
Automatically compute interruption duration
- β
Compute advanced analytics:
- Summary: total work time, time lost, effective focus time
- Breakdown by interruption type
- Productivity by hour of day
- Peak distraction hour
- Weekly concentration pattern
The focus is not just CRUD, but **useful analytics** that reflect real human behavior.
---
## π§± Tech Stack
- **Language:** Python
- **Framework:** FastAPI
- **ORM:** SQLModel (SQLAlchemy + Pydantic)
- **Database:** SQLite
- **Schemas:** Pydantic v2
- **Testing:** Pytest + FastAPI TestClient
- **Containerization:** Docker
- **Docs:** Auto-generated OpenAPI (Swagger UI)
---
## π Project Structure
```
hyperfocus/
ββ app/
β ββ main.py # FastAPI app, lifespan, router registration
β ββ models.py # SQLModel models (User, Session, Interruption)
β ββ schemas.py # Pydantic schemas (input/output)
β ββ db.py # DB engine, session dependency, table creation
β ββ core/
β β ββ stats_logic.py # All analytics and statistics logic
β β ββ config.py # (Reserved for future configuration)
β ββ routers/
β ββ users.py # /users endpoints
β ββ sessions.py # /sessions endpoints
β ββ interruptions.py # /interruptions endpoints
β ββ stats.py # /users/{id}/stats endpoints
ββ tests/
β ββ test_interruptions_api.py # End-to-end API tests (user β session β interruption)
β ββ test_stats_logic.py # Unit tests for analytics logic
β ββ conftest.py # Test DB setup (in-memory SQLite)
ββ requirements.txt
ββ Dockerfile
ββ README.md
````
---
## ποΈ Data Model
### `User`
Represents a person using the system.
* `id`: int (PK)
* `name`: str
* `email`: str (unique)
* `created_at`: datetime (UTC)
---
### `Session` (Focus Session)
Represents a block of focused work.
* `id`: int (PK)
* `user_id`: FK β `User`
* `start_time`: datetime
* `end_time`: datetime | null (null = still active)
* `created_at`: datetime
Rules:
* A user cannot have **two active sessions** at the same time.
---
### `Interruption`
Represents a single interruption inside a session.
* `id`: int (PK)
* `session_id`: FK β `Session`
* `user_id`: FK β `User`
* `type`: `"family" | "phone" | "noise" | "self" | "urgent_task" | "unknown"`
* `description`: str
* `start_time`: datetime
* `end_time`: datetime
* `duration`: int (seconds, computed automatically)
* `created_at`: datetime
Constraints:
* Every interruption belongs to exactly one session.
* `end_time` must be greater than `start_time`.
---
## π Getting Started
### 1. Clone the repo
```
git clone https://github.com//hyperfocus.git
cd hyperfocus
```
### 2. Create and activate a virtual environment
**Windows (PowerShell):**
```
py -m venv venv
.\venv\Scripts\Activate
```
**macOS / Linux:**
```
python -m venv venv
source venv/bin/activate
```
### 3. Install dependencies
```
pip install -r requirements.txt
```
### 4. Run the development server
```
uvicorn app.main:app --reload
```
Access:
* Swagger UI: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
* ReDoc: [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
* Health check: `GET /` β `{"message": "HyperFocus API is running π"}`
---
## π³ Run with Docker (optional)
Build the image:
```
docker build -t hyperfocus-api .
```
Run the container:
```
docker run -p 8000:8000 hyperfocus-api
```
API will be available at `http://127.0.0.1:8000`.
---
## π Core API Overview
### π€ Users
**Create user**
```
POST /users/
```
Body example:
```
{ "name": "Victor", "email": "victor@example.com" }
```
**Get user by ID**
```
GET /users/{id}
```
---
### β± Sessions
**Start a session**
```
POST /sessions/start
```
Body:
```
{ "user_id": 1 }
```
Rules:
* If the user already has an active session β HTTP 400.
**End a session**
```
POST /sessions/{id}/end
```
**Get a session**
```
GET /sessions/{id}
```
**List user sessions (optional day filter)**
```
GET /sessions/user/{user_id}?day=YYYY-MM-DD
```
---
### β Interruptions
**Create interruption**
```
POST /interruptions/
```
Example:
```
{
"session_id": 1,
"user_id": 1,
"type": "phone",
"description": "WhatsApp messages",
"start_time": "2025-11-15T16:00:00Z",
"end_time": "2025-11-15T16:02:30Z"
}
```
Backend automatically:
* Validates session ownership
* Ensures session is active
* Ensures `end_time > start_time`
* Computes `duration`
**List interruptions**
```
GET /interruptions/session/{session_id}
```
---
## π Statistics (Analytics)
All under:
```
/users/{user_id}/stats/...
```
### Available Endpoints
| Endpoint | Description |
| ------------------------------ | ----------------------------------- |
| `/stats/summary` | High-level focus summary |
| `/stats/interruption-types` | Counts & proportions by type |
| `/stats/productive-hours` | Focus vs. distractions by hour |
| `/stats/peak-distraction-time` | Hour of day with most interruptions |
| `/stats/weekly-pattern` | MondayβSunday focus overview |
---
### Summary Example
`GET /users/{user_id}/stats/summary?range=7d`
Includes:
* `total_sessions`
* `total_interruptions`
* `total_time_worked_seconds`
* `total_time_lost_seconds`
* `effective_time_seconds`
* `average_interruption_duration_seconds`
* `interruptions_per_hour`
---
### Weekly Pattern Example
Each entry contains:
```
{
"weekday_index": 0,
"weekday_name": "monday",
"work_seconds": 5400,
"time_lost_seconds": 600,
"effective_time_seconds": 4800,
"interruptions": 3
}
```
---
## π§ͺ Testing
Run all tests:
```
pytest
```
Includes:
* **Unit tests** for analytics (`test_stats_logic.py`)
* **Integration tests** for the interruption flow (`test_interruptions_api.py`)
* **In-memory DB** using `sqlite://` + `StaticPool`
* `TestClient` with dependency overrides
---
## π§ Design Decisions
* **SQLModel** chosen for strong typing + declarative models.
* **UTC timezone-aware datetimes** for reliable time calculations.
* **Separation of concerns**:
* Routers β HTTP logic
* Models/Schemas β data layer
* `stats_logic.py` β business & analytics
* **Layered validation** (schemas β API β DB constraints).
* **Tests** ensure analytics work exactly as expected.
---
## π§ Future Improvements
* Authentication (JWT)
* Rate limiting
* Export stats (CSV / JSON)
* A dashboard frontend
* More advanced analytics (focus score)
* Deployment on Fly.io / Railway with Docker
---
## π§Ύ What I Learned
While building HyperFocus I practiced:
* Modeling a real-world domain (focus sessions & interruptions)
* Clean FastAPI architecture
* SQLModel relationships
* UTC datetime handling
* Separation of analytics logic
* Writing both unit and end-to-end API tests
---
## π License
This project is licensed under the **MIT License**.
See the [LICENSE](./LICENSE) file for details.