lipasr.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. ###############################################################################
  2. # Copyright (C) 2024 LiveTalking@lipku https://github.com/lipku/LiveTalking
  3. # email: lipku@foxmail.com
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. ###############################################################################
  17. import time
  18. import torch
  19. import numpy as np
  20. import queue
  21. from queue import Queue
  22. #import multiprocessing as mp
  23. from baseasr import BaseASR
  24. from wav2lip import audio
  25. class LipASR(BaseASR):
  26. def run_step(self):
  27. ############################################## extract audio feature ##############################################
  28. # get a frame of audio
  29. for _ in range(self.batch_size*2):
  30. frame,type,eventpoint = self.get_audio_frame()
  31. self.frames.append(frame)
  32. # put to output
  33. self.output_queue.put((frame,type,eventpoint))
  34. # context not enough, do not run network.
  35. if len(self.frames) <= self.stride_left_size + self.stride_right_size:
  36. return
  37. inputs = np.concatenate(self.frames) # [N * chunk]
  38. mel = audio.melspectrogram(inputs)
  39. #print(mel.shape[0],mel.shape,len(mel[0]),len(self.frames))
  40. # cut off stride
  41. left = max(0, self.stride_left_size*80/50)
  42. right = min(len(mel[0]), len(mel[0]) - self.stride_right_size*80/50)
  43. mel_idx_multiplier = 80.*2/self.fps
  44. mel_step_size = 16
  45. i = 0
  46. mel_chunks = []
  47. while i < (len(self.frames)-self.stride_left_size-self.stride_right_size)/2:
  48. start_idx = int(left + i * mel_idx_multiplier)
  49. #print(start_idx)
  50. if start_idx + mel_step_size > len(mel[0]):
  51. mel_chunks.append(mel[:, len(mel[0]) - mel_step_size:])
  52. else:
  53. mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size])
  54. i += 1
  55. self.feat_queue.put(mel_chunks)
  56. # discard the old part to save memory
  57. self.frames = self.frames[-(self.stride_left_size + self.stride_right_size):]