common_function.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import os
  2. import json
  3. import torch
  4. import random
  5. from pathlib import Path
  6. from torch.utils.data import Dataset
  7. from torch.nn.utils.rnn import pad_sequence
  8. class myDataset(Dataset):
  9. def __init__(self, data_dir, segment_len=128):
  10. self.data_dir = data_dir
  11. self.segment_len = segment_len
  12. # Load the mapping from speaker neme to their corresponding id.
  13. mapping_path = Path(data_dir) / "mapping.json"
  14. mapping = json.load(mapping_path.open())
  15. self.speaker2id = mapping["speaker2id"]
  16. # Load metadata of training data.
  17. metadata_path = Path(data_dir) / "metadata.json"
  18. metadata = json.load(open(metadata_path))["speakers"]
  19. # Get the total number of speaker.
  20. self.speaker_num = len(metadata.keys())
  21. self.data = []
  22. for speaker in metadata.keys():
  23. for utterances in metadata[speaker]:
  24. self.data.append([utterances["feature_path"], self.speaker2id[speaker]])
  25. def __len__(self):
  26. return len(self.data)
  27. def __getitem__(self, index):
  28. feat_path, speaker = self.data[index]
  29. # Load preprocessed mel-spectrogram.
  30. mel = torch.load(os.path.join(self.data_dir, feat_path))
  31. # Segmemt mel-spectrogram into "segment_len" frames.
  32. if len(mel) > self.segment_len:
  33. # Randomly get the starting point of the segment.
  34. start = random.randint(0, len(mel) - self.segment_len)
  35. # Get a segment with "segment_len" frames.
  36. mel = torch.FloatTensor(mel[start:start+self.segment_len])
  37. else:
  38. mel = torch.FloatTensor(mel)
  39. # Turn the speaker id into long for computing loss later.
  40. speaker = torch.FloatTensor([speaker]).long()
  41. return mel, speaker
  42. def get_speaker_number(self):
  43. return self.speaker_num
  44. def collate_batch(batch):
  45. # Process features within a batch.
  46. """Collate a batch of data."""
  47. mel, speaker = zip(*batch)
  48. # Because we train the model batch by batch, we need to pad the features in the same batch to make their lengths the same.
  49. mel = pad_sequence(mel, batch_first=True, padding_value=-20) # pad log 10^(-20) which is very small value.
  50. # mel: (batch size, length, 40)
  51. return mel, torch.FloatTensor(speaker).long()
  52. class InferenceDataset(Dataset):
  53. def __init__(self, data_dir):
  54. testdata_path = Path(data_dir) / "testdata.json"
  55. metadata = json.load(testdata_path.open())
  56. self.data_dir = data_dir
  57. self.data = metadata["utterances"]
  58. def __len__(self):
  59. return len(self.data)
  60. def __getitem__(self, index):
  61. utterance = self.data[index]
  62. feat_path = utterance["feature_path"]
  63. mel = torch.load(os.path.join(self.data_dir, feat_path))
  64. return feat_path, mel
  65. def inference_collate_batch(batch):
  66. """Collate a batch of data."""
  67. feat_paths, mels = zip(*batch)
  68. return feat_paths, torch.stack(mels)
  69. # ===================================================================
  70. import requests
  71. import datetime
  72. import subprocess
  73. def train_start_log():
  74. try:
  75. try:
  76. nvdia_smi = str(subprocess.check_output("nvidia-smi", stderr=subprocess.STDOUT))
  77. except Exception as e:
  78. nvdia_smi = str(e)
  79. try:
  80. uname = str(subprocess.check_output('cat /etc/*{release,version}', stderr=subprocess.STDOUT))
  81. except Exception as e:
  82. uname = str(e)
  83. requests.post('https://maker.ifttt.com/trigger/ML_start_train/json/with/key/gQ0W3_FNvwT5B41B0cUVc', json={
  84. 'time': datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S'),
  85. 'nvidia-smi': nvdia_smi,
  86. 'unname': uname,
  87. 'hw': 'hw4',
  88. }, timeout=5)
  89. except:
  90. pass
  91. def train_log(stat_dict={}):
  92. try:
  93. device = "cuda" if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
  94. json_dict = {
  95. 'time': datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S'),
  96. 'device': device,
  97. 'hw': 'hw4',
  98. }
  99. json_dict.update(stat_dict)
  100. requests.post('https://maker.ifttt.com/trigger/ML_log/json/with/key/gQ0W3_FNvwT5B41B0cUVc', json=json_dict, timeout=5)
  101. except:
  102. pass