Blane187 commited on
Commit
c0560f8
1 Parent(s): 21d0d32

Create animalesepy.py

Browse files
Files changed (1) hide show
  1. animalesepy.py +56 -0
animalesepy.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Animalese:
2
+ def __init__(self, letters_file, onload):
3
+ with open(letters_file, 'rb') as f:
4
+ self.letter_library = np.frombuffer(f.read(), dtype=np.uint8)
5
+ onload()
6
+
7
+ def synthesize(self, script, shorten=False, pitch=1.0):
8
+ def shorten_word(word):
9
+ return word[0] + word[-1] if len(word) > 1 else word
10
+
11
+ if shorten:
12
+ # Replace all non-alphabet characters with spaces and split the script into words
13
+ words = re.sub(r'[^a-zA-Z]', ' ', script).split()
14
+ # Shorten each word and join them back into a single string
15
+ processed_script = "".join(map(shorten_word, words))
16
+ else:
17
+ processed_script = script
18
+
19
+ data = []
20
+
21
+ sample_freq = 44100
22
+ library_letter_secs = 0.15
23
+ library_samples_per_letter = int(library_letter_secs * sample_freq)
24
+ output_letter_secs = 0.075
25
+ output_samples_per_letter = int(output_letter_secs * sample_freq)
26
+
27
+ for c in processed_script.upper():
28
+ if 'A' <= c <= 'Z':
29
+ library_letter_start = library_samples_per_letter * (ord(c) - ord('A'))
30
+ for i in range(output_samples_per_letter):
31
+ data.append(self.letter_library[44 + library_letter_start + int(i * pitch)])
32
+ else:
33
+ data.extend([127] * output_samples_per_letter)
34
+
35
+ # Create the .wav file data
36
+ data = np.array(data, dtype=np.uint8)
37
+ return self.create_wave(data, sample_freq)
38
+
39
+ def create_wave(self, data, sample_rate):
40
+ output_file = "output.wav"
41
+ with wave.open(output_file, "wb") as f:
42
+ f.setnchannels(1)
43
+ f.setsampwidth(1)
44
+ f.setframerate(sample_rate)
45
+ f.writeframes(data.tobytes())
46
+ return output_file
47
+
48
+ # Initialize the synthesizer
49
+ synth = Animalese('animalese.wav', lambda: print("Loaded"))
50
+
51
+ def generate_audio(text, shorten, pitch):
52
+ return synth.synthesize(text, shorten, pitch)
53
+
54
+ def preview_audio(audio_file):
55
+ with open(audio_file, 'rb') as f:
56
+ return f.read()