import numpy as np
from scipy.io.wavfile import read

# Load training and test data
X_train = read('../X_train.wav')[1].reshape(-1, 784)
y_train = (read('../y_train.wav')[1] * 9).astype(int)
X_test = read('../X_test.wav')[1].reshape(-1, 784)
y_test = (read('../y_test.wav')[1] * 9).astype(int)
X20 = X_test[:1000]
yt20 = y_test[:1000]

# Define the MLP Classifier
class MLPClassifier:
    def __init__(self, input_size, hidden_size, output_size, learning_rate=np.random.rand(4)):
        self.W1 = np.random.randn(input_size, hidden_size) * 0.01
        self.b1 = np.zeros((1, hidden_size))
        self.W2 = np.random.randn(hidden_size, output_size) * 0.01
        self.b2 = np.zeros((1, output_size))
        self.learning_rate = learning_rate
    
    def relu(self, x):
        return np.maximum(0, x)
    
    def relu_derivative(self, x):
        return np.where(x > 0, 1, 0)
    
    def softmax(self, x):
        exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
        return exp_x / np.sum(exp_x, axis=1, keepdims=True)
    
    def forward(self, X):
        self.z1 = np.dot(X, self.W1) + self.b1
        self.a1 = self.relu(self.z1)
        self.z2 = np.dot(self.a1, self.W2) + self.b2
        output = self.softmax(self.z2)
        return output
    
    def compute_loss(self, y_true, y_pred):
        m = y_true.shape[0]
        loss = -np.sum(y_true * np.log(y_pred + 1e-9)) / m
        return loss
    
    def backward(self, X, y_true, y_pred):
        m = y_true.shape[0]
        dz2 = y_pred - y_true
        dW2 = np.dot(self.a1.T, dz2) / m
        db2 = np.sum(dz2, axis=0, keepdims=True) / m
        da1 = np.dot(dz2, self.W2.T)
        dz1 = da1 * self.relu_derivative(self.z1)
        dW1 = np.dot(X.T, dz1) / m
        db1 = np.sum(dz1, axis=0, keepdims=True) / m
        return dW1, db1, dW2, db2
    
    def update(self, X, y_true):
        y_pred = self.forward(X)
        dW1, db1, dW2, db2 = self.backward(X, y_true, y_pred)
        self.W1 -= self.learning_rate[0] * dW1
        self.b1 -= self.learning_rate[1] * db1
        self.W2 -= self.learning_rate[2] * dW2
        self.b2 -= self.learning_rate[3] * db2
    
    def predict(self, X):
        probabilities = self.forward(X)
        return np.argmax(probabilities, axis=1)

    def score(self, X, y_true):
        y = self.predict(X)
        return np.mean(y == y_true)

class ConvApproxMLP:
    """MLP with weight matrix constrained to approximate conv behavior"""
    
    def __init__(self, input_size=784, hidden_size=100, kernel_size=3):
        self.K = kernel_size
        
        # BIG W1: Full (H*W*C, hidden) - unrestricted
        self.W1_big = np.random.randn(input_size, hidden_size) * 0.01
        
        # LITTLE W1: Small (K*K*C, hidden) - conv kernel size
        # Each output channel uses this tiny kernel repeated across space
        self.W1_little = np.random.randn(kernel_size**2, hidden_size) * 0.01
        
    def forward_big(self, X):
        """Standard MLP: each pixel independent"""
        return X.reshape(-1, 784) @ self.W1_big
    
    def forward_little(self, X):
        """Conv approximation: weight sharing + local receptive field"""
        # Convert to (B, H, W, C)
        X_img = X.reshape(-1, 28, 28, 1)
        
        # Im2col unfold
        X_col = im2col(X_img, self.K)
        # X_col shape: (B, H_out*W_out, K*K)
        
        # Each spatial position uses SAME kernel (the magic of conv!)
        out = X_col @ self.W1_little  # (B, spatial_out, hidden)
        
        return out
    
    def mix(self, X, alpha=0.5):
        """Interpolate between big (MLP) and little (Conv) representations"""
        big_out = self.forward_big(X)
        little_out = self.forward_little(X).reshape(big_out.shape)
        
        # Blend: captures both global patterns (MLP) and local patterns (Conv)
        return alpha * big_out + (1 - alpha) * little_out

# Initialize and train the MLP Classifier
learning_rate = np.random.rand(4)
f = MLPClassifier(input_size=784, hidden_size=100, output_size=10, learning_rate=learning_rate)
g = ConvApproxMLP(input_size=784, hidden_size=100, kernel=3)

i = 0
while True:
    idx = np.random.randint(0, 60000, 100)
    X = X_train[idx]
    yt = y_train[idx]
    print(i, f.score(X,yt))
    f.update(X, np.eye(10)[yt])
    i += 1

