Skip to content

Instantly share code, notes, and snippets.

@aflaag
Last active November 20, 2021 19:58
Show Gist options
  • Save aflaag/52ebbb2b5ad9cfa16f928227360bab37 to your computer and use it in GitHub Desktop.
Save aflaag/52ebbb2b5ad9cfa16f928227360bab37 to your computer and use it in GitHub Desktop.
import math
import pronouncing
def evaluate_partial_precedence(A, B, tau, mA, mB):
c = i = j = 0
while i < mA and j < mB:
curr_A = A[i]
curr_B = B[j]
if curr_A < curr_B:
i += 1
else:
if curr_A - curr_B <= tau:
c += 1
i += 1
else:
j += 1
return c
def stresses(phonetic, possible_accents, one, zero, word):
stresses = ""
phonetic_first = phonetic[0] if len(phonetic) else len(word) // 2 * zero
for c in phonetic_first:
if c in possible_accents:
stresses += c if c == one else zero
return stresses
def evaluate_unpadded_matrix(filtered_lines):
matrix = []
lists = []
one = "1"
zero = "0"
possible_accents = "012"
for line in filtered_lines:
new_line = []
for word in line.split():
phonetic = pronouncing.phones_for_word(word)
new_line.extend(stresses(phonetic, possible_accents, one, zero, word) + zero)
new_line_list = [i for i, v in enumerate(new_line) if v == one]
lists.append(new_line_list)
matrix.append(new_line)
return matrix, lists
def evaluate_sync_average(matrix, tau):
sync_values = 0
len_matrix = len(matrix)
ms = list(map(len, matrix))
for i in range(len_matrix - 1):
line1 = matrix[i]
mA = ms[i]
for j in range(i + 1, len_matrix):
mB = ms[j]
if mA and mB:
line2 = matrix[j]
c = evaluate_partial_precedence(line1, line2, tau, mA, mB)
c += evaluate_partial_precedence(line2, line1, tau, mB, mA)
sync_values += c / math.sqrt(mA * mB << 2)
return round(sync_values * 2 / (len_matrix * (len_matrix - 1)), 6)
def PoemSync(inputfilename, outputfilename, tau):
space = " "
newline = "\n"
matrix, lists = evaluate_unpadded_matrix(list(map(lambda line: "".join(map(lambda c: c if c.isalpha() else space, line)), [line for line in open(inputfilename, encoding="utf-8").readlines() if line != newline])))
longest = max(map(len, matrix))
zero = "0"
for line in matrix:
line.extend(zero * (longest - len(line)) + newline)
open(outputfilename, "w").writelines((map(lambda line: "".join(line), matrix)))
return evaluate_sync_average(lists, tau)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment