Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/audio input (rebased) #140

Merged
merged 20 commits into from
Apr 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
4a65d0b
feat: start implementing initial dumb audio parsing
sbaier1 Mar 23, 2022
68545fc
feat: initial rough audio parsing logic
sbaier1 Mar 24, 2022
ee20b1e
fix: some math edge cases
sbaier1 Mar 25, 2022
8a1ff32
fix: add debug log for audio 0 vectors
sbaier1 Mar 25, 2022
2c5c7c2
fix: add missing warmup config params
sbaier1 Mar 25, 2022
affdaaa
fix: run fft analysis only when images are actually saved
sbaier1 Mar 26, 2022
3eea431
fix: try adding some rudimentary error handling
sbaier1 Mar 26, 2022
97aaa06
fix: add sample count to log statement as well
sbaier1 Mar 26, 2022
d0edc43
fix: more warning logs for debugging
sbaier1 Mar 26, 2022
5bc02f4
feat: start implementing bandpass filters instead of fft+ frequency s…
sbaier1 Apr 1, 2022
c232386
feat: completely refactor fft / window_size /band-splitting based imp…
sbaier1 Apr 3, 2022
21e5b3f
refactor: remove window size config param, fix eval tooling for dict …
sbaier1 Apr 3, 2022
139eaaa
style: cleanup, remove useless todos, formatting
sbaier1 Apr 8, 2022
52c58b1
fix: use correct parameter naming, properly print bands
sbaier1 Apr 8, 2022
1688ab4
fix: param must be dict instead of tuple now
sbaier1 Apr 18, 2022
548edba
fixed dangling merge conflict
dmarx Apr 20, 2022
ba63ea9
audio filter config needs to be optional.
dmarx Apr 20, 2022
7f59f1e
typing.Optional for backwards compatibility
dmarx Apr 20, 2022
92c5f4a
sadly, optional doesn't permit absent...
dmarx Apr 20, 2022
80faea2
fixed minor integration errors
dmarx Apr 20, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions src/pytti/AudioParse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import numpy as np
import typing
import subprocess
from loguru import logger
from scipy.signal import butter, sosfilt, sosfreqz

SAMPLERATE = 44100


class SpectralAudioParser:
"""
reads a given input file, scans along it and parses the amplitude in selected bands using butterworth bandpass filters.
the amplitude is normalized into the 0..1 range for easier use in transformation functions.
"""

def __init__(
self,
input_audio,
offset,
frames_per_second,
filters
):
if len(filters) < 1:
raise RuntimeError("When using input_audio, at least 1 filter must be specified")

pipe = subprocess.Popen(['ffmpeg', '-i', input_audio,
'-f', 's16le',
'-acodec', 'pcm_s16le',
'-ar', str(SAMPLERATE),
'-ac', '1',
'-'], stdout=subprocess.PIPE, bufsize=10 ** 8)

self.audio_samples = np.array([], dtype=np.int16)

# read the audio file from the pipe in 0.5s blocks (2 bytes per sample)
while True:
buf = pipe.stdout.read(SAMPLERATE)
self.audio_samples = np.append(self.audio_samples, np.frombuffer(buf, dtype=np.int16))
if len(buf) < SAMPLERATE:
break
if len(self.audio_samples) < 0:
raise RuntimeError("Audio samples are empty, assuming load failed")
self.duration = len(self.audio_samples) / SAMPLERATE
logger.debug(
f"initialized audio file {input_audio}, samples read: {len(self.audio_samples)}, total duration: {self.duration}s")
self.offset = offset
if offset > self.duration:
raise RuntimeError(f"Audio offset set at {offset}s but input audio is only {duration}s long")
# analyze all samples for the current frame
self.window_size = int(1 / frames_per_second * SAMPLERATE)
self.filters = filters

# parse band maxima first for normalizing the filtered signal to 0..1 at arbitrary points in the file later
# this initialization is a bit compute intensive, especially for higher fps numbers, but i couldn't find a cleaner way
# (band-passing the entire track instead of windows creates maxima that are way off, some filtering anomaly i don't understand...)
steps = int((self.duration - self.offset) * frames_per_second)
interval = 1 / frames_per_second
maxima = {}
time_steps = np.linspace(0, steps, num=steps) * interval
for t in time_steps:
sample_offset = int(t * SAMPLERATE)
cur_maxima = bp_filtered(self.audio_samples[sample_offset:sample_offset + self.window_size], filters)
for key in cur_maxima:
if key in maxima:
maxima[key] = max(maxima[key], cur_maxima[key])
else:
maxima[key] = cur_maxima[key]
self.band_maxima = maxima
logger.debug(f"initialized band maxima for {len(filters)} filters: {self.band_maxima}")

def get_params(self, t) -> typing.Dict[str, float]:
"""
Return the amplitude parameters at the given point in time t within the audio track, or 0 if the track has ended.
Amplitude/energy parameters are normalized into the [0,1] range.
"""
# Get the point in time (sample-offset) in the track in seconds based on sample-rate
sample_offset = int(t * SAMPLERATE + self.offset * SAMPLERATE)
logger.debug(f"Analyzing audio at {self.offset + t}s")
if sample_offset < len(self.audio_samples):
window_samples = self.audio_samples[sample_offset:sample_offset + self.window_size]
if len(window_samples) < self.window_size:
# audio input file has likely ended
logger.debug(
f"Warning: sample offset is out of range at time offset {t + self.offset}s. Returning null result")
return {}
return bp_filtered_norm(window_samples, self.filters, self.band_maxima)
else:
logger.debug(f"Warning: Audio input has ended. Returning null result")
return {}

