alipalru
Posts: 2
Joined: Thu Mar 01, 2018 4:09 pm

question about line command argument

Thu Mar 01, 2018 4:40 pm

hello, i'm newbie in this forum.

I'm using google cloud vision to test how it works and I found a python code that works but
the image file to analyze is provided as a command line argument to the code

python code.py MIIEvQIBADANBgkq(Credentials google) imagen.png

the code is :

Code: Select all

from base64 import b64encode
from os import makedirs
from os.path import join, basename
from sys import argv
import json
import requests

ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'
RESULTS_DIR = 'jsons'
makedirs(RESULTS_DIR, exist_ok=True)

def make_image_data_list(image_filenames):
    """
    image_filenames is a list of filename strings
    Returns a list of dicts formatted as the Vision API
        needs them to be
    """
    img_requests = []
    for imgname in image_filenames:
        with open(imgname, 'rb') as f:
            ctxt = b64encode(f.read()).decode()
            img_requests.append({
                    'image': {'content': ctxt},
                    'features': [{
                        'type': 'TEXT_DETECTION',
                        'maxResults': 1
                    }]
            })
    return img_requests

def make_image_data(image_filenames):
    """Returns the image data lists as bytes"""
    imgdict = make_image_data_list(image_filenames)
    return json.dumps({"requests": imgdict }).encode()


def request_ocr(api_key, image_filenames):
    response = requests.post(ENDPOINT_URL,
                             data=make_image_data(image_filenames),
                             params={'key': 'AIzaSyBZILsRauBAu-be1WClq9kJZ0_w7w56XH8'},
                             headers={'Content-Type': 'application/json'})
    return response


if __name__ == '__main__':
    api_key, *image_filenames = argv[1:]
    if not api_key or not image_filenames:
        print("""
            Please supply an api key, then one or more image filenames

            $ python cloudvisreq.py api_key image1.jpg image2.png""")
    else:
        response = request_ocr(api_key, image_filenames)
        if response.status_code != 200 or response.json().get('error'):
            print(response.text)
        else:
            for idx, resp in enumerate(response.json()['responses']):
                # save to JSON file
                imgname = image_filenames[idx]
                jpath = join(RESULTS_DIR, basename(imgname) + '.json')
                with open(jpath, 'w') as f:
                    datatxt = json.dumps(resp, indent=2)
                    print("Wrote", len(datatxt), "bytes to", jpath)
                    f.write(datatxt)

                # print the plaintext to screen for convenience
                print("---------------------------------------------")
                t = resp['textAnnotations'][0]
                mensaje = t['description']
                print(mensaje[0:7])
How can I modify the code so that the image and the api_key do not have to enter them in the command line?

hopefully someone can give me some reference to start modifying the code.

I know that on the main code main I have to modify the lines.

[codeapi_key, *image_filenames = argv[1:]
if not api_key or not image_filenames:][/code]

and pass the arguments that will then use the functions to encrypt the image and create the json
but I'm kind of confused about how to get started.

thanks

User avatar
OutoftheBOTS
Posts: 659
Joined: Tue Aug 01, 2017 10:06 am

Re: question about line command argument

Thu Mar 01, 2018 9:05 pm

Easy api_key and image_filenames are the variables that the data from the command line is written to.

Code: Select all

api_key = #what ever your api_kay data is
image_filename = [#list of file names] 

alipalru
Posts: 2
Joined: Thu Mar 01, 2018 4:09 pm

Re: question about line command argument

Fri Mar 02, 2018 4:47 pm

Thank you, I try it but I have the following issue:

Image

I'm looking for
[Errno 13] Permission denied : '/'
but I can't find the solution.

the script is in the path
c:/pruebas
and the image is in
c:/pruebas/imagenes/patente.png


Maybe it's a problem about permissions.
or how to open the file (image)

any suggestions?. thanks

B.Goode
Posts: 6446
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: question about line command argument

Fri Mar 02, 2018 4:59 pm

the image is in
c:/pruebas/imagenes/patente.png
But you have coded it as being at /imagenes/patente.png


Maybe you simply need to omit the first '/'?



(Perhaps volunteer helpers in this Raspberry Pi Foundation forum have a reputation for being more knowledgeable or approachable than users of the Microsoft Windows Operating System that you are using... )

User avatar
mahjongg
Forum Moderator
Forum Moderator
Posts: 10932
Joined: Sun Mar 11, 2012 12:19 am
Location: South Holland, The Netherlands

Re: question about line command argument

Fri Mar 02, 2018 5:02 pm

Windows questions are off topic here.


post edit, but WIN10IOT is not.

Heater
Posts: 9836
Joined: Tue Jul 17, 2012 3:02 pm

Re: question about line command argument

Fri Mar 02, 2018 6:19 pm

mahjongg,
Windows questions are off topic here.
Great.

Does that mean the "Windows 10 for IoT" section is going away?

Best news I have heard all day.

:)

