{"id":33319254,"url":"https://github.com/victormarlor/hyperfocus","last_synced_at":"2025-11-19T20:01:07.449Z","repository":{"id":324769266,"uuid":"1098484265","full_name":"victormarlor/HyperFocus","owner":"victormarlor","description":"Typed, test-driven FastAPI backend using SQLModel and SQLite to analyze user focus, interruptions, and time-based productivity metrics.","archived":false,"fork":false,"pushed_at":"2025-11-17T19:47:26.000Z","size":23,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-17T20:26:01.245Z","etag":null,"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"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/victormarlor.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-17T18:47:41.000Z","updated_at":"2025-11-17T19:47:29.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/victormarlor/HyperFocus","commit_stats":null,"previous_names":["victormarlor/hyperfocus"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/victormarlor/HyperFocus","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/victormarlor%2FHyperFocus","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/victormarlor%2FHyperFocus/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/victormarlor%2FHyperFocus/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/victormarlor%2FHyperFocus/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/victormarlor","download_url":"https://codeload.github.com/victormarlor/HyperFocus/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/victormarlor%2FHyperFocus/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":285319005,"owners_count":27151474,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-19T02:00:05.673Z","response_time":65,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["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"],"created_at":"2025-11-19T20:00:29.093Z","updated_at":"2025-11-19T20:01:07.438Z","avatar_url":"https://github.com/victormarlor.png","language":"Python","readme":"![Tests](https://github.com/victormarlor/HyperFocus/actions/workflows/tests.yml/badge.svg)\n\n# HyperFocus – Deep Work \u0026 Interruptions Analytics API\n\nHyperFocus is a backend API designed to help remote workers and students understand **how they actually focus** during their workday.\n\nIt lets a user:\n\n- Start and end *focus sessions*\n- Log *interruptions* (phone, family, noise, self-distractions, urgent tasks…)\n- Generate **analytics** about:\n  - Total focused time vs. time lost\n  - Which interruption types affect them the most\n  - At what hours they are most productive\n  - When they get most distracted\n  - Weekly concentration patterns\n\n---\n\n## 💡 Problem\n\nPeople who work or study remotely get interrupted all the time:\n\n- Family or roommates\n- Phone notifications\n- Noise\n- “Quick” urgent tasks\n- Self-distractions (social media, random browsing, etc.)\n\nWe all *feel* less productive, but it's hard to **measure**:\n\n- How much time we really work vs. lose  \n- Which sources of interruption hurt us the most  \n- When (time of day or week) we struggle to focus  \n\n**HyperFocus** converts those everyday interruptions into meaningful metrics and patterns you can act on.\n\n---\n\n## 🎯 What This API Does\n\nCore capabilities:\n\n- ✅ Manage users  \n- ✅ Track focus sessions per user  \n- ✅ Log interruptions inside a session  \n- ✅ Automatically compute interruption duration  \n- ✅ Compute advanced analytics:\n  - Summary: total work time, time lost, effective focus time\n  - Breakdown by interruption type\n  - Productivity by hour of day\n  - Peak distraction hour\n  - Weekly concentration pattern\n\nThe focus is not just CRUD, but **useful analytics** that reflect real human behavior.\n\n---\n\n## 🧱 Tech Stack\n\n- **Language:** Python  \n- **Framework:** FastAPI  \n- **ORM:** SQLModel (SQLAlchemy + Pydantic)  \n- **Database:** SQLite  \n- **Schemas:** Pydantic v2  \n- **Testing:** Pytest + FastAPI TestClient  \n- **Containerization:** Docker  \n- **Docs:** Auto-generated OpenAPI (Swagger UI)\n\n---\n\n## 📁 Project Structure\n\n```\nhyperfocus/\n├─ app/\n│  ├─ main.py                 # FastAPI app, lifespan, router registration\n│  ├─ models.py               # SQLModel models (User, Session, Interruption)\n│  ├─ schemas.py              # Pydantic schemas (input/output)\n│  ├─ db.py                   # DB engine, session dependency, table creation\n│  ├─ core/\n│  │   ├─ stats_logic.py      # All analytics and statistics logic\n│  │   └─ config.py           # (Reserved for future configuration)\n│  └─ routers/\n│      ├─ users.py            # /users endpoints\n│      ├─ sessions.py         # /sessions endpoints\n│      ├─ interruptions.py    # /interruptions endpoints\n│      └─ stats.py            # /users/{id}/stats endpoints\n├─ tests/\n│  ├─ test_interruptions_api.py  # End-to-end API tests (user → session → interruption)\n│  ├─ test_stats_logic.py        # Unit tests for analytics logic\n│  └─ conftest.py                # Test DB setup (in-memory SQLite)\n├─ requirements.txt\n├─ Dockerfile\n└─ README.md\n````\n\n---\n\n## 🗄️ Data Model\n\n### `User`\n\nRepresents a person using the system.\n\n* `id`: int (PK)\n* `name`: str\n* `email`: str (unique)\n* `created_at`: datetime (UTC)\n\n---\n\n### `Session` (Focus Session)\n\nRepresents a block of focused work.\n\n* `id`: int (PK)\n* `user_id`: FK → `User`\n* `start_time`: datetime\n* `end_time`: datetime | null (null = still active)\n* `created_at`: datetime\n\nRules:\n\n* A user cannot have **two active sessions** at the same time.\n\n---\n\n### `Interruption`\n\nRepresents a single interruption inside a session.\n\n* `id`: int (PK)\n* `session_id`: FK → `Session`\n* `user_id`: FK → `User`\n* `type`: `\"family\" | \"phone\" | \"noise\" | \"self\" | \"urgent_task\" | \"unknown\"`\n* `description`: str\n* `start_time`: datetime\n* `end_time`: datetime\n* `duration`: int (seconds, computed automatically)\n* `created_at`: datetime\n\nConstraints:\n\n* Every interruption belongs to exactly one session.\n* `end_time` must be greater than `start_time`.\n\n---\n\n## 🚀 Getting Started\n\n### 1. Clone the repo\n\n```\ngit clone https://github.com/\u003cyour-username\u003e/hyperfocus.git\ncd hyperfocus\n```\n\n### 2. Create and activate a virtual environment\n\n**Windows (PowerShell):**\n\n```\npy -m venv venv\n.\\venv\\Scripts\\Activate\n```\n\n**macOS / Linux:**\n\n```\npython -m venv venv\nsource venv/bin/activate\n```\n\n### 3. Install dependencies\n\n```\npip install -r requirements.txt\n```\n\n### 4. Run the development server\n\n```\nuvicorn app.main:app --reload\n```\n\nAccess:\n\n* Swagger UI: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)\n* ReDoc: [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)\n* Health check: `GET /` → `{\"message\": \"HyperFocus API is running 🚀\"}`\n\n---\n\n## 🐳 Run with Docker (optional)\n\nBuild the image:\n\n```\ndocker build -t hyperfocus-api .\n```\n\nRun the container:\n\n```\ndocker run -p 8000:8000 hyperfocus-api\n```\n\nAPI will be available at `http://127.0.0.1:8000`.\n\n---\n\n## 📌 Core API Overview\n\n### 👤 Users\n\n**Create user**\n\n```\nPOST /users/\n```\n\nBody example:\n\n```\n{ \"name\": \"Victor\", \"email\": \"victor@example.com\" }\n```\n\n**Get user by ID**\n\n```\nGET /users/{id}\n```\n\n---\n\n### ⏱ Sessions\n\n**Start a session**\n\n```\nPOST /sessions/start\n```\n\nBody:\n\n```\n{ \"user_id\": 1 }\n```\n\nRules:\n\n* If the user already has an active session → HTTP 400.\n\n**End a session**\n\n```\nPOST /sessions/{id}/end\n```\n\n**Get a session**\n\n```\nGET /sessions/{id}\n```\n\n**List user sessions (optional day filter)**\n\n```\nGET /sessions/user/{user_id}?day=YYYY-MM-DD\n```\n\n---\n\n### ❗ Interruptions\n\n**Create interruption**\n\n```\nPOST /interruptions/\n```\n\nExample:\n\n```\n{\n  \"session_id\": 1,\n  \"user_id\": 1,\n  \"type\": \"phone\",\n  \"description\": \"WhatsApp messages\",\n  \"start_time\": \"2025-11-15T16:00:00Z\",\n  \"end_time\": \"2025-11-15T16:02:30Z\"\n}\n```\n\nBackend automatically:\n\n* Validates session ownership\n* Ensures session is active\n* Ensures `end_time \u003e start_time`\n* Computes `duration`\n\n**List interruptions**\n\n```\nGET /interruptions/session/{session_id}\n```\n\n---\n\n## 📊 Statistics (Analytics)\n\nAll under:\n\n```\n/users/{user_id}/stats/...\n```\n\n### Available Endpoints\n\n| Endpoint                       | Description                         |\n| ------------------------------ | ----------------------------------- |\n| `/stats/summary`               | High-level focus summary            |\n| `/stats/interruption-types`    | Counts \u0026 proportions by type        |\n| `/stats/productive-hours`      | Focus vs. distractions by hour      |\n| `/stats/peak-distraction-time` | Hour of day with most interruptions |\n| `/stats/weekly-pattern`        | Monday–Sunday focus overview        |\n\n---\n\n### Summary Example\n\n`GET /users/{user_id}/stats/summary?range=7d`\n\nIncludes:\n\n* `total_sessions`\n* `total_interruptions`\n* `total_time_worked_seconds`\n* `total_time_lost_seconds`\n* `effective_time_seconds`\n* `average_interruption_duration_seconds`\n* `interruptions_per_hour`\n\n---\n\n### Weekly Pattern Example\n\nEach entry contains:\n\n```\n{\n  \"weekday_index\": 0,\n  \"weekday_name\": \"monday\",\n  \"work_seconds\": 5400,\n  \"time_lost_seconds\": 600,\n  \"effective_time_seconds\": 4800,\n  \"interruptions\": 3\n}\n```\n\n---\n\n## 🧪 Testing\n\nRun all tests:\n\n```\npytest\n```\n\nIncludes:\n\n* **Unit tests** for analytics (`test_stats_logic.py`)\n* **Integration tests** for the interruption flow (`test_interruptions_api.py`)\n* **In-memory DB** using `sqlite://` + `StaticPool`\n* `TestClient` with dependency overrides\n\n---\n\n## 🧠 Design Decisions\n\n* **SQLModel** chosen for strong typing + declarative models.\n* **UTC timezone-aware datetimes** for reliable time calculations.\n* **Separation of concerns**:\n\n  * Routers → HTTP logic\n  * Models/Schemas → data layer\n  * `stats_logic.py` → business \u0026 analytics\n* **Layered validation** (schemas → API → DB constraints).\n* **Tests** ensure analytics work exactly as expected.\n\n---\n\n## 🚧 Future Improvements\n\n* Authentication (JWT)\n* Rate limiting\n* Export stats (CSV / JSON)\n* A dashboard frontend\n* More advanced analytics (focus score)\n* Deployment on Fly.io / Railway with Docker\n\n---\n\n## 🧾 What I Learned\n\nWhile building HyperFocus I practiced:\n\n* Modeling a real-world domain (focus sessions \u0026 interruptions)\n* Clean FastAPI architecture\n* SQLModel relationships\n* UTC datetime handling\n* Separation of analytics logic\n* Writing both unit and end-to-end API tests\n\n---\n\n## 📄 License\n\nThis project is licensed under the **MIT License**.\nSee the [LICENSE](./LICENSE) file for details.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvictormarlor%2Fhyperfocus","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvictormarlor%2Fhyperfocus","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvictormarlor%2Fhyperfocus/lists"}