def get_duration(self):
return self.duration


def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='bandpass', output='sos')
return sos


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y


def bp_filtered(window_samples, filters) -> typing.Dict[str, float]:
results = {}
for filter in filters:
offset = filter.f_width / 2
lower = filter.f_center - offset
upper = filter.f_center + offset
filtered = butter_bandpass_filter(window_samples, lower, upper, SAMPLERATE, order=filter.order)
results[filter.variable_name] = np.max(np.abs(filtered))
return results


def bp_filtered_norm(window_samples, filters, norm_factors) -> typing.Dict[str, float]:
results = bp_filtered(window_samples, filters)
for key in results:
# normalize
results[key] = results[key] / norm_factors[key]
return results
13 changes: 13 additions & 0 deletions src/pytti/ImageGuide.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
freeze_vram_usage,
vram_usage_mode,
)
from pytti.AudioParse import SpectralAudioParser
from pytti.Image.differentiable_image import DifferentiableImage
from pytti.Image.PixelImage import PixelImage
from pytti.Notebook import tqdm, make_hbox
Expand Down Expand Up @@ -108,6 +109,18 @@ def __init__(
self.optimizer = optimizer
self.dataframe = []

self.audio_parser = None
if params is not None:
if params.input_audio and params.input_audio_filters:
self.audio_parser = SpectralAudioParser(
params.input_audio,
params.input_audio_offset,
params.frames_per_second,
params.input_audio_filters,
)
# else:
# self.audio_parser = None

# self.null_update = null_update
self.params = params
self.writer = writer
Expand Down
7 changes: 7 additions & 0 deletions src/pytti/assets/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ far_plane: 10000
######################
### Induced Motion ###
######################
input_audio: ""
input_audio_offset: 0
input_audio_filters: []
# - variable_name: fLo
# f_center: 60
# f_width: 30
# order: 5

pre_animation_steps: 100
lock_camera: true
Expand Down
14 changes: 13 additions & 1 deletion src/pytti/config/structured_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ def check_input_against_list(attribute, value, valid_values):
)


@define(auto_attribs=True)
class AudioFilterConfig:
variable_name: str = ""
f_center: int = -1
f_width: int = -1
order: int = 5


@define(auto_attribs=True)
class ConfigSchema:
#############
Expand Down Expand Up @@ -100,6 +108,10 @@ def check(self, attribute, value):
### Induced Motion ###
######################

input_audio: str = ""
input_audio_offset: float = 0
input_audio_filters: Optional[AudioFilterConfig] = None

# _2d and _3d only apply to those animation modes

translate_x: str = "0"
Expand Down Expand Up @@ -195,7 +207,7 @@ def check(self, attribute, value):
backups: int = 0
show_graphs: bool = False
approximate_vram_usage: bool = False
use_tensorboard: bool = False
use_tensorboard: Optional[bool] = False

#####################################

Expand Down
16 changes: 14 additions & 2 deletions src/pytti/eval_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

math_env = None
global_t = 0
global_bands = {}
global_bands_prev = {}
eval_memo = {}


Expand All @@ -27,6 +29,11 @@ def parametric_eval(string, **vals):
)
math_env.update(vals)
math_env["t"] = global_t
for band in global_bands:
math_env[band] = global_bands[band]
if global_bands_prev:
for band in global_bands_prev:
math_env[f'{band}_prev'] = global_bands_prev[band]
try:
output = eval(string, math_env)
except SyntaxError as e:
Expand All @@ -37,9 +44,14 @@ def parametric_eval(string, **vals):
return string


def set_t(t):
global global_t, eval_memo
def set_t(t, band_dict):
global global_t, global_bands, global_bands_prev, eval_memo
global_t = t
if global_bands:
global_bands_prev = global_bands
else:
global_bands_prev = band_dict
global_bands = band_dict
eval_memo = {}


Expand Down
20 changes: 19 additions & 1 deletion src/pytti/update_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,28 @@ def save_out(
t = (i - params.pre_animation_steps) / (
params.steps_per_frame * params.frames_per_second
)
set_t(t)
set_t(t, {})
if i >= params.pre_animation_steps:
if (i - params.pre_animation_steps) % params.steps_per_frame == 0:
logger.debug(f"Time: {t:.4f} seconds")

# Audio Reactivity ############
if model.audio_parser is None:
set_t(t, {})
# set_t(t) # this won't need to be a thing with `t`` attached to the class
if i >= params.pre_animation_steps:
# next_step_pil = None
if (i - params.pre_animation_steps) % params.steps_per_frame == 0:
if model.audio_parser is not None:
band_dict = model.audio_parser.get_params(t)
logger.debug(
f"Time: {t:.4f} seconds, audio params: {band_dict}"
)
set_t(t, band_dict)
else:
logger.debug(f"Time: {t:.4f} seconds")
###############################

update_rotoscopers(
((i - params.pre_animation_steps) // params.steps_per_frame + 1)
* params.frame_stride
Expand Down
8 changes: 8 additions & 0 deletions tests/config/default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,11 @@ models_parent_dir: ${user_cache:}
##########################

gradient_accumulation_steps: 1

##################

# This shouldn't be necessary, but let's see if maybe it squashes test errors?

input_audio: ""
input_audio_offset: 0
input_audio_filters: null
4 changes: 4 additions & 0 deletions tests/test_animation_broken.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@
##########################
# adding new config items for backwards compatibility
"use_tensorboard": True, # This should actually default to False. Prior to April2022, tb was non-optional
# Default null audio input parameters
"input_audio": "",
"input_audio_offset": 0,
"input_audio_filters": [],
}


Expand Down