Пример #1
0
def render_all():

    notes = set()
    static_pages = set()

    Path(output_directory).mkdir(parents=True, exist_ok=True)
    Path(image_directory).mkdir(parents=True, exist_ok=True)

    for file in os.listdir(input_directory):

        filename = os.fsdecode(file)
        clean_filename = os.path.splitext(filename)[0]
        file_path = f"{input_directory}{filename}"

        if filename.endswith(RENDERER_CONFIG["input_file_extensions"]):

            output_file = f"{output_directory}{clean_filename}.html"

            pypandoc.convert_file(
                file_path,
                "html5",
                outputfile=output_file,
                extra_args=(RENDERER_CONFIG["pandoc_extra_args"]))

            update_img_tags(output_file)
            add_toc(file_path, output_file)

            metadata = get_metadata(file_path)

            if "summary" not in metadata:

                metadata["summary"] = get_summary_from_html(output_file)

            if "static_url" in metadata:

                static_pages.add(Note(output_file, clean_filename, **metadata))

            else:

                notes.add(Note(output_file, clean_filename, **metadata))

        elif filename.endswith(RENDERER_CONFIG["image_file_extensions"]):

            try:
                os.symlink(file_path, f"{image_directory}/{filename}")

            # link already exists, so we can skip
            except FileExistsError:
                pass

    tag_set = get_tags(notes)

    published_notes = (note for note in notes
                       if note.publication_date is not None)

    published_notes = sorted(published_notes,
                             reverse=True,
                             key=lambda n: n.publication_date)

    return published_notes, tag_set, static_pages
Пример #2
0
    def __init__(self):
        self.notes = []

        inbox = Note()
        self.inbox = Inbox(inbox)

        taskl = Note()
        self.tasklist = TaskList(taskl)
Пример #3
0
def note_creator(arg: Union[str, int, PCls]) -> Note_:
    """  """
    if type(arg) is str:
        name, acc = n.name_acc(arg[:-1])
        octave = int(arg[-1:])  # 0 <= octave <= 9
        return Note(n.name_to_id[name] + nn.accidental_to_id[acc] +
                    octave * 12)
    elif type(arg) is int:
        return Note(arg)
    else:
        raise TypeError
Пример #4
0
def print_fitness_vals(fq_curr, fq_trgt, fitness):
    
    for f in range(len(fq_trgt)):
        curr_trgt = Note(fq_trgt[f],1)
        curr_freq = Note(fq_curr[f][0],2)
        app.logger.critical(f"Midis | {round(curr_trgt.midi, 3)} - {round(curr_freq.midi, 3)} | = {round(abs(curr_trgt.midi - curr_freq.midi), 3)}")
    
    app.logger.critical(f"\n\nFitness: {fitness}\n")
    
    for f in range(len(fq_trgt)):
        curr_trgt = Note(fq_trgt[f],1)
        curr_freq = Note(fq_curr[f][0],2)
        app.logger.critical(f"Freqs | {round(curr_trgt.freq, 3)} - {round(curr_freq.freq, 3)} | = {round(abs(curr_trgt.freq - curr_freq.freq), 3)}")
    
    return
Пример #5
0
def fitness_from_sampled_freqs(fr, tr):

    ky_in_d = {}
    ch_v = np.ones((len(tr),1)) * (1.0 * 10)
    tr_as_m = []
    m_out = np.ones((len(tr),1)) * (1.0 * 10)
    s_ini = 0
    for t in tr:
        tr_as_m.append(Note(t,1).midi)

    for t in range(len(tr_as_m)):
        k = tr_as_m[t]
        s_mod, k_collect = sub_search(fr[s_ini:], k)
        s_ini += s_mod
        ky_in_d[k] = np.array(k_collect)
        temp = ky_in_d[k] - k
        if len(temp) > 0:
            ch_v[t] = (np.min(np.abs(temp)))
            if ch_v[t] in temp:
                m_out[t] = ch_v[t] + k
            else:
                m_out[t] = -1*ch_v[t] + k
        else:
            m_out[t] = -1

    assert len(ch_v) == len(tr)

    ch_v = np.transpose(ch_v)
    x = np.mean( (ch_v**2)/tr_as_m )
    x *= 100

    # return x, ch_v

    return x, m_out
Пример #6
0
    def __getitem__(self, uid: str) -> Note:
        if uid not in self.keys():
            raise KeyError

        return Note(
            EncryptedDocument(storage=self._storage,
                              uid=uid,
                              doc_key=self._doc_key))
