This is my script to post a picture on my facebook page:
import facebook
def add_static_image_to_audio(text, media):
page_access_token = "token"
graph = facebook.GraphAPI(page_access_token)
facebook_page_id = "1234567890"
photo = open('example.jpg', 'rb')
graph.put_object(facebook_page_id, "photos", message=text, file=photo.read())
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Simple Python script to add a static image to an audio to make a video")
parser.add_argument("text", help="The text")
parser.add_argument("media", help="image")
args = parser.parse_args()
add_static_image_to_audio(args.text, args.media)
This error code occurs when i run the script above:
Traceback (most recent call last):
File "C:\xampp\htdocs\laravel\storage\app\fb.py", line 19, in <module>
add_static_image_to_audio(args.text, args.media)
File "C:\xampp\htdocs\laravel\storage\app\fb.py", line 11, in add_static_image_to_audio
graph.put_object(facebook_page_id, "photos", message=text, file=photo)
File "C:\Users\Linus\AppData\Local\Programs\Python\Python310\lib\site-packages\facebook\__init__.py", line 189, in put_object
return self.request(
File "C:\Users\Linus\AppData\Local\Programs\Python\Python310\lib\site-packages\facebook\__init__.py", line 313, in request
raise GraphAPIError(result)
facebook.GraphAPIError: (#324) Requires upload file
How do i have to call the file so this problem stops occuring? The example.jpg used here is in the same directory as the script.
Related
I'm just trying to create a simple speech to text transcriber using the openai whisper module and streamlit for web application but having some problems.
It is giving me error
Traceback (most recent call last):
File "C:\Users\Satyam Singh\AppData\Local\Programs\Python\Python310\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "C:\Users\Satyam Singh\Desktop\Python Project\app.py", line 19, in <module>
transcription = model.transcribe(audio_file)
File "C:\Users\Satyam Singh\AppData\Local\Programs\Python\Python310\lib\site-packages\whisper\transcribe.py", line 84, in transcribe
mel = log_mel_spectrogram(audio)
File "C:\Users\Satyam Singh\AppData\Local\Programs\Python\Python310\lib\site-packages\whisper\audio.py", line 112, in log_mel_spectrogram audio = torch.from_numpy(audio)
**TypeError: expected np.ndarray (got NoneType)**
Here's my code
import streamlit as st
import whisper
from audio_recorder_streamlit import audio_recorder
# App Title Name
st.title("Speech to Text")
# uploading an audio file
# audio_file = st.file_uploader("Upload Audio", type=["wav","mp3","m4a"])
audio_file = audio_recorder()
if audio_file:
st.audio(audio_file, format="audio/wav")
model = whisper.load_model("base")
st.text("Whisper Model Loaded")
transcription = model.transcribe(audio_file)
print(transcription['text'])
if st.sidebar.button("Transcribe Audio"):
if audio_file is not None:
st.sidebar.success("Transcribing Audio")
transcription = model.transcribe(audio_file.name)
st.sidebar.success("Transcription Complete")
st.text(transcription["text"])
else:
st.sidebar.error("Please Upload an Audio File")
I want something like Baseten
I want this code to work or something more innovative which works same way like this one or Baseten.
I have this script from a few months ago which was working fine, but right now it gives me a weird error. The script is a simple one that extract URLs from emails.
it is working correctly in my test env but when I export it as an exe file it throws this error:
C:\Users\tyagi\Desktop\Localization_Download.exe
Extracting download links from outlook
Traceback (most recent call last):
File "main.py", line 62, in <module>
File "urlextract\urlextract_core.py", line 97, in __init__
File "urlextract\cachefile.py", line 61, in __init__
File "urlextract\cachefile.py", line 88, in _get_default_cache_file_path
urlextract.cachefile.CacheFileError: Default cache file does not exist
'C:\Users\tyagi\AppData\Local\Temp\_MEI146482\urlextract\data\tlds-alpha-by-domain.txt'!
[7456] Failed to execute script 'main' due to unhandled exception!
This is the script:
##############################################################
# interacting with outlook to fetch the URL & download all the files
#############################################################
print("Extracting download links from outlook")
from win32com.client import Dispatch
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
root_folder = outlook.Folders.Item(2)
inbox_folder = root_folder.Folders.Item(2)
localisation_folder = inbox_folder.Folders['localisation']
messages = localisation_folder.items
bodylist = []
for mail in messages:
body_content = mail.body
bodylist.append(body_content)
####### exporting all outlook emails as a text file
with open("Emailfile.txt", 'w') as output:
for row in bodylist:
output.write(str(row) + '\n')
####### extracting target links from that text file
from urlextract import URLExtract
extractor = URLExtract()
finalUrlList = []
with open("Emailfile.txt") as file:
for line in file:
urls = extractor.find_urls(line,True)
finalUrlList.append(urls)
from pandas import DataFrame
df = DataFrame(finalUrlList,columns=['download urls'])
df = df[df['download urls'].notna()]
df.reset_index(drop=True, inplace=True)
running it as an administrator is not an option
In file catchefile.py line 73 change:
return os.path.join(os.path.dirname(__file__), self._DATA_DIR)
to
return '' #os.path.join(os.path.dirname(__file__), self._DATA_DIR)
and insert to path of main file this downloaded filetext: https://data.iana.org/TLD/tlds-alpha-by-domain.txt
How do I download a file from googledrive?
I am using pydrive using the link.
#https://drive.google.com/open?id=DWADADDSASWADSCDAW
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
gdrive_file = drive.CreateFile({'id': 'id=DWADADDSASWADSCDAW'})
gdrive_file.GetContentFile('DWADSDCXZCDWA.zip') # Download content file.
Error:
raceback (most recent call last):
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\oauth2client\clientsecrets.py", line 121, in _loadfile
with open(filename, 'r') as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'client_secrets.json'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 386, in LoadClientConfigFile
client_type, client_info = clientsecrets.loadfile(client_config_file)
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\oauth2client\clientsecrets.py", line 165, in loadfile
return _loadfile(filename)
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\oauth2client\clientsecrets.py", line 125, in _loadfile
exc.strerror, exc.errno)
oauth2client.clientsecrets.InvalidClientSecretsError: ('Error opening file', 'client_secrets.json', 'No such file or directory', 2)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Hoxton/123/pyu_test.py", line 8, in <module>
gdrive_file.GetContentFile('PyUpdater+App-win-1.0.zip') # Download content file.
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\files.py", line 210, in GetContentFile
self.FetchContent(mimetype, remove_bom)
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\files.py", line 42, in _decorated
self.FetchMetadata()
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 57, in _decorated
self.auth.LocalWebserverAuth()
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 113, in _decorated
self.GetFlow()
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 443, in GetFlow
self.LoadClientConfig()
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 366, in LoadClientConfig
self.LoadClientConfigFile()
File "C:\Users\Hoxton\AppData\Local\Continuum\miniconda3\lib\site-packages\pydrive\auth.py", line 388, in LoadClientConfigFile
raise InvalidConfigError('Invalid client secrets file %s' % error)
pydrive.settings.InvalidConfigError: Invalid client secrets file ('Error opening file', 'client_secrets.json', 'No such file or directory', 2)
Process finished with exit code 1
Try the provided sample code in the documentation.
The Drive API allows you to download files that are stored in Google
Drive. Also, you can download exported versions of Google Documents
(Documents, Spreadsheets, Presentations, etc.) in formats that your
app can handle. Drive also supports providing users direct access to a
file via the URL in the webViewLink property.
Here is the code snippet:
file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print "Download %d%%." % int(status.progress() * 100)
This works for me:
from google_drive_downloader import GoogleDriveDownloader as gdd
gdd.download_file_from_google_drive(file_id='1z8e2CnvrX8ZSu2kk0QgiFWurOKMr0', dest_path='E:/model.h5')
Source: https://newbedev.com/python-download-files-from-google-drive-using-url
Hey I know it's a bit late to answer, but it might still be helpful to someone.
I had a similar problem with G-sheets, the problem here is that there might be multiple formats to download the file in and you're not specifying which one you want.To do this you need to add the mimetype parameter to the GetContentFile Method. Like so:
gdrive_file.GetContentFile('DWADSDCXZCDWA.zip', mimetype = 'application/zip')
Note that there are multiple mimetypes for zip files and that the mimetype and extension need to agree. So you need to know which one to use, or just try out different ones if you don't. Here's a handy list:
application/x-compressed
application/x-zip-compressed
application/zip
multipart/x-zip
Furthermore, if you actually access the metadata of the file you can have a peek at all the types of formats you can export it in under 'exportLinks'. There will be a dict with mimetypes and the associated links.
I have built a scraper to retrieve concert data from songkick by using their api. However, it takes a lot of time to retrieve all the data from these artists. After scraping for approximately 15 hours the script is still running but the JSON file doesn’t change anymore. I interrupted the script and I checked if I could access my data with TinyDB. Unfortunately I get the following error. Does anybody know why this is happening?
Error:
('cannot fetch url', 'http://api.songkick.com/api/3.0/artists/8689004/gigography.json?apikey=###########&min_date=2015-04-25&max_date=2017-03-01')
8961344
Traceback (most recent call last):
File "C:\Users\rmlj\Dropbox\Data\concerts.py", line 42, in <module>
load_events()
File "C:\Users\rmlj\Dropbox\Data\concerts.py", line 27, in load_events
print(artist)
File "C:\Python27\lib\idlelib\PyShell.py", line 1356, in write
return self.shell.write(s, self.tags)
KeyboardInterrupt
>>> mydat = db.all()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
mydat = db.all()
File "C:\Python27\lib\site-packages\tinydb\database.py", line 304, in all
return list(itervalues(self._read()))
File "C:\Python27\lib\site-packages\tinydb\database.py", line 277, in _read
return self._storage.read()
File "C:\Python27\lib\site-packages\tinydb\database.py", line 31, in read
raw_data = (self._storage.read() or {})[self._table_name]
File "C:\Python27\lib\site-packages\tinydb\storages.py", line 105, in read
return json.load(self._handle)
File "C:\Python27\lib\json\__init__.py", line 287, in load
return loads(fp.read(),
MemoryError
below you can find my script
import urllib2
import requests
import json
import csv
import codecs
from tinydb import TinyDB, Query
db = TinyDB('events.json')
def load_events():
MIN_DATE = "2015-04-25"
MAX_DATE = "2017-03-01"
API_KEY= "###############"
with open('artistid.txt', 'r') as f:
for a in f:
artist = a.strip()
print(artist)
url_base = 'http://api.songkick.com/api/3.0/artists/{}/gigography.json?apikey={}&min_date={}&max_date={}'
url = url_base.format(artist, API_KEY, MIN_DATE, MAX_DATE)
# url = u'http://api.songkick.com/api/3.0/search/artists.json?query='+artist+'&apikey=WBmvXDarTCEfqq7h'
try:
r = requests.get(url)
resp = r.json()
if(resp['resultsPage']['totalEntries']):
results = resp['resultsPage']['results']['event']
for x in results:
print(x)
db.insert(x)
except:
print('cannot fetch url',url);
load_events()
db.close()
print ("End of script")
MemoryError is a built in Python exception (https://docs.python.org/3.6/library/exceptions.html#MemoryError) so it looks like the process is out of memory and this isn't really related to Songkick.
This question probably has the information you need to debug this: How to debug a MemoryError in Python? Tools for tracking memory use?
I am new to INDD CC Server. I have Implemented Indesign server running on Windows. I need to convert IDML to PDF but having issues.
I have used SimpleIDML Python library to manipulate Adobe(r) IDML(r) files.
My sample script is
I2P.py
from simple_idml.indesign import indesign
idml_file = "/home/user/Project/EPS/media/test/2-idml/test001.idml"
indd_file = "/home/user/Project/EPS/media/test/InDesigndocument/test001.indd"
url_path = "http://192.168.1.1:12345/"
client_dir = "/home/user/Project/EPS/media/source"
server_dir = "/home/user/Project/EPS/media/server"
response = indesign.save_as(indd_file, [{
"fmt": "pdf",
"params": {"colorSpace": "CMYK"},
}],
url_path,
client_dir,
server_dir)[0]
with open("my_file.pdf", "w+") as f:
f.write(response)
In documentation :
response = indesign.save_as("/path_to_file.indd", [{
"fmt": "pdf",
"params": {"colorSpace": "CMYK"},
}],
"http://url-to-indesign-server:port",
"/path/to/client/workdir",
"/path/to/indesign-server/workdir")[0]
When i run I2P script throws me error as :
Traceback (most recent call last):
File "ItoP.py", line 12, in <module>
server_path)[0]
File "/home/user/eps2_env/local/lib/python2.7/site-packages/simple_idml/indesign/indesign.py", line 71, in new_func
logger, logger_extra)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/simple_idml/indesign/indesign.py", line 180, in save_as
responses = map(lambda fmt: _save_as(fmt), dst_formats_params)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/simple_idml/indesign/indesign.py", line 180, in <lambda>
responses = map(lambda fmt: _save_as(fmt), dst_formats_params)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/simple_idml/indesign/indesign.py", line 149, in _save_as
response = cl.service.RunScript(params)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/suds/client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/suds/client.py", line 602, in invoke
result = self.send(soapenv)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/suds/client.py", line 649, in send
result = self.failed(binding, e)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/suds/client.py", line 702, in failed
r, p = binding.get_fault(reply)
File "/home/user/eps2_env/local/lib/python2.7/site-packages/suds/bindings/binding.py", line 265, in get_fault
raise WebFault(p, faultroot)
suds.WebFault: Server raised fault: 'The specified script file can not be found: /home/user/Project/EPS/media/server/tmp9LVUWj/save_as.jsx'
Manually i can see dynamically created dir tmp9LVUWj inside server dir. Server path expecting on same time.
Not able to figure out how to set indesign-server/workdir and access in code and how to solve ? I have spend much time on this and not able find help or example code.
Or is there other python package to convert from IDML to PDF.
Thanks in advance
You wrote,
Manually I can see dynamically created dir tmp9LVUWj inside server
dir.
That is true, but that is not the error. It is stating that it cannot find a JSX file named save_as.jsx within that directory. Is that in fact the name of the JSX file that you were intending to place there, or the file that is residing there now?