import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import hilbert

# 1. Load the file
rate, data = wavfile.read("challenge/evidence_4b.wav")

# 2. Extract Signal (Hilbert Transform) (We need the instantaneous frequency (pitch) of each channel.)
analytic_x = hilbert(data[:, 0])
analytic_y = hilbert(data[:, 1])

# Calculate Frequency: Frequency is the rate of change of the phase
freq_x = np.diff(np.unwrap(np.angle(analytic_x)))
freq_y = np.diff(np.unwrap(np.angle(analytic_y)))

# 3. Filter Silence (Simple "Pen Up" check) (Only draw when the volume is loud enough)
amplitude = np.abs(analytic_x[1:])  # Match length with freq array (which is 1 shorter)
mask = amplitude > (np.max(amplitude) * 0.1)

# 4. Plot (We plot Frequency X vs Frequency Y)
plt.figure(figsize=(10, 10))
plt.scatter(freq_x[mask], freq_y[mask], s=0.1, c='green')
plt.axis('equal') # Prevent squashing
plt.show()