def note_detection(image, templates):
    """
    It takes whole picture and detect each staff and all notes

    :param image: Image with music notation
    :param templates: Images with templates
    :return: List of objects of class Note
    """
    ind = 0
    notes = []
    repeat = False
    scale = 1

    for im in crop(image):
        extent = im.shape[1]/800.
        notes_aux = []
        coordinates = lines_detection(im, scale)
        imag = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        for temp in templates:
            if 'half' in temp:
                length = 1./2
            else:
                length = 1./4
            template = cv2.imread(temp, 0)
            w, h = template.shape[::-1]
            res = cv2.matchTemplate(imag, template, cv2.TM_CCOEFF_NORMED)
            threshold = 0.8
            loc = np.where(res >= threshold)
            loc = np.asarray(loc)
            c = list(zip(loc[1], loc[0]))
            c = sorted(c, key=lambda x: x[0])

            for pt in c:
                pitch = pitch_define(int(pt[1] + h/2), coordinates)
                note = Note(pitch_dict[pitch], ind, length, pt[0], pt[1])
                for n in notes_aux:
                    if abs(pt[0] - n.x) < 6*extent:
                        repeat = True
                        break
                if not repeat:
                    notes_aux.append(note)
                    ind += 1
                repeat = False

        notes_aux = sorted(notes_aux, key=lambda no: no.x)
        notes += notes_aux
        for pt in notes_aux:
            cv2.rectangle(im, (pt.x, pt.y), (pt.x + w, pt.y + h), (0, 0, 255), 1)
        plt.imshow(im)
        plt.show()

    return notes
Пример #8
0
    def create_note(self) -> Note:
        """
        Creates a new note with a random uid, inserts it into the index and returns it
        :return:
        """

        # Create new empty document at a new uid
        doc = EncryptedDocument(self._storage, self._storage.generate_uid())

        # Push note into index
        self._document[doc.uid] = None

        # Create a note instance to wrap the document, and return it
        return Note(doc, new=True)
Пример #9
0
def readSimpleNote(fname):
    n = Note()
    f = open(fname, "r")
    tmp = f.read()
    f.close()

    tmp = tmp.splitlines()
    n.setTitle(tmp[0])

    # collect body
    msg = ""
    for i in range(1, len(tmp)):
        msg += tmp[i] + "\n"

    n.setBody(msg)

    return n
Пример #10
0
def sub_search(fr_set, tr):

    note_tol = 12 # allowance of one octave
    # note_tol = 6 # allowance of half an octave

    f_pot = []
    ini_id = -1

    for i in range(len(fr_set)):
        m = Note(fr_set[i],1).midi

        if (-1*note_tol <= (m - tr) <= 0):
            f_pot.append(m)
        elif (0 < (m - tr) <= note_tol):
            if ini_id == -1:
                ini_id = i
            f_pot.append(m)
        elif ((m - tr) > note_tol):
            break

    # print("potential f: ")
    # print(f_pot)
    return (ini_id, f_pot)
