Files
writer-ide/backend/services/bible_service.py
T
admin 46af290db3
Build and Push Docker Images / build-and-push (push) Failing after 3m33s
initial commit
2026-11-07 16:39:43 +03:00

136 lines
5.5 KiB
Python

import json
from datetime import datetime
from pathlib import Path
from config.settings import settings
from models.bible import Character, Event, Location, StoryBible, StoryThread
from services.project_service import project_service
class BibleService:
def __init__(self):
from config.settings import settings
self.data_dir = Path(settings.DATA_DIR)
self.project_service = project_service
def _get_bible_file(self, project_id: str, user_id: str) -> Path:
"""Получить путь к файлу Story Bible проекта"""
project_dir = self.project_service.get_project_dir(project_id, user_id)
return project_dir / "story_bible.json"
def _load_bible(self, project_id: str, user_id: str) -> StoryBible:
"""Загрузить Story Bible проекта"""
bible_file = self._get_bible_file(project_id, user_id)
if bible_file.exists():
with open(bible_file, "r", encoding="utf-8") as f:
data = json.load(f)
return StoryBible(**data)
else:
# Инициализация с примером данных
return self._create_sample_bible()
def _create_sample_bible(self) -> StoryBible:
"""Создать пример Story Bible для тестирования"""
return StoryBible(
characters=[
Character(
name="Алекс",
description="Главный герой, бывший архитектор",
traits=["Циничный", "Справедливый", "Наблюдательный"],
appearance="Высокий, темные волосы, шрам на левой руке",
role="protagonist",
),
Character(
name="Лира",
description="Таинственная проводница",
traits=["Загадочная", "Решительная"],
appearance="Носит красный плащ, зеленые глаза",
role="supporting",
),
],
locations=[
Location(
name="Нижний Город",
description="Старая часть города с узкими улочками",
atmosphere="Вечный туман, запах озона и мокрого камня",
type="city",
)
],
events=[
Event(
title="Встреча с Лирой",
description="Алекс встречает Лиру в тумане Нижнего Города",
chapter="Глава 1",
importance="major",
)
],
threads=[
StoryThread(
title="Тайна хранилища",
description="Поиск древнего хранилища знаний",
status="active",
related_characters=[],
related_events=[],
)
],
last_updated=datetime.now().isoformat(),
)
def _save_bible(self, project_id: str, bible: StoryBible, user_id: str):
"""Сохранить Story Bible проекта"""
bible_file = self._get_bible_file(project_id, user_id)
bible.last_updated = datetime.now().isoformat()
with open(bible_file, "w", encoding="utf-8") as f:
json.dump(bible.model_dump(), f, ensure_ascii=False, indent=2)
def get_bible(self, project_id: str, user_id: str) -> StoryBible:
"""Получить Story Bible проекта"""
return self._load_bible(project_id, user_id)
def update_bible(
self, project_id: str, new_bible: StoryBible, user_id: str
) -> StoryBible:
"""Обновить Story Bible проекта"""
self._save_bible(project_id, new_bible, user_id)
return new_bible
def add_character(
self, project_id: str, character: Character, user_id: str
) -> Character:
"""Добавить персонажа в проект"""
bible = self._load_bible(project_id, user_id)
bible.characters.append(character)
self._save_bible(project_id, bible, user_id)
return character
def add_location(
self, project_id: str, location: Location, user_id: str
) -> Location:
"""Добавить локацию в проект"""
bible = self._load_bible(project_id, user_id)
bible.locations.append(location)
self._save_bible(project_id, bible, user_id)
return location
def add_event(self, project_id: str, event: Event, user_id: str) -> Event:
"""Добавить событие в проект"""
bible = self._load_bible(project_id, user_id)
bible.events.append(event)
self._save_bible(project_id, bible, user_id)
return event
def add_thread(
self, project_id: str, thread: StoryThread, user_id: str
) -> StoryThread:
"""Добавить сюжетную нить в проект"""
bible = self._load_bible(project_id, user_id)
bible.threads.append(thread)
self._save_bible(project_id, bible, user_id)
return thread
# Singleton instance
bible_service = BibleService()