Error with pydub in python - python

i have successfully imported pydub
but for the code:
from pydub import AudioSegment
song = AudioSegment.from_mp3("c:\mks.mp3")
first_ten_seconds = song[:10000]
song.export("d:\mks.mp3", format="mp3")
But it gives the following error:
python "C:\Users\mKs\Desktop\mks2.py"
Process started >>>
Traceback (most recent call last):
File "C:\Users\mKs\Desktop\mks2.py", line 2, in <module>
song=AudioSegment.from_mp3("c:\mks.mp3");
File "C:\Python27\lib\site-packages\pydub-0.5.2-py2.7.egg\pydub\audio_segment.py", line 194, in from_mp3
return cls.from_file(file, 'mp3')
File "C:\Python27\lib\site-packages\pydub-0.5.2-py2.7.egg\pydub\audio_segment.py", line 189, in from_file
return cls.from_wav(output)
File "C:\Python27\lib\site-packages\pydub-0.5.2-py2.7.egg\pydub\audio_segment.py", line 206, in from_wav
return cls(data=file)
File "C:\Python27\lib\site-packages\pydub-0.5.2-py2.7.egg\pydub\audio_segment.py", line 33, in __init__
raw = wave.open(StringIO(data), 'rb')
File "C:\Python27\lib\wave.py", line 498, in open
return Wave_read(f)
File "C:\Python27\lib\wave.py", line 163, in __init__
self.initfp(f)
File "C:\Python27\lib\wave.py", line 128, in initfp
self._file = Chunk(file, bigendian = 0)
File "C:\Python27\lib\chunk.py", line 63, in __init__
raise EOFError
EOFError
I would love to get help on this topic

