import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import requests
import parselmouth
import tempfile
sns.set() # Use seaborn's default style to make attractive graphs
plt.rcParams['figure.dpi'] = 300 # Show nicely large images in this notebook
def load_from_teanglann(word, dialect):
    valid_dialects = ['C', 'M', 'U']
    if dialect not in valid_dialects and dialect.upper()[0] not in valid_dialects:
        raise Exception(f'Dialect must be one of "C", "M" or "U"; got "{dialect}"')
    url = f'https://www.teanglann.ie/Can{dialect}/{word}.mp3'
    r = requests.get(url)
    if r.status_code != 200:
        raise Exception(f'Failed to fetch {url}')
    file = tempfile.NamedTemporaryFile(mode='w+b')
    file.write(r.content)
    return file
def draw_spectrogram(spectrogram, dynamic_range=70):
    X, Y = spectrogram.x_grid(), spectrogram.y_grid()
    sg_db = 10 * np.log10(spectrogram.values)
    plt.pcolormesh(X, Y, sg_db, vmin=sg_db.max() - dynamic_range, cmap='afmhot')
    plt.ylim([spectrogram.ymin, spectrogram.ymax])
    plt.xlabel("time [s]")
    plt.ylabel("frequency [Hz]")

def draw_intensity(intensity):
    plt.plot(intensity.xs(), intensity.values.T, linewidth=3, color='w')
    plt.plot(intensity.xs(), intensity.values.T, linewidth=1)
    plt.grid(False)
    plt.ylim(0)
    plt.ylabel("intensity [dB]")
file=load_from_teanglann('athdhreas', 'U')
snd = parselmouth.Sound(file_path=file.name)

intensity = snd.to_intensity()
spectrogram = snd.to_spectrogram()
plt.figure()
draw_spectrogram(spectrogram)
plt.twinx()
#draw_intensity(intensity)
plt.xlim([snd.xmin, snd.xmax])
plt.show()
def draw_pitch(pitch):
    # Extract selected pitch contour, and
    # replace unvoiced samples by NaN to not plot
    pitch_values = pitch.selected_array['frequency']
    pitch_values[pitch_values==0] = np.nan
    plt.plot(pitch.xs(), pitch_values, 'o', markersize=5, color='w')
    plt.plot(pitch.xs(), pitch_values, 'o', markersize=2)
    plt.grid(False)
    plt.ylim(0, pitch.ceiling)
    plt.ylabel("fundamental frequency [Hz]")

pitch = snd.to_pitch()
# If desired, pre-emphasize the sound fragment before calculating the spectrogram
pre_emphasized_snd = snd.copy()
pre_emphasized_snd.pre_emphasize()
spectrogram = pre_emphasized_snd.to_spectrogram(window_length=0.03, maximum_frequency=8000)
plt.figure()
draw_spectrogram(spectrogram)
plt.twinx()
#draw_pitch(pitch)
plt.xlim([snd.xmin, snd.xmax])
plt.show()