danjacobellis commited on
Commit
a912f33
1 Parent(s): 49ddfb0

Upload audio_diffusion.py

Browse files
Files changed (1) hide show
  1. audio_diffusion.py +96 -0
audio_diffusion.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import tensorflow_io as tfio
3
+ import IPython.display as ipd
4
+ import matplotlib.pyplot as plt
5
+ import scipy as sp
6
+ import PIL.Image
7
+ import numpy as np
8
+
9
+ def wav_to_tf(filename):
10
+ bits = tf.io.read_file(filename)
11
+ x = tfio.audio.decode_wav(bits,dtype=tf.int16)[:,0]
12
+ x = tf.cast(x,tf.float32)
13
+ x = x - tf.math.reduce_mean(x);
14
+ x = x / tf.math.reduce_std(x)
15
+ return tf.Variable(x)
16
+
17
+ def play(x,rate=24000):
18
+ ipd.display(ipd.Audio(x,rate=rate,autoplay=False))
19
+
20
+ def slog(x):
21
+ return tf.sign(x) * tf.math.log(1+ tf.math.abs(x) )
22
+
23
+ def show(X,clim=(-3,3), xlim=(0,300), ylim=(0,100)):
24
+ plt.figure(figsize=(15,6),dpi=200)
25
+ plt.imshow(tf.transpose(X),origin='lower',cmap='RdBu')
26
+ plt.colorbar()
27
+ plt.clim(clim)
28
+ plt.xlim(xlim)
29
+ plt.ylim(ylim)
30
+
31
+ def mdct(x,L=624):
32
+ X = tf.signal.mdct(x,L);
33
+ return tf.Variable(X)
34
+
35
+ def imdct(X):
36
+ y = tf.signal.inverse_mdct(X)
37
+ return y
38
+
39
+ Γ = sp.special.gamma
40
+
41
+ def F(x,μ,σ,γ):
42
+ return sp.stats.gennorm.cdf(x, beta=γ, loc=μ, scale=σ)
43
+
44
+ def Finv(x,μ,σ,γ):
45
+ return sp.stats.gennorm.ppf(x, beta=γ, loc=μ, scale=σ)
46
+
47
+ def r(γ):
48
+ return Γ(1/γ)*Γ(3/γ)/Γ(2/γ)
49
+
50
+ def estimate_GGD(X):
51
+ μ = tf.math.reduce_mean(X)
52
+ σ = tf.math.reduce_std(X)
53
+ E = tf.math.reduce_mean(tf.abs(X - μ))
54
+ ρ = tf.square(σ/E)
55
+
56
+ γ = sp.optimize.bisect(lambda γ:r(γ)-ρ, 0.3, 1.5,maxiter=50)
57
+ return μ,σ,γ
58
+
59
+ def tf_to_pil(x):
60
+ x = np.array(x)
61
+ return PIL.Image.fromarray(x,mode="L")
62
+ def pil_to_tf(x):
63
+ x = np.array(x)
64
+ return tf.convert_to_tensor(x)
65
+
66
+ def σ_prior(band):
67
+ def sc(z,μ,σ,γ):
68
+ return sp.stats.skewcauchy.pdf(z, γ, loc=μ, scale=σ)
69
+ return 10000*(2*sc(band,20,100,0.9)+sc(band,22,12,0.5))
70
+
71
+ def img_to_mdct(img):
72
+ X = []
73
+ q = 256;
74
+ Y = pil_to_tf(img)
75
+ Y = tf.cast(Y,tf.float32)/q
76
+ for i_band in range(512):
77
+ band = Y[:,i_band]
78
+ σ = σ_prior(i_band)
79
+ X.append(Finv(band,0,σ,0.85))
80
+ X = tf.stack(X)
81
+ X = tf.transpose(X)
82
+ X = tf.where(tf.math.is_inf(X), tf.ones_like(X), X)
83
+ return tf.cast(X,tf.float32)
84
+
85
+ def mdct_to_img(X):
86
+ Y = []
87
+ q = 256;
88
+ for i_band in range(512):
89
+ band = X[:,i_band]
90
+ σ = σ_prior(i_band)
91
+ Y.append(F(band,0,σ,0.85))
92
+ Y = tf.stack(Y)
93
+ Y = tf.transpose(Y)
94
+ Y = tf.round(q*Y)
95
+ Y = tf.cast(Y,tf.uint8)
96
+ return tf_to_pil(Y)