Python Image Url Extraction - python

I am uploading an image to a wordpress site. How can I get the url of the image? The library is at this link. I am sharing the codes. https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.demo.SayHello
filename = 'C:\\Users\\Image_1.jpg'
prepare metadata
data = {
'name': 'Image_1.jpg',
'type': 'image/jpeg', # mimetype
}
read the binary file and let the XMLRPC library encode it into base64
with open(filename, 'rb') as img:
data['bits'] = xmlrpc_client.Binary(img.read())
response = client.call(media.UploadFile(data))
attachment_id = response['id']

Have a look at the docs you linked: https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.media.UploadFile
it says that the media.UploadFile method:
Returns: dict with keys id, file (filename), url (public URL), and type (MIME-type).
so you should be able to get the url of uploaded image in response["url"]

Related

Form Recognizer custom model fails with invalid file type `{"error":{"code":"1000","message":"Invalid input file."}}`

I have successfully trained a custom model for key value extraction, however any file or file type I use to evaluate the model is failing to return a result. So far I have tried both pdf and png files.
I have matched the query provided in the API docs to create my query but it still fails, any suggestions?
import requests
import json
import os
import pathlib
# path of file to evaluate
floc = 'path/to/file'
# extract file type
file_type = pathlib.Path(floc).suffix[1:]
# set headers with file type and our api key
headers = {
'Content-Type': f'application/{file_type}',
'Ocp-Apim-Subscription-Key': os.environ["AZURE_FORM_RECOGNIZER_KEY"]
}
# read in the file as binary to send
files = {'file': open(floc, 'rb')}
# post the file to be analysed
r = requests.post(
f'https://eastus.api.cognitive.microsoft.com/formrecognizer/v2.1/custom/models/{os.environ["MODEL_ID"]}/analyze',
headers=headers,
files=files
)
r
The result is 400 with the following error:
{"error":{"code":"1000","message":"Invalid input file."}}
A very similar query using the layout/analyze request works perfectly. I have also read this question that has the same error but from cURL but it has not helped.
I have fixed my problem but will leave my answer for any one else.
There were two main problems:
sending the pdf with files rather than data
using the default endpoint (https://eastus.api.cognitive.microsoft.com) rather than my own endpoint
The fix is found below:
import requests
import json
import os
import pathlib
# path of file to evaluate
floc = 'path/to/file'
# extract file type
file_type = pathlib.Path(floc).suffix[1:]
# set headers with file type and our api key
headers = {
'Content-Type': f'application/{file_type}',
'Ocp-Apim-Subscription-Key': os.environ["AZURE_FORM_RECOGNIZER_KEY"]
}
# post the file to be analysed
r = requests.post(
f'{endpoint}/formrecognizer/v2.1/custom/models/{os.environ["MODEL_ID"]}/analyze',
headers=headers,
data=open(floc, 'rb') # send binary of your file
)
r
You can find your own endpoint value by going on to the Azure instance for your form_recognizer:

How to get a file from a url and then read it as if it were local?

I have a jpg image that is stored at a url that I need to access and read the binary/byte data from.
I can get the file in Python by using:
import urllib3
http = urllib3.PoolManager()
url = 'link to jpg'
contents = http.request('GET' url)
Purely reading the data from this request with contents.data doesn't provide the correct binary but if I download the file and read it locally, I get the correct binary. But I cannot continue with reading the file contents as such:
with open(contents, "rb") as image:
f = image.read()
Using the bytes from the request doesn't work either:
with open(contents.data, "rb") as image:
f = image.read()
How can I treat the jpg from the url as if it were local so that I can read the binary correctly?
The result obtained in f when file is read locally and the result of contents.data is exactly the same.
import urllib3
http = urllib3.PoolManager()
url = 'https://tinyjpg.com/images/social/website.jpg'
contents = http.request('GET', url)
with open('website.jpg', "rb") as image:
f = image.read()
print(f==contents.data)
You can download the image from the link in the code and then run this code, you will receive output True which implies the data read from local image file is same as data read from website.

How can combine send_file() with another information (E.g., int) in 1 response using Flask

My problem is I'm trying to send to client and image with another additional information using Python with Flask.
I tried to use send_file(), but the issue is I can only send the image only and I can't find other ways to send the additional information with it.
I also tried to combine the image and info into JSON, but it seems that send_file() can't be serialized as JSON
def post(self):
img_path, score = self.get_result()
final_image = send_file(
img_path,
mimetype='image/jpg'
)
output = {'img': final_image, 'score': score}
return output
Is there any way that I can receive an image with additional results within 1 request from client?
You can consider either of these approaches:
Set extra information as cookie.
response = send_file(
img_path,
mimetype='image/jpg'
)
response.set_cookies('score', score)
Set additional response headers to contain extra information.
response = send_file(
img_path,
mimetype='image/jpg'
)
response.set_header('x-myapp-score', score)
Or encode the file contents in a JSON response. You can encode as base64 string or use Concise Binary Object Representation (Server-side library: https://github.com/brianolson/cbor_py, Client-side library: https://github.com/paroga/cbor-js)
from base64 import b64encode
import logging
logger = logging.getLogger(__name__)
def post(self):
# ...
output = {
'score': score
}
try:
with open(final_image, 'rb') as f:
content = f.read()
output['img'] = b64encode(content)
except TypeError, FileNotFoundError:
# handle default image ¯\_(ツ)_/¯
logger.exception('Failed to encode image file')
return output

How to create an image from binary data returned by a request to store and use in Django app?

I am using the Dropbox API Explorer - get_thumbnail to get a thumbnail of images stored following the get_thumbnail documentation
The response returns a blob in binary. I am attempting to create a image file to store as an imagefield on my django app's database.
I followed this Quickstart to create the image.
# get_thumbnail request
url = "https://content.dropboxapi.com/2/files/get_thumbnail"
# product_path is a variable storing path from list_folder
new_product_path = "{\"path\":\"/%s\"}" %(product_path)
headers = {
"Authorization": "Bearer <api_token_ommitted>",
"Dropbox-API-Arg": new_product_path
}
r = requests.post(url, headers=headers)
thumbnail = Image.open(BytesIO(r.content))
# album is foreign key for Album model
product = Product.objects.create(album=album, name=converted_name, image=converted_url, thumbnail=thumbnail)
print('Product has been created!')
The results of print(r.content):
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06\x07\x07\x06\x08\n\x10\n\n\t\t\n\x14\x0e\x0f\x0c\x10\x17\x14\x18\x18\x17\x14\x16\x16\x1a\x1d%\x1f\x1a\x1b#\x1c\x16\x16 , #&\')*)\x19\x1f-0-(0%()(\xff\xdb\x00C\x01\x07\x07\x07\n\x08\n\x13\n\n\x13(\x1a\x16\x1a((((((((((((((((((((((((((((((((((((((((((((((((((\xff\xc0\x00\x11\x08\x00$\x00#\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xc4\x00\x1f\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x11\x00\x02\x01\x02\x04\x04\x03\x04\x07\x05\x04\x04\x00\x01\x02w\x00\x01\x02\x03\x11\x04\x05!1\x06\x12AQ\x07aq\x13"2\x81\x08\x14B\x91\xa1\xb1\xc1\t#3R\xf0\x15br\xd1\n\x16$4\xe1%\xf1\x17\x18\x19\x1a&\'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe2\xe3\xe4\xe5\xe6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6b\x14QE\x00\x14QE\x00\x14QE\x00\x7f\xff\xd9'
I have tried to convert bytes data to image as follows, if your data in bytes format, I think following code will help you
bytes_data = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00'
with open("path/image.png", "wb") as f:
f.write(bytes_data)
Add the new path of image to image field.
For more details refer following
How to generate temporary file in django and then destroy
Temporary file with specific file extension in Python 3
Programmatically saving image to Django ImageField

Convert uploaded file to GIF and then POST to web service

I need to take an uploaded JPG from request.FILES, convert it to a GIF thumbnail and then POST it to a 3rd party web service.
import StringIO
import Image
import requests
img_file = request.FILES['files[]'] if request.FILES else None
#create the thumbnail
import StringIO
thumb_buffer = StringIO.StringIO()
im = Image.open(img_file)
im.thumbnail(settings.THUMBNAIL_SIZE)
im.save(thumb_buffer, "GIF")
thumb_buffer.seek(0)
thumb_contents = thumb_buffer.getvalue()
thumb_buffer.close()
#send file via POST request
thumb_upload_dict = {
'upload_file': (filename + '.gif', thumb_contents)}
print thumb_upload_dict
thumb_payload = {
'func': 'upload_file',
'base_id': new_asset.base_id,
'type': 'GIF',
'username': 'remote_admin',
'password': 'we1398fj'
}
r = requests.post(url, params=thumb_payload, files=thumb_upload_dict)
Unfortunately this doesn't work. When I try to view the image I get The image “http://theurl.com/gif_filename.gif” cannot be displayed because it contains errors.
I should note that if I just POST img_file without converting it, it works fine. I'm guessing the problem has to do with thumb_contents but I'm not totally sure.

Categories