Importing images from Github to Colab - github

I am having trouble importing my own images to https://colab.research.google.com/github/vijishmadhavan/Light-Up/blob/master/ArtLine.ipynb#scrollTo=eOhPqC6fysD4.
I am able to execute the sample images (e.g., https://wallpapercave.com/wp/wp2504860.jpg), but when I copy the same image and put it into my own Github repository (https://github.com/thiirane/Artline_images/blob/main/wp2504860.jpg), I get this error.
Here is the Code
#url = 'https://wallpapercave.com/wp/wp2504860.jpg' ##param {type:"string"}
url='https://github.com/thiirane/Artline_images/blob/main/wp2504860.jpg'##param {type:"string"}
from google.colab import files
from PIL import Image
from IPython.display import Image
#uploaded = files.upload()
response = requests.get(url)
img= PIL.Image.open(BytesIO(response.content)).convert("RGB")
img_t = T.ToTensor()(img)
img_fast = Image(img_t)
show_image(img_fast, figsize=(8,8), interpolation='nearest');
Here is the error:
UnidentifiedImageError Traceback (most recent call last)
<ipython-input-18-5d0fa6dc025f> in <module>()
8 response = requests.get(url)
9
---> 10 img= PIL.Image.open(BytesIO(response.content)).convert("RGB")
11 img_t = T.ToTensor()(img)
12 img_fast = Image(img_t)
/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode)
2860 warnings.warn(message)
2861 raise UnidentifiedImageError(
-> 2862 "cannot identify image file %r" % (filename if filename else fp)
2863 )
2864
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7fb88126f0f8>
I would be grateful for your help. It is likely something that I am not doing to allow Colab to access my repository.

It's because the URL is not the direct download link. Use this instead.
import requests
from io import BytesIO
from PIL import Image
url = 'https://raw.githubusercontent.com/thiirane/Artline_images/main/wp2504860.jpg'
page = requests.get(url)
Image.open(BytesIO(page.content))
Or you could use git to download your repository containing images.
!git clone https://github.com/thiirane/Artline_images.git images
from PIL import Image
Image.open('images/wp2504860.jpg')

Related

Libre office configuration file bootstrap.ini corrupt

I am using the libreoffice-convert package to convert a Word file into PDF. But when I try to convert I get this error. How do I fix this? I have installed LibreOffice 7.0.5
Console log is showing this error:
'C:\\Program Files\\LibreOffice\\program\\soffice.exe -env:UserInstallation=file://C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F --headless --convert-to .pdf --outdir C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe\\source'
Try this, you will probably need administrator rights.
Locate and copy your orignal file, for example to "bootstrap.ini.org", in the same directory1.
Open the file and replace its contents with this, which is a copy of my file:
[Bootstrap]
InstallMode=<installmode>
ProductKey=LibreOffice 7.0
UserInstallation=$SYSUSERCONFIG/LibreOffice/4
Another option is to re-install or repair the installation.
Note 1: This copy is just in case you need to revert.
//let data = await fs.promises.readFile(path_to_excel_file);
let data = fs.readFileSync(path_to_excel_file)
let pdfFile = await libreConvert(data, '.pdf', undefined);
await fs.promises.writeFile(`${__dirname}/${docName}.pdf`, pdfFile);
res.download(`${__dirname}/${docName}.pdf`)
It will works File.
Even If don't work then follow
below step:
Add this line 14 after instalDir
const installDir = tmp.dirSync({prefix: 'soffice', unsafeCleanup: true, ...tmpOptions});
const posixInstallDir = installDir.name.split(path.sep).join(path.posix.sep);
then Replace commant
let command = `${results.soffice} --headless --convert-to ${format}`;
That's it..
-env:UserInstallation needs to be in URI form.
Note: also that you using file:// this should be file:/// see File URI scheme
-env:UserInstallation=file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F
>>> from pathlib import Path
>>> def get_posix(mypath) -> str:
>>> p = Path(mypath)
>>> return p.as_posix()
>>> tmp = "C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F"
>>> get_posix(tmp)
'C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'
or
>>> from pathlib import Path
>>> tmp = Path("C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F")
>>> tmp.as_uri()
'file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'

