# Path: poetry/apps/corpus/models.py
# class Poem(Model):
#     text = TextField("Текст", blank=False)
#     name = CharField("Нвзвание стихотворения", max_length=50, blank=True)
#     author = CharField("Автор", max_length=50, blank=False)
#     date_from = IntegerField("Дата написания - первый год", blank=True, null=True)
#     date_to = IntegerField("Дата написания - второй год", blank=True, null=True)
#     themes = ManyToManyField(Theme, verbose_name="Темы", related_name="poems", blank=True)
#     is_restricted = BooleanField("Стихи с ограниченным доступом", default=False)
#     is_standard = BooleanField("Эталонные (проверенные) стихи", default=False)
# 
#     class Meta:
#         verbose_name = "Стихотворение"
#         verbose_name_plural = "Стихотворения"
#         permissions = (
#             ("can_view_restricted_poems", "Can view restricted poems"),
#         )
# 
#     def __str__(self):
#         return 'Стихотворение: ' + self.get_name() + ", " + str(self.author)
# 
#     def get_name(self):
#         name = self.name
#         if name == "":
#             name = self.text.strip().split("\n")[0]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#         return name
# 
#     def get_name_short(self):
#         name = self.__clean_name(self.name)
#         if name == "":
#             name = self.__get_name_form_text()
#         return name[:64].replace(" ", "")
# 
#     def __get_name_form_text(self):
#         name = ""
#         line_number = 0
#         while name == "":
#             name = self.text.strip().split("\n")[line_number]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#             name = self.__clean_name(name)
#             line_number += 1
#         return name
# 
#     def __clean_name(self, name):
#         new_name = ""
#         for ch in name:
#             if ch.isalpha() or ch.isalnum() or ch == " ":
#                 new_name += ch
#         return new_name.strip()
# 
#     def count_lines(self):
#         return len(self.text.rstrip().split("\n"))
# 
#     def count_automatic_errors(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup.get_automatic_additional().get_metre_errors_count()
# 
#     def get_absolute_url(self):
#         if len(self.markups.all()) != 0:
#             return self.markups.all()[0].get_absolute_url()
#         return reverse("corpus:poems")
# 
#     def get_automatic_markup(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup
#         return None
# 
#     def count_manual_markups(self):
#         return sum([int(markup.markup_version.name == "Manual") for markup in self.markups.all()])
# 
# class MarkupVersion(Model):
#     name = CharField("Имя версии разметки", max_length=50, blank=False)
#     additional = TextField("Дополнительная ифнормация", blank=True)
#     is_manual = BooleanField("Ручные разметки?", default=False)
# 
#     class Meta:
#         verbose_name = "Версия разметки"
#         verbose_name_plural = "Версии разметки"
# 
#     def __str__(self):
#         return str(self.name)
# 
#     def count_markups(self):
#         return self.markups.count()


from collections import namedtuple
from typing import List
from django.views.generic import TemplateView, View
from django.http import HttpResponse
from braces.views import LoginRequiredMixin, GroupRequiredMixin
from poetry.apps.corpus.models import Poem, MarkupVersion
from rupo.main.markup import Markup


def get_recall(standard_accents: List[bool], test_accents: List[bool]):
    tp = sum([1 for standard_accent, test_accent in zip(standard_accents, test_accents)
              if standard_accent == test_accent == 1])
    tp_fn = sum([1 for accent in standard_accents if accent == 1])
    return float(tp) / tp_fn


def get_comparison(poem, standard_pk, test_pk):
    test_markup = None
    standard_markup = None
    for markup in poem.markups.all():
        if markup.markup_version.pk == standard_pk:
            standard_markup = markup
        if markup.markup_version.pk == test_pk:
            test_markup = markup
    assert test_markup.get_markup().text == standard_markup.get_markup().text
    standard_accents = get_accents(standard_markup.get_markup())
    test_accents = get_accents(test_markup.get_markup())
    accuracy = get_accuracy(standard_accents, test_accents)
    precision = get_precision(standard_accents, test_accents)
    recall = get_recall(standard_accents, test_accents)
    f1 = 2*precision*recall/(precision+recall)
    Comparison = namedtuple("Comparison", "poem test standard accuracy precision recall f1")
    return Comparison(poem=poem, test=test_markup, standard=standard_markup, accuracy=accuracy,
                      precision=precision, recall=recall, f1=f1)


def get_all_comparisons(standard_pk, test_pk):

