Google Drive indexableText for a video in Python - python

I am trying to add indexable text to a video already in drive. From the Drive SDK Docs I used the Patch method.
def add_indexable_text(service, file_id, text_to_index):
try:
file = {'indexableText': {'text': text_to_index}}
updated_file = service.files().patch(
fileId = file_id,
body = file,
fields = 'indexableText').execute()
return updated_file
except errors.HttpError, error:
print 'An error occurred: %s' % error
return None
I'm not seeing any errors in the terminal but when I search in drive for the metadata text there are no results. I've tried waiting for a while but that didn't seem to help/matter. The video says it was updated when I ran the script so there's something. Thanks for any help you can provide.
Update: It seems I can only add indexableText to a video once but not change it afterward.

The code looks fine to me. Try using the "try it" function of the docs, does that work?
https://developers.google.com/drive/v2/reference/files/patch
Maybe the request went through but failed, which causes no HttpError.
What's the return value from a typical call?

Related

Python Github update file throws UnknownObjectException (404)

I am trying to update the contents of a file on github with the following code
file = repo.get_contents('test.csv', ref="main")
data = file.decoded_content.decode("utf-8")
data += "\n test;test;test"
repo.update_file(file.path, "automatic update", data, file.sha, branch='main')
It returns a cryptic error stack with this last line: github.GithubException.UnknownObjectException: 404 {"message": "Not Found", "documentation_url": "https://docs.github.com/rest/reference/repos#create-or-update-file-contents"}
the get-method seems to work, as it allows me to print out the original content of the file. Any pointers, why the update_file method is not working?
TIA!

AttributeError: 'dict' object has no attribute 'append' Trying to write to .JSON file

I have a script where I am trying to write to a .JSON file called alerted_comments.json
I had this working on Windows, but when I have moved it to Ubuntu I am getting the error in the title.
I am kind of new at this and am a little stuck. I know that its an issue with lists and dictionaries but I cannot figure it out. Any help would be appreciated
I am using python 3.6 on Ubuntu.
My current code related to this problem is here.
with open(save_path, 'r') as fp:
alerted_comments = json.load(fp)
for comment in comment_stream:
if comment.id in alerted_comments:
continue
if comment.author: # if comment author hasn't deleted
if comment.author.name in ignore_users:
continue
alerted_comments.append(comment.id)
if len(alerted_comments) > 100:
alerted_comments = alerted_comments[-100:]
with open(save_path, 'w') as fp:
json.dump(alerted_comments, fp)
else:
# You'll probably want to be more discerning than "not 200",
# but that's fine for now.
raise SlackError('Request to Slack returned an error %s, the response is:\n%s' % (response.status_code, response.text))
if __name__ == '__main__':
while True:
try:
main(save_path='alerted_comments.json')
except Exception as e:
print('There was an error: {}'.format(str(e)))
time.sleep(60) # wait for 60 seconds before restarting
What is meant to happen is, The script reads a keyword, and then puts that comment id of the keyword into the alerted_comments.json so it remembers and does not keep repeating the same keyword.
From an error we can find that we are working with dict instance when list was assumed, so the problem is in passed JSON or in our assumption about its structure.
From conversation it becomes clear that initial JSON has
{}
empty object literal in its contents which becomes Python dict after deserialization with json.load, so if it should be an empty array instead we can replace contents with
[]

Downloading Image with Python Telegram API

I followed their brief tutorial on downloading an image but I'm encountering an exception:
telegram.photosize.PhotoSize object at ... is not JSON serializable
the function for catching the images looks like this:
def photo(bot, update):
file_id = update.message.photo[-1]
newFile = bot.getFile(file_id)
newFile.download('test.jpg')
bot.sendMessage(chat_id=update.message.chat_id, text="download succesfull")
photo_handler = MessageHandler(Filters.photo, photo)
dispatcher.add_handler(photo_handler)
The Exception occurs while getting the file.
I have tried all kinds of files however im was not succesful with the download.
At this point I have no idea what I'm doing wrong and can't find any solution on the net.

Python webbrowser - Check if browser is available (nothing happens when opening webpage over an SSH connection)

Is there a way to detect whether there is a browser available on the system on which the script is run? Nothing happens when running the following code on a server:
try:
webbrowser.open("file://" + os.path.realpath(path))
except webbrowser.Error:
print "Something went wrong when opening webbrowser"
It's weird that there's no caught exception, and no open browser. I'm running the script from command line over an SSH-connection, and I'm not very proficient in server-related stuff, so there may be another way of detecting this that I am missing.
Thanks!
Checkout the documentation:
webbrowser.get([name])
Return a controller object for the browser type name. If name is empty, return a controller for a default browser appropriate to the caller’s environment.
This works for me:
try:
# we are not really interested in the return value
webbrowser.get()
webbrowser.open("file://" + os.path.realpath(path))
except Exception as e:
print "Webbrowser error: " % e
Output:
Webbrowser error: could not locate runnable browser