ERROR: blob.download_to_filename, return an empty file and raise error

I'm trying to download the *.tflite model on Google Cloud Storage to my Rapberry Pi 3B+ using the code as follows:
export_metadata = response.metadata
export_directory = export_metadata.export_model_details.output_info.gcs_output_directory
model_dir_remote = export_directory + remote_model_filename # file path on Google Cloud Storage
model_dir = os.path.join("models", model_filename) # file path supposed to store locally
blob = bucket.blob(model_dir_remote)
blob.download_to_filename(model_dir)
However, this returns an empty file in my target directory locally, and meanwhile, raise an error:
# ERROR: google.resumable_media.common.InvalidResponse: ('Request failed with status code', 404,
# 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
# ERROR: google.api_core.exceptions.NotFound: 404
# GET https://storage.googleapis.com/download/storage/v1/b/ao-example/o/
# gs%3A%2F%2Fao-example%2Fmodel-export%2Ficn%2Fedgetpu_tflite-Test_Model12-2020-11-16T07%3A54%3A27.187Z%2Fedgetpu_model.tflite?alt=media:
# ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
I guaranteed the corresponding authority to the service account. What confuses me is that when I use gsutil command, it works:
gsutil cp gs://ao-example/model-export/icn/edgetpu_model.tflite models/
Is anyone encountering the same problem? Is there any error in my code? Your help will be greatly appreciated!
I used the following code:
from google.cloud import storage
from google.cloud import automl
from google.cloud.storage import Blob
client = storage.Client(project="semesterproject-294707")
bucket_name = 'ao-example'
bucket = client.get_bucket(bucket_name)
model_dir_remote = "gs://ao-example/model-export/icn/edgetpu_tflite-Test_Model13-2020-11-18T15:03:42.620Z/edgetpu_model.tflite"
blob = Blob(model_dir_remote, bucket)
with open("models/edgetpu_model13.tflite", "wb") as file_obj:
blob.download_to_file(file_obj)
This raises the same error, and return an empty file also... Still, I can use gsutil cp command to download the file...
(Edited on 06/12/2020)
The info of model generated:
export_model_details {
output_info {
gcs_output_directory: "gs://ao-example/model-export/icn/edgetpu_tflite-gc14-2020-12-06T14:43:18.772911Z/"
}
}
model_gcs_path: 'gs://ao-example/model-export/icn/edgetpu_tflite-gc14-2020-12-06T14:43:18.772911Z/edgetpu_model.tflite'
model_local_path: 'models/edgetpu_model.tflite'
It still encounters the error:
google.api_core.exceptions.NotFound: 404 GET https://storage.googleapis.com/download/storage/v1/b/ao-example/o/gs%3A%2F%2Fao-example%2Fmodel-export%2Ficn%2Fedgetpu_tflite-gc14-2020-12-06T14%3A43%3A18.772911Z%2Fedgetpu_model.tflite?alt=media: ('Request failed with status code', 404, 'Expected one of', <HTTPStatus.OK: 200>, <HTTPStatus.PARTIAL_CONTENT: 206>)
Still, when I use gsutil cp command, it works:
gsutil cp model_gcs_path model_local_path
Edited on 12/12/2020
Soni Sol's method works! Thanks!!
I believe you should use something like this:
from google.cloud.storage import Blob
client = storage.Client(project="my-project")
bucket = client.get_bucket("my-bucket")
blob = Blob("file_on_gcs", bucket)
with open("/tmp/file_on_premise", "wb") as file_obj:
blob.download_to_file(file_obj)
Blobs / Objects
When using the client libraries the gs:// is not needed, also the name of the bucket is being passed twice on This Question they had a similar issue and got corrected.
please try with the following code:
from google.cloud import storage
from google.cloud import automl
from google.cloud.storage import Blob
client = storage.Client(project="semesterproject-294707")
bucket_name = 'ao-example'
bucket = client.get_bucket(bucket_name)
model_dir_remote = "model-export/icn/edgetpu_tflite-Test_Model13-2020-11-18T15:03:42.620Z/edgetpu_model.tflite"
blob = Blob(model_dir_remote, bucket)
with open("models/edgetpu_model13.tflite", "wb") as file_obj:
blob.download_to_file(file_obj)