Пример #11
0
    def render_in_png(self, rescale=1.0):
        def trans_paste(bg, fg, box=(0, 0)):
            if fg.mode == 'RGBA':
                if bg.mode != 'RGBA':
                    bg = bg.convert('RGBA')
                fg_trans = Image.new('RGBA', bg.size)
                fg_trans.paste(fg, box, mask=fg)  # transparent foreground
                return Image.alpha_composite(bg, fg_trans)
            else:
                if bg.mode == 'RGBA':
                    bg = bg.convert('RGB')
                bg.paste(fg, box)
                return bg

        harp_silent = self.get_is_silent()
        harp_broken = self.get_is_broken()

        harp_file = Image.open(self.unhighlighted_chord_png
                               )  # loads default harp image into memory
        harp_size = harp_file.size

        harp_render = Image.new('RGB', harp_file.size,
                                self.song_bkg)  # Empty image

        # Get a typical note to check that the size of the note png is consistent with the harp png
        note_size = Note(self).get_png_size()
        note_rel_width = note_size[0] / harp_size[0]  # percentage of harp
        if note_rel_width > 1.0 / self.get_column_count(
        ) or note_rel_width < 0.05:
            note_rescale = 0.153 / note_rel_width
        else:
            note_rescale = 1

        if harp_broken:  # '?' in the middle of the image (no harp around)
            symbol = Image.open(self.broken_png)
            harp_render = trans_paste(harp_render, symbol, (int(
                (harp_size[0] - symbol.size[0]) /
                2.0), int((harp_size[1] - symbol.size[1]) / 2.0)))
        elif harp_silent:  # '.' in the middle of the image (no harp around)
            symbol = Image.open(self.silent_png)
            harp_render = trans_paste(harp_render, symbol, (int(
                (harp_size[0] - symbol.size[0]) /
                2.0), int((harp_size[1] - symbol.size[1]) / 2.0)))
        else:
            harp_render = trans_paste(harp_render,
                                      harp_file)  # default harp image
            for row in range(self.get_row_count()):
                for col in range(self.get_column_count()):

                    note = self.get_note_from_position((row, col))
                    # note.set_position(row, col)

                    # NOTE RENDER
                    if len(note.get_highlighted_frames()
                           ) > 0:  # Only paste highlighted notes
                        xn = (0.13 + col * (1 - 2 * 0.13) /
                              (self.get_column_count() - 1)
                              ) * harp_size[0] - note_size[0] / 2.0
                        yn = (0.17 + row * (1 - 2 * 0.17) /
                              (self.get_row_count() - 1)
                              ) * harp_size[1] - note_size[1] / 2.0
                        note_render = note.render_in_png(note_rescale)
                        harp_render = trans_paste(
                            harp_render, note_render,
                            (int(round(xn)), int(round(yn))))

        if rescale != 1:
            harp_render = harp_render.resize(
                (int(harp_render.size[0] * rescale),
                 int(harp_render.size[1] * rescale)),
                resample=Image.LANCZOS)

        return harp_render
Пример #12
0
def process_message(msg, user):
    """
    Aqui ocorre o processamento de fato das mensagens. No momento em que
    o programa chega aqui, já é garantido que o user é o usuário atual.
    Checa-se se a mensagem é algum dos comandos; se não for, tenta
    parsear as notas. Se não forem notas, envia uma mensagem de erro ao
    usuário.
    """

    global current_user
    global user_timestamp
    text = msg['text']

    # Em primeiro lugar, atualizar a timestamp do usuário
    user_timestamp = msg['date']

    # Verificar se a mensagem é um dos comandos: end, notas, tempo ou musicas

    if NOTES_COMMAND_PATTERN.match(text):
        notes = get_available_notes()

        bot.sendMessage(user.id, 'As notas disponíveis são:')
        bot.sendMessage(user.id, '\n'.join(notes))
        bot.sendMessage(user.id, 'Podem ser escritas em maiúsculo ou minúsculo.')
        return

    elif END_COMMAND_PATTERN.match(text):
        bot.sendMessage(user.id, 'Sessão finalizada.')
        shift_users()
        return

    m = TEMPO_COMMAND_PATTERN.match(text)
    if m:
        tempo = int(m.group(1) or user.tempo)
        user.tempo = tempo
        bot.sendMessage(user.id, 'Tempo: %d' % user.tempo)
        return

    m = SONGS_COMMAND_PATTERN.match(text)
    if m:
        song = m.group(1)
        if song:
            song = int(song) - 1
            song = songs[song]

            bot.sendMessage(user.id, 'Ajustando tempo para %d...' % song.tempo,
                            reply_markup={'hide_keyboard': True})
            user.tempo = song.tempo
            bot.sendMessage(user.id, song.name)
            bot.sendMessage(user.id, song.seq)

            text = song.seq

        else:
            song_list = list(enumerate(songs, 1))
            text = '\n'.join('%d. %s' % (i, s.name)
                             for i, s in song_list)
            kb_columns = 3
            kb_rows = math.ceil(len(songs) / kb_columns)
            bot.sendMessage(
                user.id, text, reply_markup={'keyboard':[
                    ['/musica %d' % i for i, _ in song_list
                     if math.ceil(i / kb_columns) == row]
                    for row in range(1, kb_rows+1)
                ], 'one_time_keyboard': True})

            return

    # Neste ponto, o usuário deve ter enviado notas de fato

    note_list = []
    for note in text.split():
        if not NOTE_PATTERN.match(note):
            bot.sendMessage(user.id, 'Nota inválida: ' + note)
            continue

        note, length = note.split(',')
        note_list.append(Note(note, int(length)))

    arduino_notes = ' '.join(n.to_arduino(user.tempo) for n in note_list) + ' \n'

    arduino.write(arduino_notes)
