os : windows 10 64bits
python: 3.7.3(anaconda)
# -*- coding: utf-8 -*-
from aip import AipSpeech
APP_ID = ''
API_KEY = 'xxx'
SECRET_KEY = 'yyy'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
# call "client.asr(get_file_content('01.wav'), 'wav', 16000)" will throw exception
results = client.asr(get_file_content('01.wav'), 'wav', 16000)
print(results)
Error messages
"""
Traceback (most recent call last):
File "baidu_speech_reg_api.py", line 18, in <module>
results = client.asr(get_file_content('01.wav'), 'wav', 16000)
File "C:\Users\yyyy\Anaconda3\envs\pyside2\lib\site-packages\aip\speech.py", line 78, in asr
return self._request(self.__asrUrl, data)
File "C:\Users\yyyy\Anaconda3\envs\pyside2\lib\site-packages\aip\base.py", line 90, in _request
params = self._getParams(authObj)
File "C:\Users\yyyy\Anaconda3\envs\pyside2\lib\site-packages\aip\base.py", line 190, in _getParams
params['access_token'] = authObj['access_token']
KeyError: 'access_token'
"""
I can use the same keys for ocr and image classification, but speech recognition always fail.
Related
I am trying to use Reddit's developer API to build a simple scraper that grabs posts and their replies in a target subreddit and produces JSON with the information.
I am getting a 404 error that I don't understand.
This is my code:
import praw
import json
def scrape(subreddit, limit):
r = praw.Reddit(user_agent='Reddit data organizer 1.0 by /u/reallymemorable', client_id='none of your business', client_secret='none of your business')
submissions = r.subreddit(subreddit).get_hot(limit=limit)
for submission in submissions:
data = {}
data['title'] = submission.title
data['score'] = submission.score
data['url'] = submission.url
data['author'] = str(submission.author)
data['subreddit'] = str(submission.subreddit)
data['num_comments'] = submission.num_comments
data['over_18'] = submission.over_18
data['selftext'] = submission.selftext
data['is_self'] = submission.is_self
data['name'] = submission.name
data['created_utc'] = submission.created_utc
data['permalink'] = submission.permalink
data['domain'] = submission.domain
data['id'] = submission.id
data['kind'] = submission.kind
json.dumps(data)
scrape('https://www.reddit.com/r/funny/', 25)
When I run it, I get this:
reallymemorable#Christians-MBP Desktop % python3 fetch-data-subreddit.py
Traceback (most recent call last):
File "/Users/reallymemorable/Desktop/fetch-data-subreddit.py", line 26, in <module>
scrape('https://www.reddit.com/r/augmentedreality/comments/yv7sn8/ar_maximum_distance/', 25)
File "/Users/reallymemorable/Desktop/fetch-data-subreddit.py", line 6, in scrape
submissions = r.subreddit(subreddit).get_hot(limit=limit)
File "/opt/homebrew/lib/python3.9/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
self._fetch()
File "/opt/homebrew/lib/python3.9/site-packages/praw/models/reddit/subreddit.py", line 583, in _fetch
data = self._fetch_data()
File "/opt/homebrew/lib/python3.9/site-packages/praw/models/reddit/subreddit.py", line 580, in _fetch_data
return self._reddit.request(method="GET", params=params, path=path)
File "/opt/homebrew/lib/python3.9/site-packages/praw/util/deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "/opt/homebrew/lib/python3.9/site-packages/praw/reddit.py", line 941, in request
return self._core.request(
File "/opt/homebrew/lib/python3.9/site-packages/prawcore/sessions.py", line 330, in request
return self._request_with_retries(
File "/opt/homebrew/lib/python3.9/site-packages/prawcore/sessions.py", line 266, in _request_with_retries
raise self.STATUS_EXCEPTIONS[response.status_code](response)
prawcore.exceptions.NotFound: received 404 HTTP response
r.subreddit(subreddit) - subreddit should just be the name of the subreddit e.g. "funny" and not the full URL.
See the docs here: https://praw.readthedocs.io/en/stable/getting_started/quick_start.html#obtain-a-subreddit
During a small test to learn how to run a small server, the method 'start' returns an error when I tried to start the server afet including the endpoint and some variables:
from opcua import Server
import datetime
import time
my_server = Server()
url = 'opc.tcp//192.168.1.5:4841'
my_server.set_endpoint(url)
name = "OPCUA_TEST_Server"
addspace = my_server.register_namespace(name)
node = my_server.get_objects_node()
param = node.add_object(addspace, "Parameters")
t_text1 = param.add_variable(addspace, "Text 1", "Text_1")
i_int1 = param.add_variable(addspace, "myInteger1", 0)
b_bool1 = param.add_variable(addspace, "myBool1", False)
t_text1.set_writable()
i_int1.set_writable()
b_bool1.set_writable()
my_server.start()
print("Server started at {}".format(url))
print("At" + str(datetime.datetime.now()))
while True:
time.sleep(0.5)
And in line of
my_server.start()
Returns the following error:
Endpoints other than open requested but private key and certificate are not set.
Traceback (most recent call last):
File "C:/Users/a767611/Desktop/Repositorios/flexigrid/opc-ua-server/test-opc-ua-server.py", line 23, in <module>
my_server.start()
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\server\server.py", line 347, in start
raise exp
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\server\server.py", line 344, in start
self.bserver.start()
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\server\binary_server_asyncio.py", line 116, in start
self._server = self.loop.run_coro_and_wait(coro)
File "C:\Users\a767611\Anaconda3\lib\site-packages\opcua\common\utils.py", line 197, in run_coro_and_wait
return task.result()
File "C:\Users\a767611\Anaconda3\lib\asyncio\base_events.py", line 1393, in create_server
raise ValueError('Neither host/port nor sock were specified')
ValueError: Neither host/port nor sock were specified
Your endpoint URL is malformed.
It should be:
url = 'opc.tcp://192.168.1.5:4841'
note the missing colon after opc.tcp.
I got this error when I implemented from google.cloud import storage.
Traceback (most recent call last):
File "/mnt/apps/repo/oktested/oktested-backend/wsgi.py", line 1, in <module>
from ok_app import app as application
File "./ok_app/__init__.py", line 11, in <module>
from google.cloud import storage
File "/usr/lib/python3.6/site-packages/google/cloud/storage/__init__.py", line 38, in <module>
from google.cloud.storage.batch import Batch
File "/usr/lib/python3.6/site-packages/google/cloud/storage/batch.py", line 29, in <module>
from google.cloud import _helpers
File "/usr/lib/python3.6/site-packages/google/cloud/_helpers.py", line 33, in <module>
from google.protobuf import duration_pb2
File "/usr/lib64/python3.6/site-packages/google/protobuf/duration_pb2.py", line 69, in <module>
'__module__' : 'google.protobuf.duration_pb2'
TypeError: A Message class can only inherit from Message
unable to load app 1 (mountpoint='oktested') (callable not found or import error)
The code is:
from google.cloud import storage
creds = storage.Client.from_service_account_json('s-creds.json')
def uploadProfilePic(id, image_name, image):
filename = id + '__' + str(uuid.uuid4()) + '__' + image_name
dest_dir = app.config['S3_DIR'] + app.config['PROFILE_PIC_PATH']
filepath = os.path.join(dest_dir, filename)
image_data = re.sub('^data:image/.+;base64,', '', image)
img_data = base64.b64decode(image_data)
try:
if 'jpeg' in filename:
image_type = "image/jpeg"
elif 'png' in filename:
image_type = "image/png"
elif 'jpg' in filename:
image_type = "image/jpg"
# s3.Bucket(app.config['S3_BUCKET_NAME']).put_object(Key=filepath, Body=img_data, ACL=app.config['S3_ACL'], ContentType ='image/jpeg', CacheControl=app.config['S3_CACHE_CONTROL'])
bucket = creds.bucket(app.config['GCP_BUCKET_NAME'])
blob = bucket.blob(filepath)
blob.upload_from_string(img_data, content_type=image_type)
app.logger.debug("User::uploadProfilePic::SuccessfullyUploaded::{}".format(filepath))
return filepath
except Exception as e:
app.logger.error("User::uploadProfilePic:: {}". format(e))
return ''
I run the code on server using uwsgi. I get this error even after Restarting the service. Please help.
I found a workaround, I am now calling the google cloud methods only where I need it, not during the app initialization.
I set up a try catch in my code, but it appears that my exception was not correct because it did not seem to catch it.
I am using an exception from a module, and perhaps I didn't import it correctly? Here is my code:
import logging
import fhirclient.models.bundle as b
from fhirclient.server import FHIRUnauthorizedException
logging.disable(logging.WARNING)
def get_all_resources(resource, struct, smart):
'''Perform a search on a resource type and get all resources entries from all retunred bundles.\n
This function takes all paginated bundles into consideration.'''
if smart.ready == False:
smart.reauthorize
search = resource.where(struct)
bundle = search.perform(smart.server)
resources = [entry.resource for entry in bundle.entry or []]
next_url = _get_next_url(bundle.link)
while next_url != None:
try:
json_dict = smart.server.request_json(next_url)
except FHIRUnauthorizedException:
smart.reauthorize
continue
bundle = b.Bundle(json_dict)
resources += [entry.resource for entry in bundle.entry or []]
next_url = _get_next_url(bundle.link)
return resources
Now when i ran the code I got the following error:
Traceback (most recent call last):
File "code.py", line 79, in <module>
main()
File "code.py", line 42, in main
reports = get_all_resources(dr.DiagnosticReport, search, smart)
File "somepath/fhir_tools/resource.py", line 23, in get_all_resources
json_dict = smart.server.request_json(next_url)
File "/usr/local/lib/python3.6/dist-packages/fhirclient/server.py", line 153, in request_json
res = self._get(path, headers, nosign)
File "/usr/local/lib/python3.6/dist-packages/fhirclient/server.py", line 181, in _get
self.raise_for_status(res)
File "/usr/local/lib/python3.6/dist-packages/fhirclient/server.py", line 256, in raise_for_status
raise FHIRUnauthorizedException(response)
server.FHIRUnauthorizedException: <Response [401]>
Shouldn't my exception catch this?
I'm trying to deploy a python web server. Main function of following code is to generate a qrcode and transfer the image to binary file.
def generate_qrcode(date, user_id):
qr = qrcode.QRCode(
version=1,
error_correction=constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
base_string = config_default.configs.get('const').get('url') + '/check_in/'
generate_string = date + '#' +user_id
qr.add_data(base_string + generate_string, qrcode)
qr.make(fit=True)
img = qr.make_image()
return Image.fromqimage(img) # here is the place returns exception
Then post this binary file to a url.
def upload_qrcode(datetime, user_id):
url = "https://api.weixin.qq.com/cgi-bin/media/upload
access_token = get_access_token()
querystring = {"access_token":access_token,"type":"image"}
files = {"media":generate_qrcode(datetime,user_id)}
response = requests.post(url, params=querystring, files=files)
Here is the exception:
Traceback (most recent call last):
File "/Users/yudayan/Documents/myCode/pythonCode/nuobao/QRC_maker.py", line 58, in <module>
main()
File "/Users/yudayan/Documents/myCode/pythonCode/nuobao/QRC_maker.py", line 54, in main
print(upload_qrcode("sdf", "adsf"))
File "/Users/yudayan/Documents/myCode/pythonCode/nuobao/QRC_maker.py", line 47, in upload_qrcode
files = {"media":generate_qrcode(datetime,user_id)}
File "/Users/yudayan/Documents/myCode/pythonCode/nuobao/QRC_maker.py", line 32, in generate_qrcode
return Image.fromqimage(img)
File "/Users/yudayan/anaconda/lib/python3.6/site-packages/PIL/Image.py", line 2321, in fromqimage
return ImageQt.fromqimage(im)
File "/Users/yudayan/anaconda/lib/python3.6/site-packages/PIL/ImageQt.py", line 59, in fromqimage
if im.hasAlphaChannel():
File "/Users/yudayan/anaconda/lib/python3.6/site-packages/qrcode/image/pil.py", line 50, in __getattr__
return getattr(self._img, name)
AttributeError: 'Image' object has no attribute 'hasAlphaChannel'