Реализован MVP телеграм бота для изучения языков
Основные компоненты: - База данных (PostgreSQL) с моделями User, Vocabulary, Task - Интеграция с OpenAI API для перевода слов - Команды: /start, /add, /vocabulary, /help - Сервисы для работы с пользователями, словарем и AI Реализовано: ✅ Регистрация и приветствие пользователя ✅ Добавление слов в словарь с автоматическим переводом ✅ Просмотр личного словаря ✅ Архитектура проекта с разделением на слои 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
123
services/vocabulary_service.py
Normal file
123
services/vocabulary_service.py
Normal file
@@ -0,0 +1,123 @@
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from database.models import Vocabulary, WordSource, LanguageLevel
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
class VocabularyService:
|
||||
"""Сервис для работы со словарным запасом"""
|
||||
|
||||
@staticmethod
|
||||
async def add_word(
|
||||
session: AsyncSession,
|
||||
user_id: int,
|
||||
word_original: str,
|
||||
word_translation: str,
|
||||
transcription: Optional[str] = None,
|
||||
examples: Optional[dict] = None,
|
||||
category: Optional[str] = None,
|
||||
difficulty_level: Optional[str] = None,
|
||||
source: WordSource = WordSource.MANUAL,
|
||||
notes: Optional[str] = None
|
||||
) -> Vocabulary:
|
||||
"""
|
||||
Добавить слово в словарь пользователя
|
||||
|
||||
Args:
|
||||
session: Сессия базы данных
|
||||
user_id: ID пользователя
|
||||
word_original: Оригинальное слово
|
||||
word_translation: Перевод
|
||||
transcription: Транскрипция
|
||||
examples: Примеры использования
|
||||
category: Категория слова
|
||||
difficulty_level: Уровень сложности
|
||||
source: Источник добавления
|
||||
notes: Заметки пользователя
|
||||
|
||||
Returns:
|
||||
Созданный объект слова
|
||||
"""
|
||||
# Преобразование difficulty_level в enum
|
||||
difficulty_enum = None
|
||||
if difficulty_level:
|
||||
try:
|
||||
difficulty_enum = LanguageLevel[difficulty_level]
|
||||
except KeyError:
|
||||
difficulty_enum = None
|
||||
|
||||
new_word = Vocabulary(
|
||||
user_id=user_id,
|
||||
word_original=word_original,
|
||||
word_translation=word_translation,
|
||||
transcription=transcription,
|
||||
examples=examples,
|
||||
category=category,
|
||||
difficulty_level=difficulty_enum,
|
||||
source=source,
|
||||
notes=notes
|
||||
)
|
||||
|
||||
session.add(new_word)
|
||||
await session.commit()
|
||||
await session.refresh(new_word)
|
||||
|
||||
return new_word
|
||||
|
||||
@staticmethod
|
||||
async def get_user_words(session: AsyncSession, user_id: int, limit: int = 50) -> List[Vocabulary]:
|
||||
"""
|
||||
Получить все слова пользователя
|
||||
|
||||
Args:
|
||||
session: Сессия базы данных
|
||||
user_id: ID пользователя
|
||||
limit: Максимальное количество слов
|
||||
|
||||
Returns:
|
||||
Список слов пользователя
|
||||
"""
|
||||
result = await session.execute(
|
||||
select(Vocabulary)
|
||||
.where(Vocabulary.user_id == user_id)
|
||||
.order_by(Vocabulary.created_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
@staticmethod
|
||||
async def get_words_count(session: AsyncSession, user_id: int) -> int:
|
||||
"""
|
||||
Получить количество слов в словаре пользователя
|
||||
|
||||
Args:
|
||||
session: Сессия базы данных
|
||||
user_id: ID пользователя
|
||||
|
||||
Returns:
|
||||
Количество слов
|
||||
"""
|
||||
result = await session.execute(
|
||||
select(Vocabulary).where(Vocabulary.user_id == user_id)
|
||||
)
|
||||
return len(list(result.scalars().all()))
|
||||
|
||||
@staticmethod
|
||||
async def find_word(session: AsyncSession, user_id: int, word: str) -> Optional[Vocabulary]:
|
||||
"""
|
||||
Найти слово в словаре пользователя
|
||||
|
||||
Args:
|
||||
session: Сессия базы данных
|
||||
user_id: ID пользователя
|
||||
word: Слово для поиска
|
||||
|
||||
Returns:
|
||||
Объект слова или None
|
||||
"""
|
||||
result = await session.execute(
|
||||
select(Vocabulary)
|
||||
.where(Vocabulary.user_id == user_id)
|
||||
.where(Vocabulary.word_original.ilike(f"%{word}%"))
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
Reference in New Issue
Block a user