Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get_image api added #672

Merged
merged 6 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,14 @@ Or, for a local file:
"path_url": "/path/to/local/image.gif"
}

Windows example

.. code-block:: json

{
"path_url": "C:\\path\\to\\local\\image.gif"
}

Sample Response
^^^^^^^^^^^^^^^

Expand All @@ -413,6 +421,100 @@ A successful response with two extracted frames might look like this:
]
}

/api/get_image
===========================================

Overview
--------

A RESTful endpoint designed for retrieving an image. Clients can request a file by providing either the URL or the local file path of the image resource. The image is returned in JPEG format for efficient data transmission.

Endpoint Details
----------------

- **Endpoint Path**: ``/api/get_image``

Request
-------

- **Method**: GET
- **Request Data**:
- ``path_url`` (String): The URL or local file path of the image from to be opened.

Response
--------

- **Success**:

- Status Code: 200

- Body:

- ``image`` (String): A base64 encoded image in JPEG format.

- **Failure**:

- Status Code: 400 (Bad Request)

- When JSON decoding fails or the required attribute ``path_url`` is not provided.

- Status Code: 404 (Not Found)

- When the image at the specified URL or file path cannot be opened or processed.

Error Handling
--------------

In case of an error, the endpoint returns a JSON object with the following structure:

.. code-block:: json

{
"status": "failed",
"reason": "<error reason>"
}

Usage Example
-------------

Requesting Image
^^^^^^^^^^^^^^^^^^^^^

To request an image, send a GET request with either the URL or local file path in the request data:

.. code-block:: json

{
"path_url": "http://example.com/image.gif"
}

Or, for a local file:

.. code-block:: json

{
"path_url": "/path/to/local/image.gif"
}

Windows example

.. code-block:: json

{
"path_url": "C:\\path\\to\\local\\image.gif"
}

Sample Response
^^^^^^^^^^^^^^^

A successful response with image data might look like this:

.. code-block:: json

{
"image": "<base64-encoded JPEG data>"
}

/api/effects
=========================

Expand Down
4 changes: 2 additions & 2 deletions ledfx/api/get_gif_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@ async def get(self, request: web.Request) -> web.Response:
)
frames.append(encoded_frame)

response = {"frame_count": len(frames), "frames": frames}
response = {"status": "success", "frame_count": len(frames), "frames": frames}

return web.json_response(data=response, status=200)
return await self.bare_request_success(response)
59 changes: 59 additions & 0 deletions ledfx/api/get_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import io
import logging
from json import JSONDecodeError

import pybase64
from aiohttp import web

from ledfx.api import RestEndpoint
from ledfx.utils import open_image

_LOGGER = logging.getLogger(__name__)


class GetImageEndpoint(RestEndpoint):
ENDPOINT_PATH = "/api/get_image"

async def get(self, request: web.Request) -> web.Response:
"""Open image and return as base64 encoded string

Args:
request (web.Request): The request object containing the `path_url` to open.

Returns:
web.Response: The HTTP response object containing the base64 encoded image.
"""
try:
data = await request.json()
except JSONDecodeError:
return await self.json_decode_error()

path_url = data.get("path_url")

if path_url is None:
return await self.invalid_request(
'Required attribute "path_url" was not provided'
)

_LOGGER.info(f"GetImageEndpoint from {path_url}")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved

image = open_image(path_url)

if not image:
return await self.invalid_request(
f"Failed to open GIF image from: {path_url}"
)

with io.BytesIO() as output:
# we don't care about a bit of loss, so encode to JPEG
# in example test 5x+ data saving 600kb - > 112 kb
image.convert("RGB").save(
output, format="JPEG"
) # Convert frame to JPEG
encoded_frame = pybase64.b64encode(output.getvalue()).decode(
"utf-8"
)

response = {"status": "success", "image": encoded_frame}

return await self.bare_request_success(response)
27 changes: 27 additions & 0 deletions ledfx/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,33 @@ def open_gif(gif_path):
return None


def open_image(image_path):
"""
Open an image from a local file or url

Args:
image_path: str
path to image file or url
Returns:
Image: PIL Image object or None if failed to open
"""
_LOGGER.info(f"Attempting to open image: {image_path}")
try:
if image_path.startswith("http://") or image_path.startswith("https://"):
with urllib.request.urlopen(image_path) as url:
image = Image.open(url)
_LOGGER.info("image downloaded and opened.")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved
return image

