Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ The application allows you to automate the process of generating a bibliography

Supported citation styles:
- ГОСТ Р 7.0.5-2008
- APA 7th

## Installation

Expand Down
1 change: 1 addition & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

Поддерживаемые стили цитирования:
- ГОСТ Р 7.0.5-2008
- APA 7th

Установка
=========
Expand Down
48 changes: 48 additions & 0 deletions src/formatters/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,51 @@ class ArticlesCollectionModel(BaseModel):
publishing_house: str
year: int = Field(..., gt=0)
pages: str
class DissertationModel(BaseModel):

"""
Модель диссертации:

.. code-block::

DissertationModel(
authors="Иванов И.М., Петров С.Н.",
desertation_title="Наука как искусство",
canddoc="канд.",
sience="экон."
code="01.01.01"
city="СПб.",
year=2020,
pages=999,
)
"""

authors: str
desertation_title: str
canddoc:str
sience: str
code:str
city: str
year: int = Field(..., gt=0)
pages: int = Field(..., gt=0)
class JournalArticleModel(BaseModel):
"""
Модель статьи из журнала:

.. code-block::

MagazineArticleModel(
authors="Иванов И.М., Петров С.Н.",
article_title="Наука как искусство",
journal_title="Научный журнал",
year=2020,
journal_number=1,
pages="25-30",
)
"""
authors: str
article_title: str
journal_title: str
year: int = Field(..., gt=0)
journal_number: int = Field(..., gt=0)
pages: str
185 changes: 185 additions & 0 deletions src/formatters/styles/apa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
"""
Стиль цитирования по APA 7th.
"""
from string import Template

from pydantic import BaseModel

from formatters.models import BookModel, InternetResourceModel, ArticlesCollectionModel, JournalArticleModel, DissertationModel
from formatters.styles.base import BaseCitationStyle
from logger import get_logger


logger = get_logger(__name__)


class APABook(BaseCitationStyle):
"""
Форматирование для книг.
"""

data: BookModel

@property
def template(self) -> Template:
return Template(
"$authors ($year). $title. $publishing_house."
)

def substitute(self) -> str:

logger.info('Форматирование книги "%s" ...', self.data.title)

return self.template.substitute(
authors=self.data.authors,
title=self.data.title,
publishing_house=self.data.publishing_house,
year=self.data.year,
)

def get_edition(self) -> str:
"""
Получение отформатированной информации об издательстве.

:return: Информация об издательстве.
"""

return f"{self.data.edition} изд. – " if self.data.edition else ""


class APAInternetResource(BaseCitationStyle):
"""
Форматирование для интернет-ресурсов.
"""

data: InternetResourceModel

@property
def template(self) -> Template:
return Template(
"$article (n.d.) $website $link"
)

def substitute(self) -> str:

logger.info('Форматирование интернет-ресурса "%s" ...', self.data.article)

return self.template.substitute(
article=self.data.article,
website=self.data.website,
link=self.data.link,
)


class APACollectionArticle(BaseCitationStyle):
"""
Форматирование для статьи из сборника.
"""

data: ArticlesCollectionModel

@property
def template(self) -> Template:
return Template(
"$authors ($year). $article_title. $collection_title, $pages."
)

def substitute(self) -> str:

logger.info('Форматирование сборника статей "%s" ...', self.data.article_title)

return self.template.substitute(
authors=self.data.authors,
article_title=self.data.article_title,
collection_title=self.data.collection_title,
city=self.data.city,
publishing_house=self.data.publishing_house,
year=self.data.year,
pages=self.data.pages,
)
class APAJournalArticle(BaseCitationStyle):
"""
Форматирование для статьи из журнала.
"""

data: JournalArticleModel

@property
def template(self) -> Template:
return Template(
"$authors ($year). $article_title. $journal_title, $journal_number, $pages."
)

def substitute(self) -> str:

logger.info('Форматирование статей из журнала "%s" ...', self.data.article_title)

return self.template.substitute(
authors=self.data.authors,
article_title=self.data.article_title,
journal_title=self.data.journal_title,
year=self.data.year,
journal_number = self.data.journal_number,
pages=self.data.pages,
)
class APADissertation(BaseCitationStyle):
"""
Форматирование для статьи из сборника.
"""

data: DissertationModel

@property
def template(self) -> Template:
return Template(
"$authors ($year). $desertation_title [$canddoc диссиртация]"
)

def substitute(self) -> str:

logger.info('Форматирование диссертации "%s" ...', self.data.desertation_title)

