I am currently putting together a band-pass filter using the following code: https://ipython-books.github.io/116-applying-digital-filters-to-speech-sounds/
I made few edits to the above code, namely the file is no longer pulled from an url but instead from a local WAV file. Here are the associated edits
def speak(voice):
audio = pydub.AudioSegment.from_wav(BytesIO(voice))
with tempfile.temporaryfile() as fn:
wavef = audio.export(fn, format='wav')
wavef.seek(0)
wave = wavef.read()
...
voice = open("C:\\Users\\tkim1\\Documents\\librosa\\NEUT 41s
shaking_gold.wav", "rb").read
Currently the "audio = pydub.AudioSegment.from_wav" line of the code outputs the following error: a bytes-like object is required, not 'builtin_function_or_method." I have gone over the two scripts line by line and cannot determine why this error is surfacing. Thank you so much for reading everyone. Any insights would be greatly appreciated!
You didn't call read, which is a method.
voice = open("...", "rb").read()
# ^
Related
I'm trying to write a program that takes a bunch of videos from a folder, compiles them, and then takes another bunch of audio files from a folder and concatenates them to then overlay the combined audio on top of the final video (hope that makes sense). I'm able to process the videos into one final output video, but I keep running into trouble combining the audio. Below I've provided two small sections of code pertaining to audio comp, I'm using moviepy to process the videos and attempting to use it for audio as well.
songDirectory = './songs/'
songList = []
songs = []
audioclip=''
def makeCompilation():
for filename in os.listdir(songDirectory):
f = os.path.join(songDirectory, filename)
if os.path.isfile(f) and filename.endswith(".mp3"):
audioclip = moviepy.editor.AudioFileClip(f)
songList.append(filename)
for song in os.listdir(songDirectory):
c = os.path.join(songDirectory, song)
audio_clips = moviepy.editor.AudioFileClip(c)
audio_output = moviepy.editor.concatenate_audioclips(audio_clips)
finalClip = concatenate_videoclips(videos, method="compose")
final_duration = finalClip.duration
final_audio_output = audio_output.set_duration(final_duration)
final_output= finalClip.set_audio(final_audio_output).fx(afx.audio_fadein, 3.0)
audio_path = "./songs/tempaudiofile.m4a"
#print(description)
# Create compilation
final_output.write_videofile(outputFile, threads=8, temp_audiofile=audio_path, remove_temp=True, codec="libx264", audio_codec="aac")
return description
The program appeared to be able to find the audio directory, but I needed to be able to use os.path.join(songDirectory, filename) to point directly to each mp3 file so I messed around with it until I got the above code. And when I attempted to iterate through songList, I, as expected, got an error saying that 'str' wasn't iterable, and other errors saying that 'str' has no attribute 'duration'. Essentially, all I need it to do is iterate though the input folder and combine the files by whatever means. Code currently returns the output:
🌲Free Fredobagz x Aflacko x Flint type beat - 'Default_Dance' [prod. kah]-jro0v6ogZ0Y.mp4
225.05
Total Length: 225.05
225.05
Traceback (most recent call last):
File "/Users/daddyK/Desktop/comp_ bot/make_compilation3.py", line 127, in <module>
makeCompilation(path = "./videos/",
File "/Users/daddyK/Desktop/comp_ bot/make_compilation3.py", line 110, in makeCompilation
audio_output = moviepy.editor.concatenate_audioclips(audio_clips)
File "/Users/daddyK/Library/Python/3.10/lib/python/site-packages/moviepy/audio/AudioClip.py", line 315, in concatenate_audioclips
durations = [c.duration for c in clips]
TypeError: 'AudioFileClip' object is not iterable
At this point I'm a bit stumped, so if anybody could offer some insight as to what I should do to resolve the error and/or if I'm headed in the right direction code-wise I'd greatly appreciate it! Sorry if the code doesn't make any sense I'll post the whole .py file if needed
As per the comment by #kesh, you need to replace
songList.append(filename)
with
songList.append(audioclip)
Although there's a lot of subjects related to my question already, the answers are usually no understandable for me, as I am just a beginner in the "writting scripts in Python" field.
Here is my situation :
There's a machine learning software that writes models in a .pkl format at the end of its learning phase. I would like to make those model.pkl files openable by an operator to check what there is inside the model. Thus I began to write a script that would use the pickle.load method and write the data contained in my model.pkl into a .txt file. Here's what I wrote to begin with:
import pickle
import os
model_path=input("Model Path = ")
with open(model_path, "rb") as model :
load = pickle.load(model, encoding='utf-8')
new_model_path = model_path.split('.pkl')[0] +'.txt'
print("creating new file at : ", new_model_path)
model_readable = open(new_model_path, 'rt')
model_readable.write(load)
print("writing model as readable : ", load)
model_readable.close()
model.close()
If I try to run it here's the output :
python3.7 unpickler.py
Model Path = /home/ouriacc/Desktop/workspace/SESAM/Base_de_tests/Anomalie_1/Models/OCSVM/EyeSat/CI_HEATER_CAMERA_VOLTAGE.pkl
Traceback (most recent call last):
File "unpickler.py", line 7, in <module>
load = pickle.load(model, encoding='utf-8')
_pickle.UnpicklingError: invalid load key, '_'.
I couldn't find any explanation about this error that didn't imply an incomplete or corrupted download, which can't be my case here as the model.pkl files are not modified once they've been created by the AI software.
Could someone help me to solve the error or even indicate me an other methode to achieve my goal ? All I need is a script that gives access for a user to what the .pkl file contains.
Thank you very much !
So I figured out why #wundermahn asked about scikit-learn. It seems my model.pkl files were generated by joblib and not exactly pickle library. This is why it wouldn't work apparently. It changed my code by replacing pickle.load() by joblid.load() and it works better !
Thank you !
I'm attempting to read in a series of files for processing contained in a single directory using RedVox:
input_directory = "/home/ben/Documents/Data/F1D1/21" # file location
rdvx_data = DataWindow(input_dir=input_directory, apply_correction=False, debug=True) # using RedVox to read in the files
print(os.listdir(input_directory)) # verifying the files actually exist...
# returns "['file1.rdvxz', 'file2.rdvxz', file3.rdvxz', ...etc]", they exist
# write audio portion to file
rdvx_data.to_json_file(base_dir=output_rpd_directory,
file_name=output_filename)
# this never runs, because rdvx_data.stations = [] (verified through debugging)
for station in rdvx_data.stations:
# some code here
Enabling debugging through arguments as seen above does not provide an extra details. In fact, there is no error message whatsoever. It writes the JSON file and pickle to disk, but the JSON file is full of null values and the pickle object is just a shell, no contents. So the files definitely exist, os.listdir() sees them, but RedVox does not.
I assume this is some very silly error or lack of understanding on my part. Any help is greatly appreciated. I have not worked with RedVox previously, nor do I have much understanding of what these files contain other than some audio data and some other data. I've simply been tasked with opening them to work on a model to analyze the data within.
SOLVED: Not sure why the previous code doesn't work (it was handed to me), however, I worked around the DataWindow call and went straight to calling the "redvox.api900.reader" object:
from redvox.api900 import reader
dataset_dir = "/home/*****/Documents/Data/F1D1/21/"
rdvx_files = glob(dataset_dir+"*.rdvxz")
for file in rdvx_files:
wrapped_packet = reader.read_rdvxz_file(file)
From here I can view all of the sensor data within:
if wrapped_packet.has_microphone_sensor():
microphone_sensor = wrapped_packet.microphone_sensor()
print("sample_rate_hz", microphone_sensor.sample_rate_hz())
Hope this helps anyone else who's confused.
The structure of file is not important for me so from some previous solution as mentioned "converting them to plain text and importing them with readLines" ,i changed file type from ".doc/.docx" to ".txt" and end up with an error
file_list = list.files("D:/R/New",pattern="*.txt",full.names=F
obj_list <- lapply(file_list,readLines)
Warning messages:
1: In FUN(c("adityar.txt":
incomplete final line found on 'adityar.txt'
I have tried to read with the help of corpus as well but didnt find good result ,here the second solution says about pdf and unix ,any better and fast approach, i am working on windows platform,any help.
Using python , you can do this :
from docx import *
import json
document = opendocx("path_to_your_docx")
res = getdocumenttext(document)
You can save your script and call it from R using system
I'm hoping my problem can be solved with some geojson expertise. The problem I'm having has to do with RhinoPython - the embedded IronPython engine in McNeel's Rhino 5 (more info here: http://python.rhino3d.com/). I don't think its necessary to be an expert on RhinoPython to answer this question.
I'm trying to load a geojson file in RhinoPython. Because you can't import the geojson module into RhinoPython like in Python I'm using this custom module GeoJson2Rhino provided here: https://github.com/localcode/rhinopythonscripts/blob/master/GeoJson2Rhino.py
Right now my script looks like this:
`import rhinoscriptsyntax as rs
import sys
rp_scripts = "rhinopythonscripts"
sys.path.append(rp_scripts)
import rhinopythonscripts
import GeoJson2Rhino as geojson
layer_1 = rs.GetLayer(layer='Layer 01')
layer_color = rs.LayerColor(layer_1)
f = open('test_3.geojson')
gj_data = geojson.load(f,layer_1,layer_color)
f.close()`
In particular:
f = open('test_3.geojson')
gj_data = geojson.load(f)
works fine when I'm trying to extract geojson data from regular python 2.7. However in RhinoPython I'm getting the following error message: Message: expected string for parameter 'text' but got 'file'; in reference to gj_data = geojson.load(f).
I've been looking at the GeoJson2Rhino script linked above and I think I've set the parameters for the function correctly. As far as I can tell it doesn't seem to recognize my geojson file, and wants it as a string. Is there an alternative file open function I can use to get the function to recognize it as a geojson file?
Judging by the error message, it looks like the load method requires a string as the first input but in the above example a file object is being passed instead. Try this...
f = open('test_3.geojson')
g = f.read(); # read contents of 'f' into a string
gj_data = geojson.load(g)
...or, if you don't actually need the file object...
g = open('test_3.geojson').read() # get the contents of the geojson file directly
gj_data = geojson.load(g)
See here for more information about reading files in python.