Attribute error in python with Google Speech API - python

'str' object has no attribute 'long_running_recognize'. This error is occurring at the last line of the code shown. I jump into the code and see no obvious reason for it to fail. Jumps out at the wrap_method below.
if "long_running_recognize" not in self._inner_api_calls:
self._inner_api_calls[
"long_running_recognize"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.long_running_recognize,
default_retry=self._method_configs["LongRunningRecognize"].retry,
default_timeout=self._method_configs["LongRunningRecognize"].timeout,
client_info=self._client_info,
)
The only issue that I could conceive here is maybe the audio file is too large(45mb...53 min). But the code break happens in a location that doesn't appear to relate to this.
import io
import os
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
with open("path\\My First Project-edb18653fedf.json") as f:
GOOGLE_APPLICATION_CREDENTIALS = f.read()
client = speech.SpeechClient(GOOGLE_APPLICATION_CREDENTIALS)
file_path = "audio\\102.flac"
with io.open(file_path, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
sample_rate_hertz=32000,
language_code='en-US')
operation = client.long_running_recognize(config, audio)
Connected to pydev debugger (build 191.7479.30)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevd.py", line 1758, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevd.py", line 1752, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\pydevd.py", line 1147, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/shear/Documents/PythonScripts/GStTEnv/SpeechToText/CloudSpeechText.py", line 105, in <module>
operation = client.long_running_recognize(config, audio)
File "C:\Users\shear\GStTEnv\lib\site-packages\google\cloud\speech_v1\gapic\speech_client.py", line 314, in long_running_recognize
self.transport.long_running_recognize,
AttributeError: 'str' object has no attribute 'long_running_recognize'

Did you try to prove out your theory about the length of the audio? What happens if you trim the audio and try it?
Does it happen if you try a curl request at the command line instead of code?
I’d like to see if I can help. To diagnose further, would you be able to provide:
- Exact steps to reproduce
- Pointer to github repo if available
- As much of the code as you can provide
- Exact error messages
- Language Code (config)
- All configuration options applicable
- Sample audio file with all personal data removed (on Google Drive or Cloud Storage)

Related

BadRarFile when extracting single file using RarFile in Python

I need to extract a single file (~10kB) from many very large RAR files (>1Gb). The code below shows a basic implementation of how I'm doing this.
from rarfile import RarFile
rar_file='D:\\File.rar'
file_of_interest='Folder 1/Subfolder 2/File.dat'
output_folder='D:/Output'
rardata = RarFile(rar_file)
rardata.extract(file_of_interest, output_folder)
rardata.close()
However, the extract instruction is returning the following error: rarfile.BadRarFile: Failed the read enough data: req=16384 got=52
When I open the file using WinRAR, I can extract the file successfully, so I'm sure the file isn't corrupted.
I've found some similar questions, but not a definite answer that worked for me.
Can someone help me to solve this error?
Additional info:
Windows 10 build 1909
Spyder 5.0.0
Python 3.8.1
Complete traceback of the error:
Traceback (most recent call last):
File "D:\Test\teste_rar_2.py", line 27, in <module>
rardata.extract(file_of_interest, output_folder)
File "C:\Users\bernard.kusel\AppData\Local\Continuum\anaconda3\lib\site-packages\rarfile.py", line 826, in extract
return self._extract_one(inf, path, pwd, True)
File "C:\Users\bernard.kusel\AppData\Local\Continuum\anaconda3\lib\site-packages\rarfile.py", line 912, in _extract_one
return self._make_file(info, dstfn, pwd, set_attrs)
File "C:\Users\bernard.kusel\AppData\Local\Continuum\anaconda3\lib\site-packages\rarfile.py", line 927, in _make_file
shutil.copyfileobj(src, dst)
File "C:\Users\bernard.kusel\AppData\Local\Continuum\anaconda3\lib\shutil.py", line 79, in copyfileobj
buf = fsrc.read(length)
File "C:\Users\bernard.kusel\AppData\Local\Continuum\anaconda3\lib\site-packages\rarfile.py", line 2197, in read
raise BadRarFile("Failed the read enough data: req=%d got=%d" % (orig, len(data)))
BadRarFile: Failed the read enough data: req=16384 got=52