# Path: poetry/apps/corpus/models.py
# class Poem(Model):
#     text = TextField("Текст", blank=False)
#     name = CharField("Нвзвание стихотворения", max_length=50, blank=True)
#     author = CharField("Автор", max_length=50, blank=False)
#     date_from = IntegerField("Дата написания - первый год", blank=True, null=True)
#     date_to = IntegerField("Дата написания - второй год", blank=True, null=True)
#     themes = ManyToManyField(Theme, verbose_name="Темы", related_name="poems", blank=True)
#     is_restricted = BooleanField("Стихи с ограниченным доступом", default=False)
#     is_standard = BooleanField("Эталонные (проверенные) стихи", default=False)
# 
#     class Meta:
#         verbose_name = "Стихотворение"
#         verbose_name_plural = "Стихотворения"
#         permissions = (
#             ("can_view_restricted_poems", "Can view restricted poems"),
#         )
# 
#     def __str__(self):
#         return 'Стихотворение: ' + self.get_name() + ", " + str(self.author)
# 
#     def get_name(self):
#         name = self.name
#         if name == "":
#             name = self.text.strip().split("\n")[0]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#         return name
# 
#     def get_name_short(self):
#         name = self.__clean_name(self.name)
#         if name == "":
#             name = self.__get_name_form_text()
#         return name[:64].replace(" ", "")
# 
#     def __get_name_form_text(self):
#         name = ""
#         line_number = 0
#         while name == "":
#             name = self.text.strip().split("\n")[line_number]
#             i = len(name) - 1
#             while i > 0 and not name[i].isalpha():
#                 i -= 1
#             name = name[:i+1]
#             name = self.__clean_name(name)
#             line_number += 1
#         return name
# 
#     def __clean_name(self, name):
#         new_name = ""
#         for ch in name:
#             if ch.isalpha() or ch.isalnum() or ch == " ":
#                 new_name += ch
#         return new_name.strip()
# 
#     def count_lines(self):
#         return len(self.text.rstrip().split("\n"))
# 
#     def count_automatic_errors(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup.get_automatic_additional().get_metre_errors_count()
# 
#     def get_absolute_url(self):
#         if len(self.markups.all()) != 0:
#             return self.markups.all()[0].get_absolute_url()
#         return reverse("corpus:poems")
# 
#     def get_automatic_markup(self):
#         for markup in self.markups.all():
#             if "Automatic" in markup.author:
#                 return markup
#         return None
# 
#     def count_manual_markups(self):
#         return sum([int(markup.markup_version.name == "Manual") for markup in self.markups.all()])
# 
# class MarkupVersion(Model):
#     name = CharField("Имя версии разметки", max_length=50, blank=False)
#     additional = TextField("Дополнительная ифнормация", blank=True)
#     is_manual = BooleanField("Ручные разметки?", default=False)
# 
#     class Meta:
#         verbose_name = "Версия разметки"
#         verbose_name_plural = "Версии разметки"
# 
#     def __str__(self):
#         return str(self.name)
# 
#     def count_markups(self):
#         return self.markups.count()


# Path: poetry/apps/corpus/views/comparison_view.py
from collections import namedtuple
from typing import List
from django.views.generic import TemplateView, View
from django.http import HttpResponse
from braces.views import LoginRequiredMixin, GroupRequiredMixin
from poetry.apps.corpus.models import Poem, MarkupVersion
from rupo.main.markup import Markup



def get_recall(standard_accents: List[bool], test_accents: List[bool]):
    tp = sum([1 for standard_accent, test_accent in zip(standard_accents, test_accents)
              if standard_accent == test_accent == 1])
    tp_fn = sum([1 for accent in standard_accents if accent == 1])
    return float(tp) / tp_fn


def get_comparison(poem, standard_pk, test_pk):
    test_markup = None
    standard_markup = None
    for markup in poem.markups.all():
        if markup.markup_version.pk == standard_pk:
            standard_markup = markup
        if markup.markup_version.pk == test_pk:
            test_markup = markup
    assert test_markup.get_markup().text == standard_markup.get_markup().text
    standard_accents = get_accents(standard_markup.get_markup())
    test_accents = get_accents(test_markup.get_markup())
    accuracy = get_accuracy(standard_accents, test_accents)
    precision = get_precision(standard_accents, test_accents)
    recall = get_recall(standard_accents, test_accents)
    f1 = 2*precision*recall/(precision+recall)
    Comparison = namedtuple("Comparison", "poem test standard accuracy precision recall f1")
    return Comparison(poem=poem, test=test_markup, standard=standard_markup, accuracy=accuracy,
                      precision=precision, recall=recall, f1=f1)


def get_all_comparisons(standard_pk, test_pk):

    standard_markup_version = MarkupVersion.objects.get(pk=standard_pk)