return self.template.substitute(
authors=self.data.authors,
desertation_title=self.data.desertation_title,
canddoc=self.data.canddoc,
sience=self.data.sience,
code=self.data.code,
city=self.data.city,
year=self.data.year,
pages=self.data.pages,
)
class APACitationFormatter:
"""
Базовый класс для итогового форматирования списка источников.
"""

formatters_map = {
BookModel.__name__: APABook,
InternetResourceModel.__name__: APAInternetResource,
ArticlesCollectionModel.__name__: APACollectionArticle,
DissertationModel.__name__: APADissertation,
JournalArticleModel.__name__: APAJournalArticle,
}

def __init__(self, models: list[BaseModel]) -> None:
"""
Конструктор.

:param models: Список объектов для форматирования
"""

formatted_items = []
for model in models:
formatted_items.append(self.formatters_map.get(type(model).__name__)(model)) # type: ignore

self.formatted_items = formatted_items

def format(self) -> list[BaseCitationStyle]:
"""
Форматирование списка источников.

:return:
"""

return sorted(self.formatted_items, key=lambda item: item.formatted)
54 changes: 53 additions & 1 deletion src/formatters/styles/gost.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from pydantic import BaseModel

from formatters.models import BookModel, InternetResourceModel, ArticlesCollectionModel
from formatters.models import BookModel, InternetResourceModel, ArticlesCollectionModel, JournalArticleModel, DissertationModel
from formatters.styles.base import BaseCitationStyle
from logger import get_logger

Expand Down Expand Up @@ -101,8 +101,58 @@ def substitute(self) -> str:
year=self.data.year,
pages=self.data.pages,
)
class GOSTJournalArticle(BaseCitationStyle):
"""
Форматирование для статьи из журнала.
"""

data: JournalArticleModel

@property
def template(self) -> Template:
return Template(
"$authors $article_title // $journal_title – $year. - №$journal_number, $pages."
)

def substitute(self) -> str:

logger.info('Форматирование статей из журнала "%s" ...', self.data.article_title)

return self.template.substitute(
authors=self.data.authors,
article_title=self.data.article_title,
journal_title=self.data.journal_title,
year=self.data.year,
journal_number = self.data.journal_number,
pages=self.data.pages,
)
class GOSTDissertation(BaseCitationStyle):
"""
Форматирование для статьи из сборника.
"""

data: DissertationModel

@property
def template(self) -> Template:
return Template(
"$authors, $desertation_title [Текст]: дис. ... $canddoc $sience наук: $code / $authors - $city, $year. - $pages с."
)

def substitute(self) -> str:

logger.info('Форматирование диссертации "%s" ...', self.data.desertation_title)

return self.template.substitute(
authors=self.data.authors,
desertation_title=self.data.desertation_title,
canddoc=self.data.canddoc,
sience=self.data.sience,
code=self.data.code,
city=self.data.city,
year=self.data.year,
pages=self.data.pages,
)
class GOSTCitationFormatter:
"""
Базовый класс для итогового форматирования списка источников.
Expand All @@ -112,6 +162,8 @@ class GOSTCitationFormatter:
BookModel.__name__: GOSTBook,
InternetResourceModel.__name__: GOSTInternetResource,
ArticlesCollectionModel.__name__: GOSTCollectionArticle,
DissertationModel.__name__: GOSTDissertation,
JournalArticleModel.__name__: GOSTJournalArticle,
}

def __init__(self, models: list[BaseModel]) -> None:
Expand Down
25 changes: 17 additions & 8 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from readers.reader import SourcesReader
from renderer import Renderer
from settings import INPUT_FILE_PATH, OUTPUT_FILE_PATH
from formatters.styles.apa import APACitationFormatter

logger = get_logger(__name__)

Expand Down Expand Up @@ -75,16 +76,24 @@ def process_input(
path_input,
path_output,
)

models = SourcesReader(path_input).read()
formatted_models = tuple(
str(item) for item in GOSTCitationFormatter(models).format()
)

logger.info("Генерация выходного файла ...")
Renderer(formatted_models).render(path_output)
match citation:
case CitationEnum.GOST.name:
formatted_models = tuple(
str(item) for item in GOSTCitationFormatter(models).format()
)
logger.info("Генерация выходного файла GOST ...")
Renderer(formatted_models).render(path_output)
logger.info("Команда успешно завершена.")
case CitationEnum.APA.name:
formatted_models = tuple(
str(item) for item in APACitationFormatter(models).format()
)
Renderer(formatted_models).render(path_output)
logger.info("Генерация выходного файла APA ...")
Renderer(formatted_models).render(path_output)
logger.info("Команда успешно завершена.")

logger.info("Команда успешно завершена.")


if __name__ == "__main__":
Expand Down
Loading