else:
image = Image.open(image_path) # Directly open for local files
_LOGGER.info("Image opened.")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved
return image
except Exception as e:
_LOGGER.warning(f"Failed to open image : {image_path} : {e}")
bigredfrog marked this conversation as resolved.
Show resolved Hide resolved
return None

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The open_image function lacks error handling for specific exceptions, such as HTTPError for URL issues or FileNotFoundError for local file issues. This can help provide more detailed logs for troubleshooting.

try {
    if image_path.startswith("http://") or image_path.startswith("https://"):
        with urllib.request.urlopen(image_path) as url:
            image = Image.open(url)
            _LOGGER.info("Image downloaded and opened.")
            return image
    else:
        image = Image.open(image_path)  # Directly open for local files
        _LOGGER.info("Image opened.")
        return image
- } except Exception as e {
+ } except (FileNotFoundError, urllib.error.HTTPError) as e {
    _LOGGER.warning(f"Failed to open image : {image_path} : {e}")
    return None

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def open_image(image_path):
"""
Open an image from a local file or url
Args:
image_path: str
path to image file or url
Returns:
Image: PIL Image object or None if failed to open
"""
_LOGGER.info(f"Attempting to open image: {image_path}")
try:
if image_path.startswith("http://") or image_path.startswith("https://"):
with urllib.request.urlopen(image_path) as url:
image = Image.open(url)
_LOGGER.info("image downloaded and opened.")
return image
else:
image = Image.open(image_path) # Directly open for local files
_LOGGER.info("Image opened.")
return image
except Exception as e:
_LOGGER.warning(f"Failed to open image : {image_path} : {e}")
return None
def open_image(image_path):
"""
Open an image from a local file or url
Args:
image_path: str
path to image file or url
Returns:
Image: PIL Image object or None if failed to open
"""
_LOGGER.info(f"Attempting to open image: {image_path}")
try:
if image_path.startswith("http://") or image_path.startswith("https://"):
with urllib.request.urlopen(image_path) as url:
image = Image.open(url)
_LOGGER.info("image downloaded and opened.")
return image
else:
image = Image.open(image_path) # Directly open for local files
_LOGGER.info("Image opened.")
return image
except (FileNotFoundError, urllib.error.HTTPError) as e:
_LOGGER.warning(f"Failed to open image : {image_path} : {e}")
return None

The function open_image uses a broad Exception catch which might suppress unexpected errors, making debugging harder. It's better to catch specific exceptions.

Consider catching specific exceptions such as IOError for file access issues and urllib.error.URLError for URL problems, to provide more targeted error handling and logging.


The logging within open_image uses a generic message for both successful openings and failures. It would be beneficial to differentiate between opening a local file and downloading an image from a URL for clearer logs.

if image_path.startswith("http://") or image_path.startswith("https://"):
    with urllib.request.urlopen(image_path) as url:
        image = Image.open(url)
-       _LOGGER.info("Image downloaded and opened.")
+       _LOGGER.info(f"Image from URL '{image_path}' downloaded and opened.")
else:
    image = Image.open(image_path)  # Directly open for local files
-   _LOGGER.info("Image opened.")
+   _LOGGER.info(f"Local image '{image_path}' opened.")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
def open_image(image_path):
"""
Open an image from a local file or url
Args:
image_path: str
path to image file or url
Returns:
Image: PIL Image object or None if failed to open
"""
_LOGGER.info(f"Attempting to open image: {image_path}")
try:
if image_path.startswith("http://") or image_path.startswith("https://"):
with urllib.request.urlopen(image_path) as url:
image = Image.open(url)
_LOGGER.info("image downloaded and opened.")
return image
else:
image = Image.open(image_path) # Directly open for local files
_LOGGER.info("Image opened.")
return image
except Exception as e:
_LOGGER.warning(f"Failed to open image : {image_path} : {e}")
return None
def open_image(image_path):
"""
Open an image from a local file or url
Args:
image_path: str
path to image file or url
Returns:
Image: PIL Image object or None if failed to open
"""
_LOGGER.info(f"Attempting to open image: {image_path}")
try:
if image_path.startswith("http://") or image_path.startswith("https://"):
with urllib.request.urlopen(image_path) as url:
image = Image.open(url)
_LOGGER.info(f"Image from URL '{image_path}' downloaded and opened.")
return image
else:
image = Image.open(image_path) # Directly open for local files
_LOGGER.info(f"Local image '{image_path}' opened.")
return image
except Exception as e:
_LOGGER.warning(f"Failed to open image : {image_path} : {e}")
return None


def get_mono_font(size):
"""
Get a monospace font from a list of fonts common across platforms
Expand Down
Loading