Translate documentation to english

This commit is contained in:
heboba
2026-02-26 20:25:20 +00:00
parent 06add127ff
commit bd23a9da8a
2 changed files with 341 additions and 338 deletions

334
DESIGN.md
View File

@@ -1,86 +1,86 @@
# Design / Architecture
## Цель
## Goal
Сервис генерирует Spotify playlist "daily vibe" на основе:
The service generates a Spotify "daily vibe" playlist based on:
- recent listening пользователя
- кэша liked tracks
- истории уже выданных рекомендаций
- the user's recent listening
- a local cache of liked tracks
- the history of tracks previously recommended by the bot
Управление идет через Telegram-бота (`/generate`, `/connect`, `/status` и т.д.), а также опционально через nightly cron trigger.
The main user interface is a Telegram bot (`/generate`, `/connect`, `/status`, etc.), with an optional nightly cron trigger.
## Высокоуровневая схема
## High-level overview
Компоненты:
Core components:
- `FastAPI` приложение
- healthcheck
- `FastAPI` application
- health check
- Spotify OAuth start/callback
- internal endpoint для cron (`/internal/jobs/nightly`)
- internal endpoint for cron (`/internal/jobs/nightly`)
- `TelegramBotRunner` (polling)
- принимает команды пользователей
- запускает генерацию и отправляет статусы
- handles user commands
- starts generation and sends status updates
- `PlaylistJobService`
- orchestration одного run (token -> sync likes -> candidates -> playlist -> persist)
- orchestrates a single run (token -> sync likes -> candidates -> playlist -> persist)
- `RecommendationEngine`
- строит seed profile
- собирает candidate pool
- ранжирует и отбирает треки
- builds seed profile
- collects candidate pool
- ranks and selects tracks
- `SpotifyClient` / `LastFmClient`
- внешние API вызовы
- `SQLite` (через SQLAlchemy async)
- пользователи, кэш лайков, история рекомендаций, run log
- external API calls
- `SQLite` (via async SQLAlchemy)
- users, liked cache, recommendation history, run log
## Runtime / Lifecycle
## Runtime / lifecycle
Точка входа: `app/main.py`.
Entry point: `app/main.py`.
На startup:
On startup:
1. Загружается `Settings` (`app/config.py`)
2. Создается async SQLAlchemy engine и session factory (`app/db/session.py`)
3. Выполняется `create_all` (автосоздание таблиц)
4. Создается общий `httpx.AsyncClient`
5. Создаются клиенты:
1. Load `Settings` (`app/config.py`)
2. Create async SQLAlchemy engine and session factory (`app/db/session.py`)
3. Run `create_all` (auto-create tables)
4. Create shared `httpx.AsyncClient`
5. Create API clients:
- `SpotifyClient`
- `LastFmClient`
6. Создаются сервисы:
6. Create services:
- `SpotifyAuthService`
- `RecommendationEngine`
- `PlaylistJobService`
7. Инициализируется `TelegramBotRunner` и запускается polling
8. Все объекты складываются в `app.state.runtime` и `app.state.services`
7. Initialize `TelegramBotRunner` and start polling
8. Store runtime/service objects in `app.state.runtime` and `app.state.services`
На shutdown:
On shutdown:
- останавливается Telegram polling
- закрывается `httpx.AsyncClient`
- закрывается DB engine
- stop Telegram polling
- close `httpx.AsyncClient`
- dispose DB engine
## Контейнеры / Deployment
## Containers / deployment
`docker-compose.yml`:
`docker-compose.yml` defines:
- `app` (основной сервис, FastAPI + Telegram polling)
- `cron` (опциональный сервис с `supercronic`)
- `app` (main service, FastAPI + Telegram polling)
- `cron` (optional service with `supercronic`)
Важно:
Important:
- `cron` помечен `profiles: ["cron"]` и по умолчанию не стартует
- manual-first режим: пользователь генерирует плейлисты через Telegram `/generate`
- `cron` is under `profiles: ["cron"]` and does not start by default
- the project is now manual-first: users generate playlists via Telegram `/generate`
`cron` выполняет `scripts/run_nightly.sh`, который вызывает:
`cron` runs `scripts/run_nightly.sh`, which calls:
- `POST /internal/jobs/nightly` с `Authorization: Bearer <INTERNAL_JOB_TOKEN>`
- `POST /internal/jobs/nightly` with `Authorization: Bearer <INTERNAL_JOB_TOKEN>`
## Слои приложения
## Application layers
### 1. API Layer (`app/api/routes.py`)
### 1. API layer (`app/api/routes.py`)
Назначение:
Responsibilities:
- HTTP endpoints для OAuth и internal jobs
- HTTP endpoints for OAuth and internal jobs
Endpoints:
@@ -89,18 +89,18 @@ Endpoints:
- `GET /auth/spotify/callback`
- `POST /internal/jobs/nightly`
Особенности:
Notes:
- OAuth callback после успеха отправляет сообщение в Telegram пользователю
- internal nightly endpoint защищен `INTERNAL_JOB_TOKEN`
- OAuth callback sends a Telegram notification to the user on success
- nightly endpoint is protected by `INTERNAL_JOB_TOKEN`
### 2. Bot Layer (`app/bot/telegram_bot.py`)
### 2. Bot layer (`app/bot/telegram_bot.py`)
Назначение:
Responsibilities:
- пользовательский интерфейс через Telegram команды
- user-facing interface via Telegram commands and reply-keyboard buttons
Поддерживаемые команды:
Supported commands:
- `/start`
- `/help`
@@ -111,118 +111,120 @@ Endpoints:
- `/setsize`
- `/setratio`
- `/sync`
- `/lang`
Особенности:
Notes:
- `/generate` запускает `PlaylistJobService.generate_for_user(..., force=True, notify=False)`
- `/sync` только обновляет кэш лайков
- у каждой команды свой короткий DB session через `session_factory`
- `/generate` calls `PlaylistJobService.generate_for_user(..., force=True, notify=False)`
- `/sync` only refreshes liked tracks cache
- each command uses a short-lived DB session from `session_factory`
- bot UI supports `ru` and `en` (localized text/buttons)
### 3. Service Layer
### 3. Service layer
#### `SpotifyAuthService` (`app/services/spotify_auth.py`)
Роли:
Responsibilities:
- создание OAuth state
- обмен `code` на токены
- create OAuth state
- exchange `code` for tokens
- refresh access token
- защита от истекшего access token
- ensure valid access token before Spotify calls
Особенности:
Notes:
- сравнение дат нормализуется в UTC (важно для SQLite naive datetime)
- сохраняет scopes и expiry в таблице `users`
- datetime comparison is normalized to UTC (important for SQLite naive datetimes)
- stores scopes and expiry on the `users` row
#### `RecommendationEngine` (`app/services/recommendation.py`)
Роли:
Responsibilities:
- sync liked tracks в локальный кэш
- sync liked tracks into local cache
- build seed profile
- collect candidates из нескольких источников
- rank/select итоговый список
- collect candidates from multiple sources
- rank/select final track list
Текущие источники кандидатов:
Current candidate sources:
- Spotify recommendations
- Spotify artist top tracks
- Spotify search (seed artist fallback)
- Spotify search (seed-artist fallback)
- Last.fm track similar -> Spotify search
- Last.fm artist similar -> Spotify search
Ключевые особенности:
Key implementation details:
- соблюдение лимита Spotify recommendations: максимум `5` seed'ов на запрос
- мягкая деградация при частичных ошибках источников
- liked fallback (если весь пул оказался уже в лайках)
- respects Spotify recommendations seed limit: max `5` seeds per request
- degrades gracefully when some sources fail
- includes liked fallback (if all candidates are already liked)
#### `PlaylistJobService` (`app/services/playlist_job.py`)
Роли:
Responsibilities:
- orchestration полного run
- создание Spotify playlist и добавление треков
- запись run и треков в БД
- обновление recommendation history
- отправка уведомления в Telegram (если задан notifier)
- orchestrate an end-to-end playlist generation run
- create Spotify playlist and add tracks
- persist run details and track list
- update recommendation history
- send Telegram notifications (if notifier is configured)
Порядок выполнения run:
Run sequence:
1. Проверка пользователя / Spotify connection
2. Создание записи `playlist_runs` со статусом `running`
3. Получение valid access token
1. Validate user / Spotify connection
2. Create `playlist_runs` row with `running` status
3. Get valid access token
4. Sync liked tracks
5. Сборка плейлиста через `RecommendationEngine`
6. Создание playlist в Spotify
7. Добавление треков в playlist
8. Сохранение run-трека/истории/метаданных
9. Commit и возврат `JobOutcome`
5. Build playlist via `RecommendationEngine`
6. Create playlist in Spotify
7. Add tracks to playlist
8. Persist run tracks / history / metadata
9. Commit and return `JobOutcome`
При ошибке:
On error:
- `playlist_runs.status = failed`
- в `notes` записывается сообщение ошибки
- error message is written to `notes`
## Client Layer
## Client layer
### `SpotifyClient` (`app/clients/spotify.py`)
Инкапсулирует Spotify Web API.
Encapsulates Spotify Web API calls.
Что важно в текущей реализации:
Important implementation choices:
- `create_playlist()` использует `POST /me/playlists`
- это выбранный маршрут, потому что `POST /users/{id}/playlists` может давать `403` в некоторых аккаунтах/приложениях
- `add_playlist_items()` использует `POST /playlists/{playlist_id}/items`
- маршрут `/tracks` в практике может отдавать `403`, хотя `/items` работает
- `delete_playlist()` вызывает `DELETE /playlists/{playlist_id}/followers`
- это "unfollow" (Spotify не поддерживает hard delete playlist)
- встроены retry на `429` (rate-limit) с `Retry-After`
- `create_playlist()` uses `POST /me/playlists`
- chosen because `POST /users/{id}/playlists` can return `403` in some app/account combinations
- `add_playlist_items()` uses `POST /playlists/{playlist_id}/items`
- `/tracks` may return `403` while `/items` succeeds
- `delete_playlist()` uses `DELETE /playlists/{playlist_id}/followers`
- this is "unfollow" (Spotify does not support hard-delete of playlists)
- built-in retry for `429` rate limiting using `Retry-After`
### `LastFmClient` (`app/clients/lastfm.py`)
Используется как optional enrichment layer.
Optional enrichment source for similarity.
- может быть отключен (если `LASTFM_API_KEY` пустой)
- ошибки Last.fm не должны ломать весь run, если другие источники работают
- can be disabled (empty `LASTFM_API_KEY`)
- Last.fm errors should not fail the whole run if other sources still work
## Persistence Layer (SQLite + SQLAlchemy)
## Persistence layer (SQLite + SQLAlchemy)
### Таблицы (`app/db/models.py`)
### Tables (`app/db/models.py`)
#### `users`
Хранит:
Stores:
- Telegram identity (`telegram_chat_id`, `telegram_username`)
- Spotify identity/tokens/scopes (`spotify_user_id`, access/refresh token, expiry, scopes)
- пользовательские настройки (`playlist_size`, `min_new_ratio`, timezone)
- последние результаты (`last_generated_date`, `latest_playlist_id`, `latest_playlist_url`)
- user settings (`playlist_size`, `min_new_ratio`, timezone)
- last outputs (`last_generated_date`, `latest_playlist_id`, `latest_playlist_url`)
#### `auth_states`
Временные OAuth state для callback:
Temporary OAuth state for callback:
- `state`
- `telegram_chat_id`
@@ -230,15 +232,15 @@ Endpoints:
#### `saved_tracks`
Локальный кэш `Liked Songs` пользователя:
Local cache of the user's `Liked Songs`:
- `spotify_track_id`
- название/артисты/album/popularity
- track/artist metadata, album, popularity
- `added_at`
#### `recommendation_history`
История ранее рекомендованных треков:
History of previously recommended tracks:
- `spotify_track_id`
- `first_recommended_at`
@@ -247,30 +249,30 @@ Endpoints:
#### `playlist_runs`
Run log генерации:
Playlist generation run log:
- статус (`running/success/failed`)
- метаданные Spotify playlist
- статистика (`total/new/reused`)
- status (`running/success/failed`)
- Spotify playlist metadata
- stats (`total/new/reused`)
- `notes`
#### `playlist_run_tracks`
Снимок состава конкретного run:
Snapshot of tracks in a specific run:
- track id / name / artists
- source (из какого источника пришел)
- позиция
- source (which source produced the track)
- position
- `is_new_to_bot`
### Repository Layer (`app/db/repositories.py`)
### Repository layer (`app/db/repositories.py`)
Паттерн:
Pattern:
- thin repositories над SQLAlchemy AsyncSession
- изолируют CRUD/query-логику от service layer
- thin repositories over `AsyncSession`
- isolates CRUD/query logic from the service layer
Примеры:
Repositories include:
- `UserRepository`
- `AuthStateRepository`
@@ -278,55 +280,55 @@ Run log генерации:
- `RecommendationHistoryRepository`
- `PlaylistRunRepository`
## Потоки данных
## Data flows
### OAuth Flow
### OAuth flow
1. Telegram `/connect`
2. `SpotifyAuthService.create_connect_url()`
3. Пользователь идет в Spotify auth page
3. User opens Spotify auth page
4. `GET /auth/spotify/callback`
5. `SpotifyAuthService.handle_callback()`
6. Токены и Spotify profile сохраняются в `users`
7. Пользователю отправляется сообщение в Telegram
6. Tokens and Spotify profile are saved to `users`
7. User receives a Telegram confirmation message
### Manual Generate Flow (`/generate`)
### Manual generation flow (`/generate`)
1. Telegram `/generate`
2. `PlaylistJobService.generate_for_user(..., force=True)`
3. Sync likes + recent listening + candidate collection
4. Playlist create + add items в Spotify
3. Sync likes + load recent listening + collect candidates
4. Create playlist + add items in Spotify
5. Persist run/history
6. Ответ пользователю в Telegram
6. Reply to user in Telegram
### Nightly Cron Flow (optional)
### Nightly cron flow (optional)
1. `supercronic` в `cron` контейнере
1. `supercronic` in the `cron` container
2. `scripts/run_nightly.sh`
3. `POST /internal/jobs/nightly`
4. `PlaylistJobService.generate_for_all_connected_users()`
## Concurrency / Consistency
## Concurrency / consistency
- Генерация защищена одним `asyncio.Lock` (`generate_lock`) в `PlaylistJobService`
- предотвращает одновременные run'ы и гонки обновления history
- Большинство операций run выполняются в одной DB session
- Ошибки внутри run переводят запись run в `failed`
- Generation is protected by a single `asyncio.Lock` (`generate_lock`) in `PlaylistJobService`
- prevents overlapping runs and history update races
- Most run operations happen in one DB session
- Errors inside a run mark the run as `failed`
## Алгоритм рекомендаций (кратко)
## Recommendation algorithm (summary)
Подробно см. `README.md`, но архитектурно pipeline такой:
Detailed explanation is in `README.md`, but architecturally the pipeline is:
1. Seed profile (recent + liked)
2. Candidate pool (Spotify + Last.fm + fallback search)
3. Dedupe
4. Rank (score penalties/boosts)
1. Build seed profile (recent + liked)
2. Collect candidate pool (Spotify + Last.fm + fallback search)
3. Deduplicate
4. Rank (penalties/boosts)
5. Select (min_new_ratio + artist caps)
6. Persist stats/history
## Конфигурация
## Configuration
Основные env-переменные (`app/config.py`):
Main environment variables (`app/config.py`):
- `TELEGRAM_BOT_TOKEN`
- `SPOTIFY_CLIENT_ID`
@@ -341,23 +343,23 @@ Run log генерации:
- `RECENT_DAYS_WINDOW`
- `PLAYLIST_VISIBILITY`
## Диагностика / Наблюдаемость
## Diagnostics / observability
Сейчас:
Current state:
- основной feedback идет через Telegram сообщения и `playlist_runs.notes`
- HTTP `/health` для liveness
- тесты покрывают критичные Spotify routes и части recommendation pipeline
- primary feedback comes from Telegram messages and `playlist_runs.notes`
- HTTP `/health` for liveness
- tests cover critical Spotify routes and parts of the recommendation pipeline
Что можно улучшить:
Possible improvements:
- структурированные логи по source coverage (сколько кандидатов из каждого источника)
- метрики latency/ошибок Spotify/Last.fm
- отдельный debug endpoint для dry-run (без создания playlist)
- structured logs for source coverage (how many candidates from each source)
- metrics for Spotify/Last.fm errors and latency
- dedicated debug dry-run endpoint (without creating a playlist)
## Известные ограничения
## Known limitations
- SQLite подходит для small-scale / single-node сценария
- Telegram polling + FastAPI живут в одном процессе/контейнере
- per-user timezone используется ограниченно (cron общий)
- внешние API ограничения (Spotify/Last.fm) могут различаться между приложениями/аккаунтами
- SQLite is suitable for small-scale / single-node setups
- Telegram polling + FastAPI run in the same process/container
- per-user timezone support is limited (cron is global)
- external API limitations (Spotify/Last.fm) vary by app/account