Пример #13
0
def readTodoFile(fname):

    nbtmp = NoteBook()
    nbtmp.setTitle("Updated TODO")
    nbtmp.tmpNoteFile = "notebook-tmp-C.md"

    f = open(fname, "r")
    tmp = f.read()
    f.close()

    # print("tmp file content--------------")
    tmp = tmp.splitlines()
    # print(tmp)

    # add trailing newlines for easier parsing
    # for i in range(len(tmp)):
    #    tmp[i] += "\n"

    # filter header out
    c = 0
    while True:
        if c >= len(tmp):
            break

        line = tmp[c]
        # print("skipping {}".format(line))

        mtitle = regexes.REtitle.match(line)
        if mtitle:
            break
        c += 1
    # print("skipping {}".format(c))

    ns = []
    hashes = []
    bodys = []

    body = ""
    while c < len(tmp):
        line = tmp[c]
        # print("{}".format( line ))

        mtitle = regexes.REtitle.match(line)
        mhash = regexes.REhash.match(line)
        mdate = regexes.REdate.match(line)
        mmdate = regexes.REmdate.match(line)
        mdiv = regexes.REdiv.match(line)

        if mtitle:
            n = Note()
            bodys.append(body)
            body = ""

            s = mtitle.group(1)
            s = s.replace("'",
                          "")  # strip ' from title (causes problems with rm)
            n.setTitle(s)
            ns.append(n)
            # ni += 1
        elif mdiv:
            # do nothing
            True
        elif mhash:
            s = mhash.group(1)
            hashes.append(s)
        elif mdate:
            n.setDate(mdate.group(1))
        elif mmdate:
            n.setDate(mmdate.group(1))
        else:
            body += line + "\n"
        c += 1
    bodys.append(body)  # append last hanging body

    # print("###########################################")
    for i, n in enumerate(ns):

        body = bodys[i + 1]
        # print("last char: vvv{}vvv".format(body[-2:]))

        # if (body[-2:] == "\n"):
        #    print("newline detected")
        #    body = body[:-2]

        # body = body[:-2] #strip trailing newline
        # body = body.rstrip()
        # body += "\n"
        # body += "\n"

        n.setBody(body)
        # print("{} -- {}".format(i, n.title))
        # print("{} hash is {}".format(i, n.hash() ))
        # print("----")
        # print("{}".format(n.body))
        # print("----")
        # print("{}".format(body))

        nbtmp.addNote(n)

    return nbtmp
Пример #14
0
 def new_note(self, memo, tags=''):
     n = Note(memo, tags)
     self.notes.append(n)
Пример #15
0
# -*- coding: utf-8 -*-

from notes import Note

CHROMATIC_SCALE_ASC = [
    Note('C'),
    Note('C', '#'),
    Note('D'),
    Note('D', '#'),
    Note('E'),
    Note('F'),
    Note('F', '#'),
    Note('G'),
    Note('G', '#'),
    Note('A'),
    Note('A', '#'),
    Note('B')
]

CHROMATIC_SCALE_DESC = [
    Note('B'),
    Note('B', 'b'),
    Note('A'),
    Note('A', 'b'),
    Note('G'),
    Note('G', 'b'),
    Note('F'),
    Note('E'),
    Note('E', 'b'),
    Note('D'),
    Note('D', 'b'),
Пример #16
0
def pitchclass_to_note(arg: PCls, octave: int = 4) -> Note_:
    arg = Note(arg.id + octave * 12)
    return arg
Пример #17
0
            msg = note.print(msg)

        msg = msg.rstrip()  # remove all trailing newlines

        msg += "\n"
        msg += "\n"

        f = open(self.tmpNoteFile, "w")
        f.write(msg)
        f.close()


# --------------------------------------------------
# Testing
if __name__ == "__main__":
    note1 = Note()
    note1.setTitle("note number 1")
    note1.setBody("Blaablaa, this is comment.")

    note2 = Note()
    note2.setTitle("note number 2")
    note2.setBody("blaablaa, this is another comment.")

    note3 = Note()
    note3.setTitle("Lenghty note")
    note3.setBody("This is a note with a very long text body.\n" +
                  "it continues all the way to here. and to \n" +
                  "here: Seems long, right?. Now it finally almost.\n" +
                  "here: Seems long, right?. xxx xxx xxx xxx xxx x.\n" +
                  "here: Seems long, right?. Now it finally ends.")
Пример #18
0
    def add_note(self):
        text = input("Enter the text of the note: ")
        tag = input("Enter the tag of the note: ")

        self.notebook.new_note(Note(text, tag))