Using Flopy to create vtk output

I'm trying to write the model grid from a Modflow model to a vtk output to open in Paraview.
I've used Groundwater Vistas and created the MODFLOW - USG (Unstructured Grids)
When I try to use the export function I get the following error:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.2.5\helpers\pydev\pydevd.py", line 1415, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.2.5\helpers\pydev_pydev_imps_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Work/Models/Work/Projects/Job 302/Export grid.py", line 16, in
vtkobj = fp.export.vtk.Vtk(mf)
File "C:\ProgramData\Anaconda3\lib\site-packages\flopy\export\vtk.py", line 206, in init
self.shape = (self.modelgrid.nlay, self.modelgrid.nrow,
AttributeError: 'Grid' object has no attribute 'nlay'
Below is the code I've used:
import os
import flopy as fp
from flopy.export import vtk as fv
model_path = r'C:\Work\Models\302'
os.chdir(model_path)
# MODFLOW name file:
namefile = 'westend_Alluv3_11yr_A.nam'
mf = fp.modflow.Modflow.load(namefile,verbose=False,check=False)
# create the vtk object
vtkobj = fp.export.vtk.Vtk(mf)
Thanks

PyMongo: AttributeErrors for existing attributes in class _cmessage

I use pymongo to connect to my databases on a mongodb server. I set everything up and used a simple tutorial to start with basic things in pymongo. I ended up writting this into a python file:
from pymongo import MongoClient
from random import randint
client = MongoClient("localhost", 27017) #Class from PyMongo module
db = client["rothe_plana"]
# Initialize database settings for employers and events collections:
employersCollect = db["employers"]
eventsCollect = db["events"]
#-----------------------------------------------------
#Employer database managment:
#-----------------------------------------------------
#Inserts passed dictionary objects of employer profiles:
def insertNewEmployer(new_employer_profile):
while True:
try:
readyProfile = new_employer_profile.copy()
readyProfile['employer_id'] = randint(100, 999)
employersCollect.insert_one()
except pymongo.errors.DuplicateKeyError:
continue
break
def getListOfEmployerIDs():
pass #get employer ids to identify and render template elements.
# -----------------------------------------------------
# Events database managment:
# -----------------------------------------------------
#Inserts passed dictionary objects of event data:
def insertNewEvent(new_event_data):
while True:
try:
readyEventData = new_employer_profile.copy()
readyEventData['event_id'] = randint(10000000, 99999999)
employersCollect.insert_one()
except pymongo.errors.DuplicateKeyError:
continue
break
But if I run this I get an exception:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pydev\pydevd.py", line 1664, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pydev\pydevd.py", line 1658, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pydev\pydevd.py", line 1068, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2018.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/thoma/OneDrive/Projects_For_The_Web/Fliesen Rothe/PlanA/Pyramid_PlanA/pyramid_plana/datadbhandler.py", line 1, in <module>
from pymongo import MongoClient
File "C:\Users\thoma\OneDrive\Projects_For_The_Web\Fliesen Rothe\PlanA\Pyramid_PlanA\venv\lib\site-packages\pymongo\__init__.py", line 77, in <module>
from pymongo.collection import ReturnDocument
File "C:\Users\thoma\OneDrive\Projects_For_The_Web\Fliesen Rothe\PlanA\Pyramid_PlanA\venv\lib\site-packages\pymongo\collection.py", line 29, in <module>
from pymongo import (common,
File "C:\Users\thoma\OneDrive\Projects_For_The_Web\Fliesen Rothe\PlanA\Pyramid_PlanA\venv\lib\site-packages\pymongo\message.py", line 654, in <module>
_op_msg_uncompressed = _cmessage._op_msg
AttributeError: module 'pymongo._cmessage' has no attribute '_op_msg'
Since I certainly did not touch the Pymongo module code, I am doing something wrong in my code above. Also the web didn't bring up any results so is there a clear explanation for this?
EDIT: I had a closer look into the files that were provided by the above error. And I can see that the attribute in the specified class actually do exist. So that is quite strange. Even if I comment the dependent line out of pymongo, there is another AtrributeError for the same class.
I finally resolved the problem. It turned out that the permissions in my filesystem were not handled right.
I originally installed PyMongo via PyCharm (pip install pymongo). But this just does not work (no idea why) but I finally uninstalled pymongo from the virtual environment and installed it manually again via PowerShell in the virtual environment:
python -m pip install pymongo
Restarting PyCharm and running the project did bring up no errors anymore. Hope this may help others with this problem

Getting TypeError: 'NoneType' object is not iterable while reading a JSON file to store the values in a list [duplicate]

This question already has answers here:
Why does "x = x.append(...)" not work in a for loop?
(8 answers)
Closed 4 years ago.
Even though the variable is having the 1st dictionary value for the key name from the JSON file, while storing that value to a list I am getting output as None. This seems to be a strange.. Am I missing something. Could you please help
Code:
import os
import shutil
import json
MainDir = "F:/Protocols/20180207-Iteration/"
os.chdir(MainDir)
MainDir = os.getcwd()
# print(MainDir)
#Load the JSON data to a file
with open("F:/Protocols/20180207-Iteration/rout.json",'r',encoding='utf-8') as f:
json_file = json.load(f)
#To avoid appending delete the file all_iteration.txt if it exists
if os.path.exists("all_iteration.txt"):
os.remove("all_iteration.txt")
#Create all_iteration.txt which will store the foldernames of the particular Iteration inside the Iteration folder
Path_List = []
for values in json_file['value']:
Folder_Names = values['name']
Indivisuals = str(Folder_Names)
Path_List = list(Path_List.append(Indivisuals))
print(Path_List)
print(Path_List)
Log:
E:\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py" --multiproc --qt-support=auto --client 127.0.0.1 --port 51533 --file C:/Users/SPAR/PycharmProjects/Sample/PATH_FINDER.py
pydev debugger: process 10528 is connecting
Connected to pydev debugger (build 173.4301.16)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py", line 1668, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py", line 1662, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\pydevd.py", line 1072, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/SPAR/PycharmProjects/Sample/PATH_FINDER.py", line 23, in <module>
Path_List = list(Path_List.append(Indivisuals))
TypeError: 'NoneType' object is not iterable
Process finished with exit code 1
list.append() method doesn't return anything - it just appends the item into the list. Hence, you're trying to do list(None), which is raising the error since you can't create a list out of a NoneType object.
Just change the line
Path_List = list(Path_List.append(Indivisuals))
to
Path_List.append(Indivisuals)

python memory error when loading MNIST.pkl.gz

I am new to Python and I have downloaded the code DBN.py but there is a problem:when I was trying to load the dataset MNIST.pkl.gz.there is always an meomory error..
my code is very simple:
import cPickle, gzip, numpy
# Load the dataset
f = gzip.open('C:\Users\MAC\Desktop\mnist.pkl.gz', 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
and the error is as follows:
Traceback (most recent call last):
File "<ipython-input-17-528eea6bbfdd>", line 1, in <module>
runfile('C:/Users/MAC/Documents/Python Scripts/untitled0.py', wdir='C:/Users/MAC/Documents/Python Scripts')
File "C:\Users\MAC\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Users\MAC\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/MAC/Documents/Python Scripts/untitled0.py", line 19, in <module>
train_set, valid_set, test_set = cPickle.load(f)
File "C:\Users\MAC\Anaconda\lib\gzip.py", line 268, in read
self._read(readsize)
File "C:\Users\MAC\Anaconda\lib\gzip.py", line 320, in _read
self._add_read_data( uncompress )
File "C:\Users\MAC\Anaconda\lib\gzip.py", line 338, in _add_read_data
self.extrabuf = self.extrabuf[offset:] + data
MemoryError
I really have no idea,is it because the memory of my computer is too small? it is on windows 7,32 bits
I suspect the problem to be Spyder in this case.
As to why, I have no idea but either the process isn't allowed to allocate enugh memory outside of it's own script or it simply gets stuck in a loop some how.
Try running your code without Spyder by pasting your code into myscript.py for instance and open a terminal and navigate to the folder where you saved your script and run python myscript.py and see if that works or gives the same output.
This is based on a conversation in the comments above.

Categories

Resources