String error in my python api wrapper class

I'm writing an API wrapper to a couple of different web services.
I have a method that has an article url, and I want to extract text from it using alchemyapi.
def extractText(self):
#All Extract Text Methods ---------------------------------------------------------//
#Extract page text from a web URL (ignoring navigation links, ads, etc.).
if self.alchemyapi == True:
self.full_text = self.alchemyObj.URLGetText(self.article_link)
which goes to the following code in the python wrapper
def URLGetText(self, url, textParams=None):
self.CheckURL(url)
if textParams == None:
textParams = AlchemyAPI_TextParams()
textParams.setUrl(url)
return self.GetRequest("URLGetText", "url", textParams)
def GetRequest(self, apiCall, apiPrefix, paramObject):
endpoint = 'http://' + self._hostPrefix + '.alchemyapi.com/calls/' + apiPrefix + '/' + apiCall
endpoint += '?apikey=' + self._apiKey + paramObject.getParameterString()
handle = urllib.urlopen(endpoint)
result = handle.read()
handle.close()
xpathQuery = '/results/status'
nodes = etree.fromstring(result).xpath(xpathQuery)
if nodes[0].text != "OK":
raise 'Error making API call.'
return result
However I get this error ---
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "text_proc.py", line 97, in __init__
self.alchemyObj.loadAPIKey("api_key.txt");
File "text_proc.py", line 115, in extractText
if self.alchemyapi == True:
File "/Users/Diesel/Desktop/AlchemyAPI.py", line 502, in URLGetText
return self.GetRequest("URLGetText", "url", textParams)
File "/Users/Diesel/Desktop/AlchemyAPI.py", line 618, in GetRequest
raise 'Error making API call.'
I know I'm somehow passing the url string to the api wrapper in a faulty format, but I can't figure out how to fix it.
The information provided is not actually very helpful to diagnose or solve the problem. Have you considered taking a look at the response from the server? You might inspect a complete traffic log using Fiddler.
Additionally, the SDK provided by Alchemy doesn't seem to be of - cough, cough - the greatest quality. Since it really consists only of around 600 lines of source code, I'd consider writing a shorter, more robust / pythonic / whatever SDK.
I might also add that right now, even the on-site demo at the Alchemy web site is failing, so maybe your problem is related to that. I really suggest taking a look at the traffic.
You should raise Exception or a subclass thereof, instead of a string.
You're getting the error because your function GetRequest() raising a string as an exception:
if nodes[0].text != "OK":
raise 'Error making API call.'
If that's not what you want, you have two options:
You can have the function return the string or None, or
You can pass the error message to a real subclass of Exception (as suggested by knutin)
In either case, if you are assigning that return value to a variable, you can handle it accordingly. Here is an example:
Option 1
Let's assume you decide to have GetRequest() return None:
def URLGetText(self, url, textParams=None):
self.CheckURL(url)
if textParams == None:
textParams = AlchemyAPI_TextParams()
textParams.setUrl(url)
# Capture the value of GetRequest() before returning it
retval = self.GetRequest("URLGetText", "url", textParams)
if retval is None:
print 'Error making API call.' # print the error but still return
return retval
def GetRequest(self, apiCall, apiPrefix, paramObject):
# ...
if nodes[0].text != "OK":
return None
return result
This option is a little ambiguous. How do you know that it was really an error, or the return value truly was None?
Option 2
This is probably the better way to do it:
First create an subclass of Exception:
class GetRequestError(Exception):
"""Error returned from GetRequest()"""
pass
Then raise it in GetRequest()`:
def URLGetText(self, url, textParams=None):
self.CheckURL(url)
if textParams == None:
textParams = AlchemyAPI_TextParams()
textParams.setUrl(url)
# Attempt to get a legit return value & handle errors
try:
retval = self.GetRequest(apiCall, apiPrefix, paramObject)
except GetRequestError as err:
print err # prints 'Error making API call.'
# handle the error here
retval = None
return retval
def GetRequest(self, apiCall, apiPrefix, paramObject):
# ...
if nodes[0].text != "OK":
raise GetRequestError('Error making API call.')
return result
This way you're raising a legitimate error when GetRequest() doesn't return the desired result, and then you can handle the error using a try..except block and optionally print the error, stop the program there, or keep going (which is what I think you want to do based on your question).
This is Shaun from AlchemyAPI. We just posted a new version of the python SDK that raises exceptions properly. You can get it here http://www.alchemyapi.com/tools/.
If you have any other feedback about the SDK, please message me. Thanks for using our NLP service.

Categories