Problem with connect facebookads library for extract data from Facebook with Marketing API using Python

I want to get info about ad campaign. And I start from this code to get campaign name. and I get this error :
Traceback (most recent call last):
File "C:/Users/win7/PycharmProjects/API_Facebook/dd.py", line 2, in <module>
from facebookads.adobjects.adaccount import AdAccount
File "C:\Users\win7\AppData\Local\Programs\Python\Python37-32\lib\site-packages\facebookads\adobjects\adaccount.py", line 1582
def get_insights(self, fields=None, params=None, async=False, batch=None, pending=False):
^
SyntaxError: invalid syntax
^
What is may be reason? and if you want, can give code examples how can I get more info about campaign?
Click here to view image: code and error
If you're using Python 3.7, use async_, not only async.
import os, re
path = r"path facebookads"
python_files = []
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith(".py"):
python_files.append(os.path.join(dirpath, filename))
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename.endswith(".py"):
python_files.append(os.path.join(dirpath, filename))
for python_file in python_files:
with open(python_file, "r") as f:
text = f.read()
revised_text = re.sub("async", "async_", text)
with open(python_file, "w") as f:
f.write(revised_text)
They updated and renamed the library, now it's facebook_ads and async argument was renamed to is_async
Try updating facebookads:
$ pip install --upgrade facebookads
I'm using facebookads==2.11.4.
More info: https://pypi.org/project/facebookads/

OSError: cannot identify image file <_io.StringIO object at 0x00000000022810D8>

Use win8 and python3.4,I need to convert text to images.So I try to implement a himself.But I encounter a OSError.I try to use BytesIO instead of StringIO,it will pop error "OSError: cannot identify image file <_io.BytesIO object at xxxx>.
I still can't find the reason.
Codes as follow:
# -*- coding: utf-8 -*-
import os
import pygame
from io import StringIO,BytesIO
from PIL import Image
pygame.init()
text = u'This is a test text,test 123.'
font_path = "C:/windows/fonts/simsun.ttc"
im = Image.new("RGB",(300,50),(255,255,255))
font = pygame.font.Font(os.path.join(font_path),22)
rtext = font.render(text, True, (0,0,0),(255,255,255))
sio = StringIO()
print(sio.getvalue())
pygame.image.save(rtext, sio)
sio.seek(0)
#print(sio.getvalue())
line = Image.open(sio)
im.paste(line,(10,5))
im.show()
im.save("t1.png")
As is I get this error:
Traceback (most recent call last):
File "D:/mypython/learn/demo.py", line 19, in <module>
line = Image.open(sio)
File "D:\Python34\lib\site-packages\PIL\Image.py", line 2319, in open
% (filename if filename else fp))
OSError: cannot identify image file <_io.StringIO object at 0x00000000022810D8>
line = Image.open(sio)
As far as I am concerned, sio is still a StringIO(). If you are trying to open it as an image, try opening it with line = Image.open(name), where name is the actual name of the image, not a StringIO().

FacebookAds Python SDK AppID KeyError

from facebookads import FacebookSession
from facebookads import FacebookAdsApi
from facebookads.objects import (
AdUser,
Campaign
)
import json
import os
import pprint
pp = pprint.PrettyPrinter(indent=4)
this_dir = os.path.dirname(__file__)
config_filename = os.path.join(this_dir, 'config.json')
config_file = open(config_filename)
config = json.load(config_file)
config_file.close()
### Setup session and api objects
session = FacebookSession(
config['XXXXXXXXXXXXXX']--This is AppId,
config['XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX']--This is AppSecret,
config['XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX']--This is AccessToken,
)
api = FacebookAdsApi(session)
if __name__ == '__main__':
FacebookAdsApi.set_default_api(api)
print('\n\n\n********** Reading objects example. **********\n')
I try collect facebook-ads results cliks, page view etc. And this is my code part. If i run this code i have a this error:
Traceback (most recent call last):
File "/home/kerimcaner/PycharmProjects/facebook/deneme.py", line 23, in <module>
config[XXXXXXXXXXXXXXXXX],
KeyError: XXXXXXXXXXXXXXXXX
I check many times my appId so its true but code is not working.