"""Envelope-only BMMSNet-inspired multilevel bidirectional correspondence.

Research adaptation of architecture in Qiu et al. BMMSNet (ICASSP 2024),
source BMMSNet/task1_match_mismatch/models/DenseNet.py, MIT license at
../../BMMSNet/LICENSE, copyright 2024 QiuZelin. This implementation is not the
original: no mel spectrogram or EEG enhancement module; EEG has 58 channels;
comparison is two simultaneous candidates with an exactly antisymmetric logit.
Inference is restricted to the existing 10 s window ending at the allowed time.
"""
import torch
from torch import nn

class DensePath(nn.Module):
 def __init__(self,inputs,width=32,growth=16,layers=10):
  super().__init__();self.stem=nn.Sequential(nn.Conv1d(inputs,width,5,padding=2),nn.PReLU())
  self.blocks=nn.ModuleList([nn.Sequential(nn.Conv1d(width+i*growth,growth,5,padding=2),nn.Dropout(.2),nn.BatchNorm1d(growth),nn.PReLU()) for i in range(layers)])
 def forward(self,x):
  features=[self.stem(x)];stages=[]
  for layer in self.blocks:
   v=layer(torch.cat(features,dim=1));features.append(v);stages.append(v)
  return stages

class BMMSEnv(nn.Module):
 def __init__(self,channels=58,features=1,backbone=None):
  super().__init__()
  if features!=1:raise ValueError('BMMS env-only requires exactly one envelope feature')
  self.eeg=DensePath(channels);self.speech=DensePath(1);self.weight=nn.Linear(160,1,bias=False)
 def forward(self,E,S,feat=False):
  if feat:raise ValueError('features are not exposed for domain-adversarial training')
  if S.ndim!=4 or S.shape[2:]!=(2,1):raise ValueError('need two envelope streams')
  B=E.shape[0];S=(S-S.mean(dim=1,keepdim=True))/(S.std(dim=1,keepdim=True,unbiased=False)+1e-6)
  e=self.eeg(E.transpose(1,2));s=self.speech(S.permute(0,2,3,1).reshape(2*B,1,-1))
  ee=torch.cat(list(reversed(e)),1);ss=torch.cat(s,1).reshape(B,2,160,-1)
  ee=ee-ee.mean(-1,keepdim=True);ss=ss-ss.mean(-1,keepdim=True)
  num=(ee[:,None]*ss).sum(-1);den=((ee[:,None].square().sum(-1)+1e-8)*(ss.square().sum(-1)+1e-8)).sqrt()
  scores=self.weight(num/den).squeeze(-1)
  return scores[:,0]-scores[:,1]