The only issue that I see with your code is trailing ";" at the end of last 3 line. Please remove those, and see if you still get the error.
In addition, make sure you have ffmpeg (http://www.ffmpeg.org/) installed. It is required for the support of all of the none wav file formats.
ADDED:
I think you have broken module dependencies in your python installation.
I have tried code that you provided above with python 2.7.2. It worked fine for me:
>>> from pydub import AudioSegment
>>> song = AudioSegment.from_wav('goodbye.wav')
>>> first_ten_seconds = song[:10000]
>>> song.export('goodbye1.wav',format='wav')
<open file 'goodbye1.wav', mode 'wb+' at 0x10cf2b270>

Related

Python error :OSError: [Errno 9] Bad file descriptor

I have wanted to transform DOCX file using docx library. Everytime I run it i get this error
OSError: [Errno 9] Bad file descriptor
The code is :
from docx import Document
def bionify(path_to_text: str) -> None:
doc = Document(path_to_text)
new_doc = Document()
all_paragraphs = doc.paragraphs
for paragraph in all_paragraphs:
word_list = paragraph.text.split(' ')
new_paragraph = new_doc.add_paragraph()
for word in word_list:
i = 0
while i < len(word):
if i == 0 or i == 1:
new_paragraph.add_run(word[i]).bold = True
else:
new_paragraph.add_run(word[i]).bold = False
i += 1
new_paragraph.add_run(' ')
# Input the path to the document that you wish to save to:
new_doc.save('sample_output.docx')
if __name__ == '__main__':
# Input the path to the document containing your text file you wish to read from:
bionify(r'C:\Users\###\Desktop\bionic python reader transformer\BionicTexterizer\sample_input.docx')
I have changed the destination, python package, python version to run it. But every time I get OSError: [Errno 9] Bad file descriptor
Complete tracepack:
Traceback (most recent call last):
File "c:\Users\####\Desktop\bionic python reader transformer\BionicTexterizer\main.py", line 62, in <module>
bionify(r'C:\Users\####\Desktop\bionic python reader transformer\BionicTexterizer\sample_input.docx')
File "c:\Users\####\Desktop\bionic python reader transformer\BionicTexterizer\main.py", line 57, in bionify
new_doc.save('sample_output.docx')
File "C:\Python310\lib\site-packages\docx\document.py", line 135, in save
self._part.save(path_or_stream)
File "C:\Python310\lib\site-packages\docx\parts\document.py", line 111, in save
self.package.save(path_or_stream)
File "C:\Python310\lib\site-packages\docx\opc\package.py", line 172, in save
PackageWriter.write(pkg_file, self.rels, self.parts)
File "C:\Python310\lib\site-packages\docx\opc\pkgwriter.py", line 33, in write
PackageWriter._write_content_types_stream(phys_writer, parts)
File "C:\Python310\lib\site-packages\docx\opc\pkgwriter.py", line 45, in _write_content_types_stream
phys_writer.write(CONTENT_TYPES_URI, cti.blob)
File "C:\Python310\lib\site-packages\docx\opc\phys_pkg.py", line 155, in write
self._zipf.writestr(pack_uri.membername, blob)
File "C:\Python310\lib\zipfile.py", line 1810, in writestr
with self.open(zinfo, mode='w') as dest:
File "C:\Python310\lib\zipfile.py", line 1176, in close
self._fileobj.seek(self._zinfo.header_offset)
OSError: [Errno 9] Bad file descriptor
Exception ignored in: <function ZipFile.__del__ at 0x0000022D9BF4BEB0>
Traceback (most recent call last):
File "C:\Python310\lib\zipfile.py", line 1815, in __del__
self.close()
File "C:\Python310\lib\zipfile.py", line 1837, in close
self._fpclose(fp)
File "C:\Python310\lib\zipfile.py", line 1937, in _fpclose
fp.close()
Windows 11. It is a problem with windows 11. I have ran the code without any problems on windows 10. There seems to some package permission issues.

Error in librosa.load('path.webm') RuntimeError: File contains data in an unknown format

I am trying to load sound files on a python script.
I installed, loaded the right version of modules, imported successfully librosa and soundfile, and even ffmpeg (which I found was a solution to this same error for mp3 files)
import os
import json
from scipy import signal
import librosa
[...]
y, sr = librosa.load(directory_path + filename + '.webm', mono = True)
My code works on notebooks (Kaggle) but somehow, and I can't figure out why, it doesn't work when uploaded on a computer cluster. And I really need the cluster for its computational power/memory. :/
The error:
Traceback (most recent call last):
File "/cluster/apps/nss/gcc-6.3.0/python/3.8.5/x86_64/lib64/python3.8/site-packages/librosa/core/audio.py", line 146, in load
with sf.SoundFile(path) as sf_desc:
File "/cluster/home/.local/lib/python3.8/site-packages/soundfile.py", line 740, in __init__
self._file = self._open(file, mode_int, closefd)
File "/cluster/home/.local/lib/python3.8/site-packages/soundfile.py", line 1264, in _open
_error_check(_snd.sf_error(file_ptr),
File "/cluster/home/.local/lib/python3.8/site-packages/soundfile.py", line 1455, in _error_check
raise RuntimeError(prefix + _ffi.string(err_str).decode('utf-8', 'replace'))
RuntimeError: Error opening 'input/00092.webm': File contains data in an unknown format.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "analysis_python.py", line 47, in <module>
y,sr = librosa.load(directory_path + filename + '.webm')
File "/cluster/apps/nss/gcc-6.3.0/python/3.8.5/x86_64/lib64/python3.8/site-packages/librosa/core/audio.py", line 163, in load
y, sr_native = __audioread_load(path, offset, duration, dtype)
File "/cluster/apps/nss/gcc-6.3.0/python/3.8.5/x86_64/lib64/python3.8/site-packages/librosa/core/audio.py", line 187, in __audioread_load
with audioread.audio_open(path) as input_file:
File "/cluster/apps/nss/gcc-6.3.0/python/3.8.5/x86_64/lib64/python3.8/site-packages/audioread/__init__.py", line 116, in audio_open
raise NoBackendError()
audioread.exceptions.NoBackendError
I perused the internet for a solution but no luck. Thank you for your help in advance.

Getting error 'NotImplementedError("That compression method is not supported")' when extracting zipfile in python3.9

I have read through the Python documentation about zip files and watched a couple of videos, but everything didn't work. I'm using Kali Linux, so that the password has to be encoded in bytes.
Here is my code, with which I have tried:
import zipfile
import string
import traceback
def try_function(zip, pwd):
try:
zip.extractall(pwd=pwd.encode())
print("Yes")
except TypeError:
print("No")
z = zipfile.ZipFile("test.txt.zip")
pwd_local = "abc"
if __name__ == '__main__':
try_function(z, pwd_local)
But I always get the same error:
Traceback (most recent call last):
File "ZipWorker.py", line 22, in <module>
try_function(z, pwd_list)
File "ZipWorker.py", line 11, in crack
zip.extractall(pwd.encode())
File "/usr/lib/python3.9/zipfile.py", line 1633, in extractall
self._extract_member(zipinfo, path, pwd)
File "/usr/lib/python3.9/zipfile.py", line 1686, in _
extract_member
with self.open(member, pwd=pwd) as source, \
File "/usr/lib/python3.9/zipfile.py", line 1559, in open
return ZipExtFile(zef_file, mode, zinfo, pwd, True)
File "/usr/lib/python3.9/zipfile.py", line 797, in __init__
self._decompressor = _get_decompressor(self._compress_type)
File "/usr/lib/python3.9/zipfile.py", line 698, in
_get_decompressor
_check_compression(compress_type)
File "/usr/lib/python3.9/zipfile.py", line 678, in
_check_compression
raise NotImplementedError("That compression method is not
supported")
NotImplementedError: That compression method is not supported
Does anyone know how to do this? I'm using python3.9.
So I finally find out, why the code above doesn't work.
When you are creating a zipfile with for example 7zip, this zip file will be encrypted.
But the encryption isn't in bytes, it's encrypted in the hashes: AES-256 or ZipCrypto.

Python - get encoding of file

I'm having difficulty getting the character encoding of a file. The offending code is here:
rawdata = open(file, "r").read()
encoding = chardet.detect(rawdata.encode())['encoding']
#return encoding
(Code courtesy of Ashish Greycube: https://github.com/frappe/frappe/pull/8061
I've copied a segment of the csv file I'm working on as a more manageable 'test' file. When I run the above code on it, it says it's 'ascii'. That might be part of the problem. Basically, I've found out that I need to know the encoding type for this prpogram.
The error report is as follows:
Traceback (most recent call last):
File ".\program.py", line 26, in <module>
my_encoding = get_file_encoding(data)
File ".\program.py", line 20, in get_file_encoding
encoding = chardet.detect(rawdata.encode())['encoding']
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\__init__.py", line 38, in detect
detector.feed(byte_str)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\universaldetector.py", line 211, in feed
if prober.feed(byte_str) == ProbingState.FOUND_IT:
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\charsetgroupprober.py", line 71, in feed
state = prober.feed(byte_str)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\hebrewprober.py", line 227, in feed
byte_str = self.filter_high_byte_only(byte_str)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\charsetprober.py", line 63, in filter_high_byte_only
buf = re.sub(b'([\x00-\x7F])+', b' ', buf)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 208, in sub
return _compile(pattern, flags).sub(repl, string, count)
MemoryError
PS C:\Users\stsho\dev\csv_sanitizer_1.2> python .\program.py
Please enter filename: ANQAR
Traceback (most recent call last):
File ".\program.py", line 26, in <module>
my_encoding = get_file_encoding(data)
File ".\program.py", line 19, in get_file_encoding
rawdata = open(file, "r").read()
FileNotFoundError: [Errno 2] No such file or directory: 'ANQAR.csv'
PS C:\Users\stsho\dev\csv_sanitizer_1.2> python .\program.py
Please enter filename: ANQAR
Traceback (most recent call last):
File ".\program.py", line 26, in <module>
my_encoding = get_file_encoding(data)
File ".\program.py", line 19, in get_file_encoding
rawdata = open(file, "r").read()
FileNotFoundError: [Errno 2] No such file or directory: 'ANQAR.csv'
PS C:\Users\stsho\dev\csv_sanitizer_1.2> python .\program.py
Please enter filename: ANQAR
Traceback (most recent call last):
File ".\program.py", line 26, in <module>
my_encoding = get_file_encoding(data)
File ".\program.py", line 20, in get_file_encoding
encoding = chardet.detect(rawdata.encode())['encoding']
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\__init__.py", line 38, in detect
detector.feed(byte_str)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\universaldetector.py", line 211, in feed
if prober.feed(byte_str) == ProbingState.FOUND_IT:
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\charsetgroupprober.py", line 71, in feed
state = prober.feed(byte_str)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\hebrewprober.py", line 227, in feed
byte_str = self.filter_high_byte_only(byte_str)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\site-packages\chardet\charsetprober.py", line 63, in filter_high_byte_only
buf = re.sub(b'([\x00-\x7F])+', b' ', buf)
File "C:\Users\stsho\AppData\Local\Programs\Python\Python38-32\lib\re.py", line 208, in sub
return _compile(pattern, flags).sub(repl, string, count)
MemoryError
A MemoryError usually implies you're trying to load data too large for your memory, either the address space or available storage (RAM + swap/page file space). You seem to be running a 32 bit build of Python, which would limit you to 2 GB of address space; I'd suggest switching to a 64 bit build, as most machines nowadays have more than 4 GB of RAM, and not using a 64 bit build means you can't use most of it.
Additional issue: When you read the file in text mode, you're already assuming you know the encoding. Don't do that. Open it in binary mode ("rb") to get the raw, unmodified bytes, so chardet gets them directly before you try decoding them in a possibly incorrect encoding.
This works:
import chardet
rawdata = open(file, "rb").read()
encoding = chardet.detect(rawdata)['encoding']
like #ShadowRanger said try to build it in 64bit and don't read file in text mode try this
enter co rawdata = open(file, "rb").read()
encoding = chardet.detect(rawdata.encode())['encoding']
and make sure your file is present and write its name correctly.

How can read Minecraft .mca files so that in python I can extract individual blocks?

I can't find a way of reading the Minecraft world files in a way that i could use in python
I've looked around the internet but can find no tutorials and only a few libraries that claim that they can do this but never actually work
from nbt import *
nbtfile = nbt.NBTFile("r.0.0.mca",'rb')
I expected this to work but instead I got errors about the file not being compressed or something of the sort
Full error:
Traceback (most recent call last):
File "C:\Users\rober\Desktop\MinePy\MinecraftWorldReader.py", line 2, in <module>
nbtfile = nbt.NBTFile("r.0.0.mca",'rb')
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\site-packages\nbt\nbt.py", line 628, in __init__
self.parse_file()
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\site-packages\nbt\nbt.py", line 652, in parse_file
type = TAG_Byte(buffer=self.file)
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\site-packages\nbt\nbt.py", line 99, in __init__
self._parse_buffer(buffer)
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\site-packages\nbt\nbt.py", line 105, in _parse_buffer
self.value = self.fmt.unpack(buffer.read(self.fmt.size))[0]
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\gzip.py", line 276, in read
return self._buffer.read(size)
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\_compression.py", line 68, in readinto
data = self.read(len(byte_view))
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\gzip.py", line 463, in read
if not self._read_gzip_header():
File "C:\Users\rober\AppData\Local\Programs\Python\Python36-32\lib\gzip.py", line 411, in _read_gzip_header
raise OSError('Not a gzipped file (%r)' % magic)
OSError: Not a gzipped file (b'\x00\x00')
Use anvil parser. (Install with pip install anvil-parser)
Reading
import anvil
region = anvil.Region.from_file('r.0.0.mca')
# You can also provide the region file name instead of the object
chunk = anvil.Chunk.from_region(region, 0, 0)
# If `section` is not provided, will get it from the y coords
# and assume it's global
block = chunk.get_block(0, 0, 0)
print(block) # <Block(minecraft:air)>
print(block.id) # air
print(block.properties) # {}
https://pypi.org/project/anvil-parser/
According to this page, the .mca files is not totally kind of of NBT file. It begins with an 8KiB header which includes the offsets of chunks in the region file itself and the timestamps for the last updates of those chunks.
I recommend you to see the offical announcement and this page for more information.

Categories

Resources