User avatar
mahjongg
Forum Moderator
Forum Moderator
Posts: 10932
Joined: Sun Mar 11, 2012 12:19 am
Location: South Holland, The Netherlands

Re: question about line command argument

Mon Mar 05, 2018 10:37 am

Windows ≠ WIN10IOT

Heater
Posts: 9836
Joined: Tue Jul 17, 2012 3:02 pm

Re: question about line command argument

Mon Mar 05, 2018 11:57 am

mahjongg,
Windows ≠ WIN10IOT
Microsoft would like to disagree with you.

For example they advertise the Misty robot as "Windows-powered robot showcased at CES" on their developer web site: https://developer.microsoft.com/en-us/windows/iot

Or are you suggesting MS is lying to us?

You do at least need Win 10 to develop for WIN10IOT.

hippy
Posts: 3786
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: question about line command argument

Mon Mar 05, 2018 12:34 pm

Just because someone is developing their Python code on Windows it doesn't mean it's not intended for a Pi.

That's how I do all my Python development except when it actually needs access to things which only a Pi can provide, GPIO etc.

Is it a Windows question ? Is it "off topic" ? It looks to me to be a legitimate Python question; how to get the API key entered via a command line argument than having it embedded in the code.

Heater
Posts: 9836
Joined: Tue Jul 17, 2012 3:02 pm

Re: question about line command argument

Mon Mar 05, 2018 2:03 pm

I do agree Hippy. I often develop code on a PC or whatever machine and move it to the Pi later. Pi specific things can be "stubbed" or "mocked" for testing, just write some code that returns likely values where needed in the application to allow testing to proceed.

On the other hand this question now seems to be about file permissions, which are very different on Windows.

On the third hand this forum supports Windows on the Pi so I don't see why the question gets shrugged off.

@alipalru

Clearly you need to set the key and file names in the source code. Something like this:

Code: Select all

from base64 import b64encode
from os import makedirs
from os.path import join, basename
from sys import argv
import json
import requests

ENDPOINT_URL = 'https://vision.googleapis.com/v1/images:annotate'
RESULTS_DIR = 'jsons'
makedirs(RESULTS_DIR, exist_ok=True)

def make_image_data_list(image_filenames):
    """
    image_filenames is a list of filename strings
    Returns a list of dicts formatted as the Vision API
        needs them to be
    """
    img_requests = []
    for imgname in image_filenames:
        with open(imgname, 'rb') as f:
            ctxt = b64encode(f.read()).decode()
            img_requests.append({
                    'image': {'content': ctxt},
                    'features': [{
                        'type': 'TEXT_DETECTION',
                        'maxResults': 1
                    }]
            })
    return img_requests

def make_image_data(image_filenames):
    """Returns the image data lists as bytes"""
    imgdict = make_image_data_list(image_filenames)
    return json.dumps({"requests": imgdict }).encode()


def request_ocr(api_key, image_filenames):
    response = requests.post(ENDPOINT_URL,
                             data=make_image_data(image_filenames),
                             params={'key': 'AIzaSyBZILsRauBAu-be1WClq9kJZ0_w7w56XH8'},
                             headers={'Content-Type': 'application/json'})
    return response


if __name__ == '__main__':
    api_key = 'WHATEVERTHEAPIKEYIS'
    image_filenames = ['fileName1', 'fileName2', 'fileName3']
    response = request_ocr(api_key, image_filenames)
    if response.status_code != 200 or response.json().get('error'):
        print(response.text)
    else:
        for idx, resp in enumerate(response.json()['responses']):
            # save to JSON file
            imgname = image_filenames[idx]
            jpath = join(RESULTS_DIR, basename(imgname) + '.json')
            with open(jpath, 'w') as f:
                datatxt = json.dumps(resp, indent=2)
                print("Wrote", len(datatxt), "bytes to", jpath)
                f.write(datatxt)

            # print the plaintext to screen for convenience
            print("---------------------------------------------")
            t = resp['textAnnotations'][0]
            mensaje = t['description']
            print(mensaje[0:7])
[code]
In there I have also removed any use of the command line argv. Do excuse the syntax if it is wrong, I am no Python programmer.

Also I notice that in your original code  image_filenames was an array. But in your later code you have made it a string with:

[code]image_filenames = '/imagenes/patente.png'
Is that what you intended? I have tried to make an array of names in my example above, as one would get from argv.

As mentioned above to check you file path and permissions.

User avatar
mahjongg
Forum Moderator
Forum Moderator
Posts: 10932
Joined: Sun Mar 11, 2012 12:19 am
Location: South Holland, The Netherlands

Re: question about line command argument

Wed Mar 07, 2018 10:28 am

its simple:

If the question was about Windows, it doesn't belong here, but if the question was about WIN10IOT, it does, but it belongs in the WIN10IOT section.

moved the question again, from off-topic now to the WIN10IOT section.

Return to “Windows 10 for IoT”

Who is online

Users browsing this forum: No registered users and 2 guests